diff --git a/.agents/skills/lancedb-vector-dedup/SKILL.md b/.agents/skills/lancedb-vector-dedup/SKILL.md new file mode 100644 index 000000000..1221e4061 --- /dev/null +++ b/.agents/skills/lancedb-vector-dedup/SKILL.md @@ -0,0 +1,63 @@ +--- +name: lancedb-vector-dedup +description: Plan and run Enterprise IVF vector deduplication with dedupe and duplicate_pairs, including sampling, index coverage, recall and resource limits. Use for near-duplicate embedding or perceptual-hash records; use MinHash guidance for text shingles. +--- + +# Vector deduplication + +Read the maintained [workflow](../../../docs/web/curation/dedupe.mdx), +[DEDUPE reference](../../../docs/web/sql/dql/dedupe.mdx) and +[DUPLICATE_PAIRS reference](../../../docs/web/sql/dql/duplicate-pairs.mdx) +before constructing SQL. In a source checkout these paths are relative to this +skill directory. When using an installed copy without the docs, read +`https://docs.lancedb.com/curation/dedupe` and the linked SQL references. + +## Establish the comparison contract + +- Confirm an Enterprise deployment that supports these table functions. Use + `dedupe` and `duplicate_pairs`; legacy `vector_dedup` names are rejected. +- Inspect the vector type, metric, compatible index, indexed fragments and + source version. Wait for index coverage after writes. Do not run a full + scan over unindexed fragments or silently change the index to make it run. +- Explain that candidates are compared only within physical IVF partitions + and segments. Encoded/quantized distances are not an exact raw-vector + comparison. L2 thresholds are squared distances; Hamming counts bits. +- Use `id_column` on pair queries for business IDs. Retain `dataset_version`, + segment and partition identities. Do not decode internal row IDs or assume + that representatives stay the same after later data/index changes. + +## Bound the first experiment + +Use a reproducible partition sample before a full scan: + +```sql +SELECT id_a, id_b, distance, dataset_version, segment_id, partition_id +FROM duplicate_pairs( + 'frames', 'embedding', + distance_threshold => 0.02, + id_column => 'frame_id', + selection => 'random', count => 10, seed => 42 +) +``` + +Adapt the threshold and sample size to the metric and actual partition count. +Sampling partitions is not uniform sampling of rows. Inspect known duplicate +and distinct examples, pair density, partition skew, memory, spill space and +elapsed time. Do not infer global recall or ten-billion-row qualification +from a small or unversioned benchmark. Pair work and output can be quadratic +within a partition; an outer SQL `LIMIT` is not an upstream work budget. + +## Choose the result + +`dedupe` returns original representative rows and always scans all partitions. +Use its default `connected_components` for transitive groups; choose +`direct_representative` when chains should not merge transitively. It does not +accept `id_column`, `selection`, `count` or `seed`; `duplicate_pairs` does not +accept `resolution`. + +Keep pair data on the server when possible; avoid collecting an unbounded +edge set in client memory. Persist a new table/view only within the user's +authorized scope, preserving source rows unless deletion was requested. +Do not register a Python Function or fetch/rewrite Blob payloads to invoke +these built-in table functions. For MinHash/text deduplication, follow the +separate `https://docs.lancedb.com/enterprise/sql-minhash` workflow. diff --git a/.bumpversion.toml b/.bumpversion.toml index bfeaaf02f..fec283ac1 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.4" +current_version = "0.42.0-beta.37" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. @@ -23,31 +23,6 @@ allow_dirty = true commit = true message = "Bump version: {current_version} → {new_version}" commit_args = "" -# bump-my-version >=1.4.0 rejects pre_commit_hooks containing shell syntax unless opted in. -allow_shell_hooks = true - -# Java maven files -pre_commit_hooks = [ - """ - NEW_VERSION="${BVHOOK_NEW_MAJOR}.${BVHOOK_NEW_MINOR}.${BVHOOK_NEW_PATCH}" - if [ ! -z "$BVHOOK_NEW_PRE_L" ] && [ ! -z "$BVHOOK_NEW_PRE_N" ]; then - NEW_VERSION="${NEW_VERSION}-${BVHOOK_NEW_PRE_L}.${BVHOOK_NEW_PRE_N}" - fi - echo "Constructed new version: $NEW_VERSION" - cd java && mvn versions:set -DnewVersion=$NEW_VERSION && mvn versions:commit - - # Check for any modified but unstaged pom.xml files - MODIFIED_POMS=$(git ls-files -m | grep pom.xml) - if [ ! -z "$MODIFIED_POMS" ]; then - echo "The following pom.xml files were modified but not staged. Adding them now:" - echo "$MODIFIED_POMS" | while read -r file; do - git add "$file" - echo "Added: $file" - done - fi - """, -] - [tool.bumpversion.parts.pre_l] optional_value = "final" values = ["beta", "final"] @@ -87,7 +62,17 @@ filename = "python/Cargo.toml" replace = "\nversion = \"{new_version}\"" search = "\nversion = \"{current_version}\"" -# Java documentation +# Java Maven coordinates and documentation +[[tool.bumpversion.files]] +filename = "java/pom.xml" +search = "lancedb-parent\n {current_version}" +replace = "lancedb-parent\n {new_version}" + +[[tool.bumpversion.files]] +filename = "java/lancedb-core/pom.xml" +search = "lancedb-parent\n {current_version}" +replace = "lancedb-parent\n {new_version}" + [[tool.bumpversion.files]] filename = "docs/src/java/java.md" replace = "{new_version}" diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index f5d93eb0a..a7efa1682 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -7,7 +7,10 @@ "plugins": [ { "name": "lancedb", - "source": "./plugins/lancedb", + "source": { + "source": "github", + "repo": "lancedb/lancedb-agent-plugins" + }, "description": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work with both LanceDB Embedded and LanceDB Enterprise.", "version": "0.1.0", "author": { diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d625b0698..4f5ff4bd4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,70 +1,145 @@ version: 2 -# Scope: the root Cargo workspace, which produces the Rust binaries we -# ship to users (the Node.js and Python native extensions). The -# `rust/lancedb` library crate shares the same lockfile; its consumers -# pick their own dependency versions, but bumping transitive deps here -# keeps the binaries we ship current. +# Every entry uses `versioning-strategy: lockfile-only`: bump the lockfile, +# never widen or raise the version requirements in manifests. Those ranges are +# our library consumers' constraints, not ours. +# +# Because of that, version updates are limited to minor and patch bumps. +# A semver-breaking bump (including 0.x minor bumps such as 0.12 -> 0.13) +# can't be satisfied without editing a manifest, so Dependabot would produce a +# lockfile that fails `cargo --locked` and every CI job. We do those by hand. +# This is done with `allow` rather than `ignore` because `allow.update-types` +# only filters version updates; an `ignore` rule would also suppress security +# updates. `dependency-type: all` matters for the same reason: `allow` does +# apply to security updates otherwise, and most advisories are in transitive +# dependencies. +# +# Security updates are grouped so advisories that land together become one PR. +# They ignore `schedule` and `cooldown` and are opened as soon as an advisory +# is published. updates: + # Highest priority: the root Cargo workspace is statically linked into the + # Node.js and Python native extensions we ship, so users can't patch these + # themselves. Weekly updates keep the lockfile close to current, so security + # fixes are usually small patch bumps. - package-ecosystem: cargo directory: / schedule: interval: weekly - open-pull-requests-limit: 10 - # Only update Cargo.lock, never widen/raise the version requirements in - # Cargo.toml. The goal is keeping the lockfile (and the binaries we ship) - # current on security fixes, not forcing our library's consumers onto - # newer minimum versions. + day: wednesday + cooldown: + default-days: 2 versioning-strategy: lockfile-only - groups: - # The arrow-rs and datafusion crates are released in lockstep and have to - # move together, so keep them in one PR instead of one per sub-crate. - # Listed first: a dependency joins the first group it matches. - arrow-datafusion: - patterns: - - arrow - - arrow-* - - parquet - - parquet-* - - datafusion - - datafusion-* - - object_store - rust-minor-patch: + allow: + - dependency-type: all update-types: - - minor - - patch + - version-update:semver-minor + - version-update:semver-patch + groups: + cargo: + applies-to: version-updates + patterns: + - "*" + cargo-security: + applies-to: security-updates + patterns: + - "*" - - package-ecosystem: pip + # Python and Node.js dependencies are resolved in the user's own environment, + # so these lockfiles only affect our dev/test setup. Lower priority: monthly. + - package-ecosystem: uv directory: /python schedule: - interval: weekly - # Only update uv.lock, never widen version requirements in pyproject.toml. + interval: monthly + cooldown: + default-days: 2 versioning-strategy: lockfile-only + allow: + - dependency-type: all + update-types: + - version-update:semver-minor + - version-update:semver-patch groups: - python-deps: + python: + applies-to: version-updates patterns: - "*" - - # The npm ecosystem covers pnpm lockfiles. There are two separate installs: - # the bindings themselves and the examples, which have their own lockfile. - # As with cargo and pip above, only bump the lockfile — the version ranges - # in package.json are our consumers' constraints, not ours. - - package-ecosystem: npm - directory: /nodejs - schedule: - interval: weekly - versioning-strategy: lockfile-only - groups: - nodejs-deps: + python-security: + applies-to: security-updates patterns: - "*" - package-ecosystem: npm - directory: /nodejs/examples + directories: + - /nodejs + - /nodejs/examples schedule: - interval: weekly + interval: monthly + cooldown: + default-days: 2 versioning-strategy: lockfile-only + allow: + - dependency-type: all + update-types: + - version-update:semver-minor + - version-update:semver-patch groups: - nodejs-examples-deps: + nodejs: + applies-to: version-updates + patterns: + - "*" + nodejs-security: + applies-to: security-updates + patterns: + - "*" + + # Docs, docs tests, and Java. Security updates scan these lockfiles whether or + # not they're listed here; these entries only exist to group those PRs. + # `open-pull-requests-limit: 0` turns off version updates. + - package-ecosystem: cargo + directory: /docs/web-tests/rs + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-cargo-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: npm + directories: + - /docs/web-tests/ts + - /docs/web-tests/blob-v2/ts + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-npm-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: pip + directories: + - /docs + - /docs/web-tests/blob-v2/py + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-pip-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: maven + directory: /java + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + maven-security: + applies-to: security-updates patterns: - "*" diff --git a/.github/vale/README.md b/.github/vale/README.md index 94a11bfd8..faa302c33 100644 --- a/.github/vale/README.md +++ b/.github/vale/README.md @@ -10,7 +10,7 @@ come from the `LanceDB.zip` asset of `lancedb/docs` release The product-terminology rules were added here: `EmbeddedName`, `RemoteExecution`, `OSSProduct`, `InternalNames` (warnings) and `LegacyCloud` (suggestion). They enforce the names in the -docs repository's `STYLE.md#names`. Run every rule's tests from +[style guide](../../docs/STYLE.md#names). Run every rule's tests from `.github/vale` with `vale test --coverage styles`. Keeping the rules here lets contributors and CI run Vale without access to the diff --git a/.github/vale/styles/LanceDB/Dashes.yml b/.github/vale/styles/LanceDB/Dashes.yml index 7bb10c96f..f80829c9a 100644 --- a/.github/vale/styles/LanceDB/Dashes.yml +++ b/.github/vale/styles/LanceDB/Dashes.yml @@ -1,6 +1,6 @@ extends: existence message: "Avoid '%s' in prose. Use a comma, a colon, parentheses or two sentences." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#punctuation +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#punctuation level: warning nonword: true # An em dash in prose, and a double hyphen or en dash used as one, with a diff --git a/.github/vale/styles/LanceDB/EmbeddedName.yml b/.github/vale/styles/LanceDB/EmbeddedName.yml index a372c8a04..d4f01c1e2 100644 --- a/.github/vale/styles/LanceDB/EmbeddedName.yml +++ b/.github/vale/styles/LanceDB/EmbeddedName.yml @@ -1,6 +1,6 @@ extends: substitution message: "Use '%s' instead of '%s'." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names level: warning ignorecase: false # The in-process execution model is LanceDB Embedded, whether the data is on diff --git a/.github/vale/styles/LanceDB/InternalNames.yml b/.github/vale/styles/LanceDB/InternalNames.yml index 0818090e1..6be384ffb 100644 --- a/.github/vale/styles/LanceDB/InternalNames.yml +++ b/.github/vale/styles/LanceDB/InternalNames.yml @@ -1,6 +1,6 @@ extends: substitution message: "Use '%s' instead of the internal name '%s'." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names level: warning ignorecase: false # Internal component names stay out of public text. Environment variables such diff --git a/.github/vale/styles/LanceDB/LegacyCloud.yml b/.github/vale/styles/LanceDB/LegacyCloud.yml index 932b7a7db..ab1940718 100644 --- a/.github/vale/styles/LanceDB/LegacyCloud.yml +++ b/.github/vale/styles/LanceDB/LegacyCloud.yml @@ -1,6 +1,6 @@ extends: existence message: "'%s' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise'." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names level: suggestion ignorecase: false # A suggestion, because `db://` URIs, `api_key` and `region` for the hosted diff --git a/.github/vale/styles/LanceDB/OSSProduct.yml b/.github/vale/styles/LanceDB/OSSProduct.yml index 248129208..17ff80abc 100644 --- a/.github/vale/styles/LanceDB/OSSProduct.yml +++ b/.github/vale/styles/LanceDB/OSSProduct.yml @@ -1,6 +1,6 @@ extends: existence message: "Avoid '%s'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names level: warning ignorecase: false # Bare OSS used as a product, as in "OSS and Enterprise" or "in OSS". "LanceDB diff --git a/.github/vale/styles/LanceDB/PlainLanguage.yml b/.github/vale/styles/LanceDB/PlainLanguage.yml index 563e834e2..f843da9df 100644 --- a/.github/vale/styles/LanceDB/PlainLanguage.yml +++ b/.github/vale/styles/LanceDB/PlainLanguage.yml @@ -1,6 +1,6 @@ extends: substitution message: "Consider '%s' instead of '%s'." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#say-it-directly +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#say-it-directly level: suggestion ignorecase: true # Keep this list small. Technical nouns such as GPU utilization stay intact. diff --git a/.github/vale/styles/LanceDB/ProductNames.yml b/.github/vale/styles/LanceDB/ProductNames.yml index 42cde9869..97fe18526 100644 --- a/.github/vale/styles/LanceDB/ProductNames.yml +++ b/.github/vale/styles/LanceDB/ProductNames.yml @@ -1,6 +1,6 @@ extends: substitution message: "Use '%s' instead of '%s'." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names level: warning ignorecase: false # Case-sensitive. A lowercase package, repository or domain name, such as diff --git a/.github/vale/styles/LanceDB/RemoteExecution.yml b/.github/vale/styles/LanceDB/RemoteExecution.yml index ccff9e926..278359250 100644 --- a/.github/vale/styles/LanceDB/RemoteExecution.yml +++ b/.github/vale/styles/LanceDB/RemoteExecution.yml @@ -1,6 +1,6 @@ extends: existence message: "Avoid '%s'. Write 'LanceDB Enterprise' and describe where the operation runs directly." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names level: warning ignorecase: false # Remote storage, remote URLs and a git remote are other things and stay. Class diff --git a/.github/vale/styles/LanceDB/VagueHeadings.yml b/.github/vale/styles/LanceDB/VagueHeadings.yml index e100891b0..b94438361 100644 --- a/.github/vale/styles/LanceDB/VagueHeadings.yml +++ b/.github/vale/styles/LanceDB/VagueHeadings.yml @@ -1,6 +1,6 @@ extends: existence message: "'%s' doesn't say what the section covers. Name the task or topic instead." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#headings +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#headings level: suggestion scope: heading ignorecase: true diff --git a/.github/vale/styles/LanceDB/VaguePhrases.yml b/.github/vale/styles/LanceDB/VaguePhrases.yml index 43d00f9e0..640511140 100644 --- a/.github/vale/styles/LanceDB/VaguePhrases.yml +++ b/.github/vale/styles/LanceDB/VaguePhrases.yml @@ -1,6 +1,6 @@ extends: existence message: "'%s' talks about the writing, not the subject. State the point directly." -link: https://github.com/lancedb/docs/blob/main/STYLE.md#say-it-directly +link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#say-it-directly level: suggestion ignorecase: false scope: sentence diff --git a/.github/workflows/build_linux_wheel/action.yml b/.github/workflows/build_linux_wheel/action.yml index 44ce82ee5..51cd20ab0 100644 --- a/.github/workflows/build_linux_wheel/action.yml +++ b/.github/workflows/build_linux_wheel/action.yml @@ -54,7 +54,7 @@ runs: grep '^name = ' python/pyproject.toml - name: Build x86_64 Manylinux wheel if: ${{ inputs.arm-build == 'false' }} - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: build @@ -72,7 +72,7 @@ runs: /usr/local/bin/protoc --version - name: Build Arm Manylinux Wheel if: ${{ inputs.arm-build == 'true' }} - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: build diff --git a/.github/workflows/build_mac_wheel/action.yml b/.github/workflows/build_mac_wheel/action.yml index 727cd190c..ba7b7b1c5 100644 --- a/.github/workflows/build_mac_wheel/action.yml +++ b/.github/workflows/build_mac_wheel/action.yml @@ -14,7 +14,7 @@ runs: steps: - uses: ./.github/actions/setup-protoc - name: Build wheel - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build maturin-version: "1.12.4" diff --git a/.github/workflows/build_windows_wheel/action.yml b/.github/workflows/build_windows_wheel/action.yml index 954ee7d35..0d061ac59 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -12,9 +12,12 @@ inputs: runs: using: "composite" steps: + - name: Enable long paths for Lance dependencies + shell: bash + run: git config --global core.longpaths true - uses: ./.github/actions/setup-protoc - name: Build wheel - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build maturin-version: "1.12.4" diff --git a/.github/workflows/cargo-publish.yml b/.github/workflows/cargo-publish.yml index 052fb1876..83593307b 100644 --- a/.github/workflows/cargo-publish.yml +++ b/.github/workflows/cargo-publish.yml @@ -25,14 +25,14 @@ jobs: if: startsWith(github.ref, 'refs/tags/v') steps: - uses: actions/checkout@v6 - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: rust - name: Install dependencies run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rust-lang/crates-io-auth-action@v1 + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - name: Publish the package run: | diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml index c8c4d0998..5f0cc7511 100644 --- a/.github/workflows/ci-scripts.yml +++ b/.github/workflows/ci-scripts.yml @@ -12,6 +12,7 @@ on: - ci/extract_sdk_doc_links.py - ci/build_cli_linux.sh - ci/package_cli.py + - ci/update_homebrew_formula.py - .bumpversion.toml - rust/lancedb/cli/Cargo.toml - ci/set_lance_version.py @@ -26,6 +27,7 @@ on: - ci/extract_sdk_doc_links.py - ci/build_cli_linux.sh - ci/package_cli.py + - ci/update_homebrew_formula.py - .bumpversion.toml - rust/lancedb/cli/Cargo.toml - ci/set_lance_version.py diff --git a/.github/workflows/cli-installer.yml b/.github/workflows/cli-installer.yml new file mode 100644 index 000000000..92dbfe9a7 --- /dev/null +++ b/.github/workflows/cli-installer.yml @@ -0,0 +1,32 @@ +name: CLI shell installer +on: + pull_request: + paths: + - 'scripts/install.sh' + - 'ci/tests/test_cli_installer.sh' + - '.github/workflows/cli-installer.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + install: + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, ubuntu-24.04-arm, macos-15] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - run: sh ci/tests/test_cli_installer.sh + - name: Install a pinned public release and run it + env: + LANCEDB_VERSION: v0.42.0-beta.19 + run: | + export LANCEDB_INSTALL_DIR="$RUNNER_TEMP/cli bin" + sh scripts/install.sh + test "$("$LANCEDB_INSTALL_DIR/lancedb" --version)" = "lancedb ${LANCEDB_VERSION#v}" + "$LANCEDB_INSTALL_DIR/lancedb" profile list diff --git a/.github/workflows/cli-wheels.yml b/.github/workflows/cli-wheels.yml new file mode 100644 index 000000000..490a5d24d --- /dev/null +++ b/.github/workflows/cli-wheels.yml @@ -0,0 +1,68 @@ +name: CLI Python wheels + +on: + pull_request: + paths: + - ci/cli_wheel/** + - ci/build_cli_wheels.py + - ci/package_cli.py + - .github/workflows/cli-wheels.yml + workflow_dispatch: + inputs: + tag: + description: Published CLI release to package + required: true + default: v0.42.0-beta.30 + +permissions: + contents: read + +env: + CLI_TAG: ${{ inputs.tag || 'v0.42.0-beta.30' }} + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - run: python -m pip install wheel==0.48.0 + - name: Build wheels from published release archives + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release download --repo lancedb/lancedb --dir archives \ + --pattern 'lancedb-*.tar.gz' --pattern SHA256SUMS -- "$CLI_TAG" + python -m ci.build_cli_wheels "$CLI_TAG" archives wheels + - uses: actions/upload-artifact@v7 + with: + name: lancedb-tools-wheels + path: wheels/*.whl + if-no-files-found: error + compression-level: 0 + + install: + needs: build + strategy: + fail-fast: false + matrix: + os: [macos-15, ubuntu-24.04, ubuntu-24.04-arm] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - uses: actions/download-artifact@v8 + with: + name: lancedb-tools-wheels + path: wheels + - run: python -m pip install uv==0.13.9 pipx==1.19.0 + - name: Install and exercise the native CLI with uvx and pipx + run: bash ci/cli_wheel/test_install.sh "$CLI_TAG" "$PWD/wheels" diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml index 8d8763e1d..e96d5b095 100644 --- a/.github/workflows/cli.yml +++ b/.github/workflows/cli.yml @@ -23,6 +23,8 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1 with: components: clippy + # Use only the downloads-only cache configured below. + cache: false - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: # Restoring compiled targets can exhaust the hosted runner disk. diff --git a/.github/workflows/codex-update-lance-dependency.yml b/.github/workflows/codex-update-lance-dependency.yml index 79ef84364..1d1890efb 100644 --- a/.github/workflows/codex-update-lance-dependency.yml +++ b/.github/workflows/codex-update-lance-dependency.yml @@ -16,14 +16,14 @@ on: default: "" type: string -permissions: - contents: write - pull-requests: write - actions: read +permissions: {} jobs: update: runs-on: ubuntu-latest + permissions: + # Pushes the branch with the checkout token. PR creation uses ROBOT_TOKEN. + contents: write steps: - name: Show inputs run: | @@ -44,7 +44,7 @@ jobs: run: npm install -g @openai/codex - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: toolchain: stable components: clippy, rustfmt diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index eac4cc4fc..64a6971e6 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -18,7 +18,7 @@ jobs: name: Label PR runs-on: ubuntu-latest steps: - - uses: srvaroa/labeler@v1 + - uses: srvaroa/labeler@9c29ad1ef33d169f9ef33c52722faf47a566bcf3 # v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} commitlint: @@ -30,7 +30,7 @@ jobs: - uses: actions/setup-node@v6 with: node-version: "24" - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 # These rules are disabled because Github will always ensure there diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index fb3fb1d6a..9de5d9176 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -27,12 +27,10 @@ env: PIP_EXTRA_INDEX_URL: "https://pypi.fury.io/lance-format/ https://pypi.fury.io/lancedb/" jobs: - # Single deploy job since we're just deploying build: - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-24.04 + outputs: + artifact_name: ${{ steps.artifact-name.outputs.name }} steps: - name: Checkout uses: actions/checkout@v6 @@ -44,10 +42,10 @@ jobs: - name: Set up Python uses: actions/setup-python@v6 with: - python-version: "3.10" + python-version: "3.11" cache: "pip" cache-dependency-path: "docs/requirements.txt" - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Build Python working-directory: python run: | @@ -68,10 +66,28 @@ jobs: PYTHONPATH=. mkdocs build - name: Setup Pages uses: actions/configure-pages@v5 + - name: Set artifact name + id: artifact-name + run: echo "name=github-pages-${{ github.run_id }}-${{ github.run_attempt }}" >> "$GITHUB_OUTPUT" - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: + name: ${{ steps.artifact-name.outputs.name }} path: "docs/site" + + # Deploy from a separate job so the Pages artifact upload has settled before + # the deploy action looks it up. The per-run name keeps a full workflow + # re-run from accumulating artifacts that share the default name. + deploy: + name: Deploy to GitHub Pages + needs: build + runs-on: ubuntu-24.04 + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 + with: + artifact_name: ${{ needs.build.outputs.artifact_name }} diff --git a/.github/workflows/gh-release.yml b/.github/workflows/gh-release.yml index bbaade34c..5961f444c 100644 --- a/.github/workflows/gh-release.yml +++ b/.github/workflows/gh-release.yml @@ -19,6 +19,8 @@ jobs: gh-release: needs: cli runs-on: ubuntu-latest + outputs: + prerelease: ${{ steps.extract_version.outputs.prerelease }} permissions: contents: write steps: @@ -77,7 +79,7 @@ jobs: echo "from_tag=$FROM_TAG" >> $GITHUB_OUTPUT - name: Create Release Notes id: release_notes - uses: mikepenz/release-changelog-builder-action@v4 + uses: mikepenz/release-changelog-builder-action@32e3c96f29a6532607f638797455e9e98cfc703d # v4.2.2 with: configuration: .github/release_notes.json toTag: ${{ steps.extract_version.outputs.tag }} @@ -85,7 +87,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Create GH release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2 with: # Marking betas as pre-releases keeps them from taking the "Latest" # badge on the releases page. @@ -102,9 +104,58 @@ jobs: fail_on_unmatched_files: true overwrite_files: true + homebrew: + name: Open Homebrew formula PR + needs: gh-release + if: github.repository == 'lancedb/lancedb' && needs.gh-release.outputs.prerelease == 'false' + runs-on: ubuntu-24.04 + environment: homebrew-tap + concurrency: homebrew-tap-${{ github.ref_name }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: lancedb/homebrew-tap + ref: main + path: tap + persist-credentials: false + - name: Update formula from the published checksums + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release download "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" \ + --pattern SHA256SUMS --dir "$RUNNER_TEMP" + python3 -m ci.update_homebrew_formula "$GITHUB_REF_NAME" \ + "$RUNNER_TEMP/SHA256SUMS" tap/Formula/lancedb.rb + - name: Create tap installation token + id: app + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + client-id: ${{ vars.HOMEBREW_TAP_APP_CLIENT_ID }} + private-key: ${{ secrets.HOMEBREW_TAP_APP_PRIVATE_KEY }} + owner: lancedb + repositories: homebrew-tap + permission-contents: write + permission-pull-requests: write + - name: Open or update the tap PR + uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3 + with: + path: tap + token: ${{ steps.app.outputs.token }} + base: main + branch: release/lancedb-${{ github.ref_name }} + add-paths: Formula/lancedb.rb + commit-message: Update LanceDB CLI to ${{ github.ref_name }} + title: Update LanceDB CLI to ${{ github.ref_name }} + body: | + Update the formula to [${{ github.ref_name }}](https://github.com/lancedb/lancedb/releases/tag/${{ github.ref_name }}) using its published SHA256SUMS. + Review and merge after the tap's install tests pass. + report-failure: runs-on: ubuntu-24.04 - needs: [cli, gh-release] + needs: [cli, gh-release, homebrew] if: always() && failure() permissions: contents: read diff --git a/.github/workflows/java-publish.yml b/.github/workflows/java-publish.yml index 094aa552a..35d052de9 100644 --- a/.github/workflows/java-publish.yml +++ b/.github/workflows/java-publish.yml @@ -39,9 +39,11 @@ jobs: distribution: temurin java-version: 8 cache: "maven" - server-id: ossrh - server-username: SONATYPE_USER - server-password: SONATYPE_TOKEN + # Betas go to Fury and stable releases to Maven Central, which limits + # how many releases an organization may publish each month. + server-id: ${{ contains(github.ref, 'beta') && 'fury' || 'ossrh' }} + server-username: ${{ contains(github.ref, 'beta') && 'FURY_TOKEN' || 'SONATYPE_USER' }} + server-password: ${{ contains(github.ref, 'beta') && 'FURY_PASSWORD' || 'SONATYPE_TOKEN' }} gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} gpg-passphrase: MAVEN_GPG_PASSPHRASE - name: Set git config @@ -52,8 +54,16 @@ jobs: if: github.event_name == 'pull_request' run: | ./mvnw --batch-mode -DskipTests package -pl lancedb-core -am - - name: Publish - if: startsWith(github.ref, 'refs/tags/v') + - name: Publish to Fury + if: startsWith(github.ref, 'refs/tags/v') && contains(github.ref, 'beta') + run: | + ./mvnw --batch-mode -DskipTests deploy -pl lancedb-core -am -P deploy-to-fury + env: + FURY_TOKEN: ${{ secrets.FURY_TOKEN }} + # Fury authenticates with the token as the username; the password is ignored. + FURY_PASSWORD: NOPASS + - name: Publish to Maven Central + if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, 'beta') run: | echo "use-agent" >> ~/.gnupg/gpg.conf echo "pinentry-mode loopback" >> ~/.gnupg/gpg.conf diff --git a/.github/workflows/license-header-check.yml b/.github/workflows/license-header-check.yml index 8b8510b58..904eea2c4 100644 --- a/.github/workflows/license-header-check.yml +++ b/.github/workflows/license-header-check.yml @@ -21,11 +21,10 @@ jobs: steps: - name: Check out code uses: actions/checkout@v6 + # `go install` at a fixed version is verified against the Go checksum database. - name: Install license-header-checker - working-directory: /tmp run: | - curl -s https://raw.githubusercontent.com/lluissm/license-header-checker/master/install.sh | bash - mv /tmp/bin/license-header-checker /usr/local/bin/ + GOBIN=/usr/local/bin go install github.com/lluissm/license-header-checker/cmd/license-header-checker@v1.5.0 - name: Check license headers (rust) run: license-header-checker -a -v ./rust/license_header.txt ./ rs && [[ -z `git status -s` ]] - name: Check license headers (python) diff --git a/.github/workflows/make-release-commit.yml b/.github/workflows/make-release-commit.yml index c7187a6c7..a35bff7f1 100644 --- a/.github/workflows/make-release-commit.yml +++ b/.github/workflows/make-release-commit.yml @@ -39,7 +39,9 @@ jobs: contents: write steps: - name: Output Inputs - run: echo "${{ toJSON(github.event.inputs) }}" + env: + INPUTS_JSON: ${{ toJSON(github.event.inputs) }} + run: echo "$INPUTS_JSON" - uses: actions/checkout@v6 with: fetch-depth: 0 @@ -59,9 +61,11 @@ jobs: - name: Bump version env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TYPE: ${{ inputs.type }} + BUMP_MINOR: ${{ inputs.bump-minor }} run: | pip install bump-my-version PyGithub packaging - bash ci/bump_version.sh ${{ inputs.type }} ${{ inputs.bump-minor }} + bash ci/bump_version.sh "$RELEASE_TYPE" "$BUMP_MINOR" release_tag=$(git describe --tags --exact-match HEAD) bash ci/update_lockfiles.sh --amend # Keep the unpublished tag on the commit that includes the synced lockfile. diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index e83c8d29f..94e93392a 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -42,7 +42,13 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - name: Set up Python + uses: actions/setup-python@v6 + with: + # The workspace-wide Clippy run below builds the PyO3 bindings, whose + # minimum supported interpreter is 3.11. Ubuntu 22.04 defaults to 3.10. + python-version: "3.11" + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -52,14 +58,14 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: components: rustfmt, clippy - name: Install dependencies run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -98,7 +104,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -110,7 +116,7 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -188,7 +194,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -196,7 +202,7 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Same crate, profile and target as the `linux` job above, so reuse # its cache: rust-cache keys on the job id by default, and this job @@ -234,7 +240,8 @@ jobs: NODE_OPTIONS: "--experimental-vm-modules" run: node_modules/.bin/jest --verbose macos: - timeout-minutes: 30 + # Cold native builds can take 28 minutes; reserve time for setup and Jest. + timeout-minutes: 35 # macos-15 ships a newer linker; the older macos-14 linker fails to insert # branch islands when the debug cdylib's __text section exceeds the 128 MB # AArch64 B/BL branch range. @@ -248,7 +255,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -257,8 +264,12 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 + # Use the same pinned compiler for cache selection and the native build. + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + cache: false + rustflags: "" + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index a8dd3993e..fbaa43201 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -4,9 +4,7 @@ env: MACOSX_DEPLOYMENT_TARGET: '10.13' CARGO_INCREMENTAL: '0' -permissions: - contents: write - id-token: write +permissions: {} on: push: @@ -33,6 +31,8 @@ concurrency: jobs: build-lancedb: + permissions: + contents: read strategy: fail-fast: false matrix: @@ -66,7 +66,8 @@ jobs: choco install --no-progress protoc rustup target add aarch64-pc-windows-msvc - target: x86_64-unknown-linux-gnu - host: ubuntu-latest + # Fat LTO reached 15.1 GiB before rustc was killed on the 15 GiB runner. + host: ubuntu-2404-8x-x64 features: fp16kernels # https://github.com/napi-rs/napi-rs/blob/main/debian.Dockerfile docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian @@ -161,8 +162,12 @@ jobs: working-directory: nodejs steps: - uses: actions/checkout@v6 + - name: Enable long paths for Windows dependencies + if: runner.os == 'Windows' + # Cargo also checks out Lance test fixtures below its git cache path. + run: git config --global core.longpaths true - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup node @@ -173,7 +178,7 @@ jobs: cache: pnpm cache-dependency-path: nodejs/pnpm-lock.yaml - name: Install - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable if: ${{ !matrix.settings.docker }} with: toolchain: stable @@ -189,7 +194,7 @@ jobs: # re-runs regardless, since the local crate changes every time, so the # win is larger on the non-LTO jobs than here. - name: Cache cargo (native builds) - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: ${{ !matrix.settings.docker }} with: # The release profile and per-target dirs differ from what the test @@ -211,7 +216,7 @@ jobs: # that built these artifacts -- safe, since cargo fingerprints the real # one; a base-image bump just costs one cold build. - name: Cache cargo (docker builds) - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: ${{ matrix.settings.docker }} with: key: docker-${{ matrix.settings.target }} @@ -220,17 +225,17 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - name: Install Zig - uses: mlugg/setup-zig@v2 + uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 if: ${{ contains(matrix.settings.target, 'musl') }} with: version: 0.14.1 - name: Install cargo-zigbuild - uses: taiki-e/install-action@v2 + uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 if: ${{ contains(matrix.settings.target, 'musl') }} with: tool: cargo-zigbuild - name: Build in docker - uses: addnab/docker-run-action@v3 + uses: addnab/docker-run-action@4f65fabd2431ebc8d299f8e5a018d79a769ae185 # v3 if: ${{ matrix.settings.docker }} with: image: ${{ matrix.settings.docker }} @@ -321,6 +326,8 @@ jobs: nodejs/dist/* !nodejs/dist/*.node test-lancedb: + permissions: + contents: read name: "Test: ${{ matrix.settings.target }} - node@${{ matrix.node }}" needs: - build-lancedb @@ -347,7 +354,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup Node.js 24 for install @@ -389,6 +396,10 @@ jobs: run: node_modules/.bin/jest --verbose publish: name: Publish + permissions: + contents: read + # npm provenance + id-token: write runs-on: ubuntu-latest defaults: run: @@ -399,7 +410,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup node diff --git a/.github/workflows/publish-cli-installer.yml b/.github/workflows/publish-cli-installer.yml new file mode 100644 index 000000000..6b73e2fc1 --- /dev/null +++ b/.github/workflows/publish-cli-installer.yml @@ -0,0 +1,48 @@ +name: Publish CLI installer + +on: + push: + branches: [main] + paths: + - scripts/install.sh + workflow_dispatch: + +permissions: + contents: read + id-token: write + +jobs: + publish: + if: github.repository == 'lancedb/lancedb' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + concurrency: + group: publish-cli-installer + cancel-in-progress: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # Queued jobs and retries publish the installer currently on main. + ref: refs/heads/main + persist-credentials: false + + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 + with: + aws-region: us-west-2 + role-to-assume: ${{ vars.CLI_INSTALLER_AWS_ROLE_ARN }} + + - name: Publish and verify the installer + shell: bash + env: + DISTRIBUTION_ID: ${{ vars.CLI_INSTALLER_DISTRIBUTION_ID }} + run: | + : "${DISTRIBUTION_ID:?Set CLI_INSTALLER_DISTRIBUTION_ID before publishing}" + key=cli/install.sh + aws s3api put-object --bucket lancedb-downloads --key "$key" \ + --body scripts/install.sh --content-type 'text/plain; charset=utf-8' \ + --cache-control 'public, max-age=0, must-revalidate' > /dev/null + invalidation=$(aws cloudfront create-invalidation --distribution-id "$DISTRIBUTION_ID" \ + --paths "/$key" --query Invalidation.Id --output text) + aws cloudfront wait invalidation-completed --distribution-id "$DISTRIBUTION_ID" --id "$invalidation" + curl --fail --silent --show-error --retry 3 "https://downloads.lancedb.com/$key" \ + --output "$RUNNER_TEMP/published-installer.sh" + cmp scripts/install.sh "$RUNNER_TEMP/published-installer.sh" diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index d45833def..137543eae 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -36,14 +36,15 @@ concurrency: jobs: linux: name: Python ${{ matrix.config.package_name }} ${{ matrix.config.platform }} manylinux${{ matrix.config.manylinux }} - timeout-minutes: 60 + # ARM64 and compatibility release builds can exceed an hour with cold fat LTO. + timeout-minutes: ${{ (matrix.config.platform == 'aarch64' || matrix.config.package_name == 'lancedb-compat') && 120 || 60 }} strategy: matrix: config: - platform: x86_64 manylinux: "2_28" extra_args: "--features fp16kernels" - runner: ubuntu-22.04 + runner: ubuntu-2404-8x-x64 package_name: "lancedb" rustflags: "" # For successful fat LTO builds, we need a large runner to avoid OOM errors. @@ -63,7 +64,8 @@ jobs: - platform: x86_64 manylinux: "2_28" extra_args: "" - runner: ubuntu-22.04 + # Keep fat LTO on the same larger runner as the standard x64 wheel. + runner: ubuntu-2404-8x-x64 package_name: "lancedb-compat" rustflags: "-Ctarget-cpu=x86-64-v2" runs-on: ${{ matrix.config.runner }} @@ -75,7 +77,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v6 with: - python-version: "3.10" + python-version: "3.11" - name: Add swap for Arm fat LTO if: matrix.config.platform == 'aarch64' shell: bash @@ -101,7 +103,8 @@ jobs: path: target/wheels/*.whl if-no-files-found: error mac: - timeout-minutes: 90 + # Cold fat LTO was still compiling when the 90-minute limit was reached. + timeout-minutes: 150 runs-on: ${{ matrix.config.runner }} strategy: matrix: @@ -181,7 +184,7 @@ jobs: with: python-version: "3.12" - name: Build sdist - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: sdist @@ -308,7 +311,7 @@ jobs: # `docker://ghcr.io/:` image reference that GHA tries to pull. - name: Publish to PyPI if: steps.choose_repo.outputs.repo == 'pypi' - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: packages-dir: target/wheels/ report-failure: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2080789d4..be6b8ed52 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -112,7 +112,7 @@ jobs: # `pip install -e .` builds the extension with maturin, which is most of # this job's ~33 minutes. It had no Rust cache, so every dependency was # recompiled from scratch on every run. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -130,10 +130,11 @@ jobs: run: pytest --doctest-modules python/lancedb linux: name: "Linux: python-3.${{ matrix.python-minor-version }}" - timeout-minutes: 30 + # A cold native build plus both test passes can exhaust 30 minutes. + timeout-minutes: 60 strategy: matrix: - python-minor-version: ["10", "13"] + python-minor-version: ["11", "13"] runs-on: "ubuntu-24.04" defaults: run: @@ -179,7 +180,8 @@ jobs: strategy: matrix: features: ["default", "experimental-functions"] - timeout-minutes: 30 + # A cold native build plus experimental-functions tests can exceed 30 minutes. + timeout-minutes: 60 runs-on: macos-15 defaults: run: @@ -196,7 +198,7 @@ jobs: python-version: "3.13" # maturin runs cargo natively on macOS (docker is Linux-only), so the host # target dir is cacheable. This job had no Rust cache. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -234,7 +236,7 @@ jobs: # maturin runs cargo natively on Windows (docker is Linux-only), so the # host target dir is cacheable. This job had no Rust cache at all and so # rebuilt every dependency from scratch on every run. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. The repo sits at # GitHub's cache cap, so per-PR saves just evict main's entries. @@ -266,10 +268,10 @@ jobs: - name: Set up Python uses: actions/setup-python@v6 with: - python-version: "3.10" + python-version: "3.11" # As with Doctest, `pip install -e .` compiles the extension and this job # had no Rust cache, which is most of its ~37 minutes. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index dbdcc3b54..6d9a9911d 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -14,6 +14,9 @@ on: - docs/web-tests/blob-v2/rs/** - nodejs/Cargo.toml - python/Cargo.toml + - python/src/** + - python/python/lancedb/exceptions.py + - python/python/lancedb/remote/errors.py - ci/build_no_lock.py - ci/tests/test_build_no_lock.py - .github/actions/setup-protoc/** @@ -39,7 +42,7 @@ jobs: timeout-minutes: 15 steps: - uses: actions/checkout@v6 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 - name: Read the pinned Lance tag id: lance run: | @@ -105,10 +108,10 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -132,7 +135,7 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v6 - - uses: EmbarkStudios/cargo-deny-action@v2 + - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 with: command: check advisories bans licenses sources @@ -148,14 +151,16 @@ jobs: - uses: actions/checkout@v6 # Building without a lock file often requires the latest Rust version since downstream # dependencies may have updated their minimum Rust version. - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: toolchain: "stable" + # The explicit cache below runs after lock removal and only saves on main. + cache: false # Remove cargo.lock to force a fresh build - name: Remove Cargo.lock run: rm -f Cargo.lock - - uses: rui314/setup-mold@v1 - - uses: Swatinem/rust-cache@v2 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -203,7 +208,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -213,7 +218,7 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rui314/setup-mold@v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 - name: Make Swap run: | swapfile=/swapfile @@ -237,11 +242,11 @@ jobs: sudo mkswap "$swapfile" sudo swapon "$swapfile" - name: Build - run: cargo build --profile ci --all-features --tests --locked --examples + run: cargo build --profile ci -p lancedb --all-features --tests --locked --examples - name: Run feature tests run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests - name: Run examples - run: cargo run --profile ci --all-features --example simple --locked + run: cargo run --profile ci -p lancedb --all-features --example simple --locked - name: Run blob v2 docs example # Python and TypeScript blob docs tests install preview packages. # Those builds are not guaranteed to remain available for more than @@ -275,7 +280,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Remote tests use a different feature graph from the main Linux # job. Cache downloads, but build into a fresh target directory. @@ -285,17 +290,17 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rui314/setup-mold@v1 - - name: Test the default local Functions gate - run: cargo test --profile ci -p lancedb --features remote --test experimental_functions --locked + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 - name: Run remote tests run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests macos: + name: ${{ matrix.phase == 'tests' && format('macos ({0})', matrix.mac-runner) || format('macos-doc ({0})', matrix.mac-runner) }} timeout-minutes: 60 strategy: matrix: mac-runner: ["macos-15", "macos-26"] + phase: [tests, doc] runs-on: "${{ matrix.mac-runner }}" defaults: run: @@ -306,10 +311,16 @@ jobs: with: fetch-depth: 0 lfs: true + - uses: actions/setup-python@v6 + id: python + with: + python-version: "3.13" - name: CPU features run: sysctl -a | grep cpu - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: + # PyO3 caches the interpreter library path; runner images can differ. + key: ${{ matrix.mac-runner }}-python-${{ steps.python.outputs.python-version }} # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes # caches to the creating ref. @@ -317,16 +328,18 @@ jobs: - name: Install dependencies run: brew install protobuf - name: Run tests + env: + PYO3_PYTHON: ${{ steps.python.outputs.python-path }} + CARGO_TEST_TARGETS: ${{ matrix.phase == 'doc' && '--doc' || '--lib --tests' }} run: | # Don't run the s3 integration tests since docker isn't available # on this image. ALL_FEATURES=`cargo metadata --format-version=1 --no-deps \ | jq -r '.packages[] | .features | keys | .[]' \ | grep -v s3-test | sort | uniq | paste -s -d "," -` - # Run doctests before test binaries fill the runner disk. Examples are - # already built by the Linux job, so avoid retaining them here. - cargo test --profile ci --features $ALL_FEATURES --locked --doc - cargo test --profile ci --features $ALL_FEATURES --locked --lib --tests + # Separate jobs give each phase its own time and disk budget. Examples + # are already built by the Linux job, so avoid retaining them here. + cargo test --profile ci --features $ALL_FEATURES --locked $CARGO_TEST_TARGETS windows: strategy: @@ -341,9 +354,11 @@ jobs: working-directory: rust/lancedb steps: - uses: actions/checkout@v6 + - name: Enable long paths for Lance dependencies + run: git config --global core.longpaths true - name: Set target run: rustup target add ${{ matrix.target }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -378,9 +393,11 @@ jobs: working-directory: rust/lancedb steps: - uses: actions/checkout@v6 + - name: Enable long paths for Lance dependencies + run: git config --global core.longpaths true - name: Set target run: rustup target add aarch64-pc-windows-msvc - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -406,7 +423,7 @@ jobs: runs-on: ubuntu-24.04 strategy: matrix: - msrv: ["1.95.0"] # This should match up with rust-version in Cargo.toml + msrv: ["1.98.0"] # This should match up with rust-version in Cargo.toml env: # Need up-to-date compilers for kernels CC: clang-18 @@ -420,10 +437,10 @@ jobs: sudo apt update sudo apt install -y protobuf-compiler libssl-dev - name: Install ${{ matrix.msrv }} - uses: dtolnay/rust-toolchain@master + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master with: toolchain: ${{ matrix.msrv }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/AGENTS.md b/AGENTS.md index 24465a28f..8a95dc983 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,12 @@ LanceDB is a database designed for retrieval, including vector, full-text, and hybrid search. -It is a wrapper around Lance. There are two backends: local (in-process like SQLite) and -remote (against LanceDB Cloud). +It is a wrapper around Lance. There are two editions: LanceDB Embedded (in-process, like +SQLite) and LanceDB Enterprise (a server cluster reached over HTTP). + +In user-facing text (docs, docstrings, error messages, examples), always say "Embedded" +and "Enterprise". Don't say "local" or "remote" tables. ("LanceDB Cloud" means only the +legacy hosted service, not Enterprise.) The code implements Enterprise in the `remote` +module, the `remote` cargo feature, and `Remote*` types. Those names are internal and +shouldn't leak into user-facing text. The core of LanceDB is written in Rust. There are bindings in Python, Typescript, and Java. @@ -72,9 +78,10 @@ back and fix it immediately if it is not conventional. ## Example plan: adding a new method on Table Adding a new method involves first adding it to the Rust core, then exposing it -in the Python and TypeScript bindings. There are both local and remote tables. -Remote tables are implemented via a HTTP API and require the `remote` cargo -feature flag to be enabled. Python has both sync and async methods. +in the Python and TypeScript bindings. Every method needs an Embedded and an +Enterprise implementation. Enterprise tables are implemented via a HTTP API in the +`remote` module and require the `remote` cargo feature flag to be enabled. Python +has both sync and async methods. Rust core changes: @@ -104,7 +111,7 @@ TypeScript bindings changes: 2. Run `pnpm build` to generate TypeScript definitions. 3. Add typescript method on abstract class `Table` in `nodejs/lancedb/table.ts`. 4. Add concrete method on `LocalTable` class in `nodejs/lancedb/table.ts`. - * Note: despite the name, this class is also used for remote tables. + * Note: despite the name, this class is also used for Enterprise tables. 5. Add test in `nodejs/__test__/table.test.ts`. 6. Run `pnpm run docs` to generate TypeScript documentation. @@ -155,3 +162,17 @@ Please consider the following when reviewing code contributions. ### Documentation * New features must include updates to the rust documentation comments. Link to relevant structs and methods to increase the value of documentation. +* User guides (`docs/web`) are evergreen: document only the current API. Don't add + migration tables or deprecation notices there. Mark deprecated APIs in their + docstrings, which feed the API reference. + +### Breaking changes and deprecation +* Prefer deprecating over removing a released public API. When the new name differs + from the old one, keep the old one as a deprecated alias (`#[deprecated]` in Rust, + `DeprecationWarning` in Python, `@deprecated` in TypeScript), with a test that it + still works. +* Don't reuse a released public name for something with a different meaning. Callers + get a confusing error instead of a deprecation warning. +* For a breaking change, add `!` to the PR title and start the PR body with a + `BREAKING CHANGE:` paragraph covering the new behavior, the old behavior, and how to + migrate. Release notes are generated from it. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d053fcbb3..874d121a6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -109,12 +109,13 @@ npm i -g mint@4.2.888 This previews this checkout, including your uncommitted changes. It doesn't include the other documentation sources or render the availability labels. -Use the [combined preview](https://github.com/lancedb/docs#development) when -checking Enterprise replacements or links to pages from another source. +Checking Enterprise replacements or links to pages from another source needs +the combined site, which maintainers build. Ask for that check in your pull +request if your change needs it. Staging shows saved release editions, so it won't show a new source change just because that change merged. -Follow the [style guide](https://github.com/lancedb/docs/blob/main/STYLE.md). +Follow the [style guide](docs/STYLE.md). [Vale](https://vale.sh) checks wording, names and punctuation using the [bundled LanceDB rules](.github/vale/README.md). Pull requests show suggestions on the lines they change. With Vale 3.24.0 installed, check a page locally with: @@ -182,15 +183,29 @@ You don't need to hold a documentation PR until launch. Use these controls: comment below the table or list, not between entries. Drafts remain in the source. Use them to avoid advertising an unfinished -feature, not to keep information confidential. See -[Writing docs before release](https://github.com/lancedb/docs#writing-docs-before-release) -for examples and how to preview a draft. +feature, not to keep information confidential. A draft section looks like +this: + +```mdx +{/* +Draft for the Feature X release. + +## Feature X {#feature-x} + +Feature X does ... +*/} +``` + +Give the comment lines of its own, with a blank line before and after it. To +see how a draft renders, remove its comment or its `.mintignore` entry in a +local change you don't commit, then run `mint dev`. Before the intended release, remove the draft controls, restore the navigation and links, and check the result. Those changes must be in the source commit the edition uses. A later change to `main` doesn't update an edition already saved. -For a mistake in an existing edition, fix the source and request a -[recorded correction](https://github.com/lancedb/docs#correcting-a-saved-edition). +For a mistake in an existing edition, fix the source and say in the pull +request which editions have the error. A maintainer corrects the saved +editions. ## Release process diff --git a/Cargo.lock b/Cargo.lock index 9e23f1f65..a05c79992 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,15 +63,15 @@ dependencies = [ [[package]] name = "alloc-no-stdlib" -version = "2.0.4" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" [[package]] name = "alloc-stdlib" -version = "0.2.2" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ "alloc-no-stdlib", ] @@ -221,9 +221,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" @@ -626,9 +626,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-config" -version = "1.8.16" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f156acdd2cf55f5aa53ee416c4ac851cf1222694506c0b1f78c85695e9ca9d" +checksum = "939e256cfe0ed68e96d32f194339d88210d5c10685cff0787400158f852c6819" dependencies = [ "aws-credential-types", "aws-runtime", @@ -640,12 +640,13 @@ dependencies = [ "aws-smithy-json", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", "hex", - "http 1.5.0", + "http", "sha1 0.10.6", "time", "tokio", @@ -656,9 +657,9 @@ dependencies = [ [[package]] name = "aws-credential-types" -version = "1.2.14" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f20799b373a1be121fe3005fba0c2090af9411573878f224df44b42727fcaf7" +checksum = "576e8da35751dc85409ec1cd15999f692c277a1fbe9336780fe6f15e49dd637d" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", @@ -692,9 +693,9 @@ dependencies = [ [[package]] name = "aws-runtime" -version = "1.7.3" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dcd93c82209ac7413532388067dce79be5a8780c1786e5fae3df22e4dee2864" +checksum = "9a0cc2144962cc5e358467b16e3d82981b1d424a7c3d34602be0036103814a1a" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -708,10 +709,8 @@ dependencies = [ "bytes", "bytes-utils", "fastrand", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "percent-encoding", "pin-project-lite", "tracing", @@ -720,10 +719,11 @@ dependencies = [ [[package]] name = "aws-sdk-bedrockruntime" -version = "1.130.0" +version = "1.153.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2f7bca252e3c5c8f0ed12c5501bf8b0fbadb937cd9fdd71a0ebd9d7526540f" +checksum = "89b8aeb4b1b6d5f9d377264cff21b4e4d773e66ee3c5582b4099a8fbc702bdb3" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -734,12 +734,12 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "http-body-util", "regex-lite", "tracing", @@ -747,10 +747,11 @@ dependencies = [ [[package]] name = "aws-sdk-dynamodb" -version = "1.111.0" +version = "1.137.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc418346e3cb248c7d59e642acbcb06488b7c7cd2ba6ebc79e8003f618c60099" +checksum = "41515f51bd2b5608268336bda372065e8fd5d1ca2f684b63e5c25ae4abb62c53" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -759,22 +760,24 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", + "url", ] [[package]] name = "aws-sdk-kms" -version = "1.106.0" +version = "1.129.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2336350f96efcf9c2552b7fdb4dd07a0c1fef11f22b28fb020a9e33e7925cf9d" +checksum = "5c5cdb29ad25d71c9ee54c408a672c98d90a24a0ea6eb063025483e0e894b411" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -783,22 +786,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-s3" -version = "1.132.0" +version = "1.157.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5575840a3a6b11f6011463ebe359320dfe5b67babb5e9b06fed6ddf809a9ab40" +checksum = "6ea9794c741520d8baec9462bcd0ad12164d4f5f78d008a8da9d6a0b7222caa8" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -810,6 +814,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", @@ -817,10 +822,9 @@ dependencies = [ "fastrand", "hex", "hmac 0.13.0", - "http 0.2.12", - "http 1.5.0", - "http-body 1.1.0", - "lru", + "http", + "http-body", + "lru 0.18.5", "percent-encoding", "regex-lite", "sha2 0.11.0", @@ -830,10 +834,11 @@ dependencies = [ [[package]] name = "aws-sdk-sso" -version = "1.98.0" +version = "1.119.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69c77aafa20460c68b6b3213c84f6423b6e76dbf89accd3e1789a686ffd9489" +checksum = "3c414f25ec4aa9dc18f5cc8f55e18848bb509fcda4ce7c77bee6072e95806bc9" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -842,22 +847,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-ssooidc" -version = "1.100.0" +version = "1.121.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c7e7b09346d5ca22a2a08267555843a6a0127fb20d8964cb6ecfb8fdb190225" +checksum = "bc638bb4355e6514334dcc3228cd4622f5ee54d704bd6a9010a5a91d7856d9d9" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -866,22 +872,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-sts" -version = "1.103.0" +version = "1.124.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2249b81a2e73a8027c41c378463a81ec39b8510f184f2caab87de912af0f49b" +checksum = "3f8a0dd8fbde04ba58ad722113c7addb11bf94cf549b1ea0eb9ea427fb87198a" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -891,21 +898,21 @@ dependencies = [ "aws-smithy-query", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sigv4" -version = "1.4.3" +version = "1.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68dc0b907359b120170613b5c09ccc61304eac3998ff6274b97d93ee6490115a" +checksum = "f385da9b7757ed4c8214797ad663ff534fb622006143530aa80e21f8e06ff85c" dependencies = [ "aws-credential-types", "aws-smithy-eventstream", @@ -913,15 +920,14 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "bytes", - "crypto-bigint 0.5.5", + "crypto-bigint", + "ecdsa", "form_urlencoded", "hex", "hmac 0.13.0", - "http 0.2.12", - "http 1.5.0", + "http", "p256", "percent-encoding", - "ring", "sha2 0.11.0", "subtle", "time", @@ -931,9 +937,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "1.2.14" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffcaf626bdda484571968400c326a244598634dc75fd451325a54ad1a59acfc" +checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e" dependencies = [ "futures-util", "pin-project-lite", @@ -942,17 +948,17 @@ dependencies = [ [[package]] name = "aws-smithy-checksums" -version = "0.64.7" +version = "0.65.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10efbbcec1e044b81600e2fc562a391951d291152d95b482d5b7e7132299d762" +checksum = "b67ecd999972b58e67cab052f5129906c08c25883bd0788ceefc55ef97d61307" dependencies = [ "aws-smithy-http", "aws-smithy-types", "bytes", "crc-fast", "hex", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "md-5", "pin-project-lite", @@ -963,9 +969,9 @@ dependencies = [ [[package]] name = "aws-smithy-eventstream" -version = "0.60.20" +version = "0.61.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf09d74e5e32f76b8762da505a3cd59303e367a664ca67295387baa8c1d7548" +checksum = "14c8a643d0e114cae39e45415e3225793a6396698b7779a0c9e3ede731d8fc71" dependencies = [ "aws-smithy-types", "bytes", @@ -974,9 +980,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.63.6" +version = "0.64.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba1ab2dc1c2c3749ead27180d333c42f11be8b0e934058fb4b2258ee8dbe5231" +checksum = "19af609dd5edf8b056cd0bb001c706c8b3b1458055328b334ec13d7f46f6aaa8" dependencies = [ "aws-smithy-eventstream", "aws-smithy-runtime-api", @@ -985,26 +991,25 @@ dependencies = [ "bytes-utils", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "percent-encoding", "pin-project-lite", - "pin-utils", "tracing", ] [[package]] name = "aws-smithy-http-client" -version = "1.1.13" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c3ef8931ad1c98aa6a55b4256f847f3116090819844e0dd41ea682cac5dd2d3" +checksum = "859a81364f8185349c584fb41cd8765a400cf982f447adada590cf008a9f3b85" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", "aws-smithy-types", "h2", - "http 1.5.0", + "http", "hyper", "hyper-rustls", "hyper-util", @@ -1020,9 +1025,9 @@ dependencies = [ [[package]] name = "aws-smithy-json" -version = "0.62.7" +version = "0.65.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "701a947f4797e52a911e114a898667c746c39feea467bbd1abd7b3721f702ffa" +checksum = "b45f9fc77ffe92c92c341165a01a565bd30c39ecf5aa8c0719b41719009604f9" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-schema", @@ -1031,28 +1036,31 @@ dependencies = [ [[package]] name = "aws-smithy-observability" -version = "0.2.6" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06c2315d173edbf1920da8ba3a7189695827002e4c0fc961973ab1c54abca9c" +checksum = "8e86338c869539a581bf161247762a6e87f92c5c075060057b5ed6d06632ed0c" dependencies = [ "aws-smithy-runtime-api", ] [[package]] name = "aws-smithy-query" -version = "0.60.15" +version = "0.64.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a56d79744fb3edb5d722ef79d86081e121d3b9422cb209eb03aea6aa4f21ebd" +checksum = "165f6265342a313ad6f7a1ac17a0cdba30c522039d3f41d8d6871ce8a2b34ecd" dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", + "aws-smithy-xml", "urlencoding", ] [[package]] name = "aws-smithy-runtime" -version = "1.11.3" +version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e6f5caf6fea86f8c2206541ab5857cfcda9013426cdbe8fa0098b9e2d32182" +checksum = "4cb80fb19c084da5fca9d797845735e184445e5b958599440d67529bf6ef1b64" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -1063,29 +1071,25 @@ dependencies = [ "aws-smithy-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", - "pin-utils", "tokio", "tracing", ] [[package]] name = "aws-smithy-runtime-api" -version = "1.12.3" +version = "1.19.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9db177daa6ba8afb9ee1aefcf548c907abcf52065e394ee11a92780057fe0e8c" +checksum = "8c4e85cffe9944b10d576b075432bd8f98dbc081e8681cb37d5b2d87dc27bc84" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", "aws-smithy-types", "bytes", - "http 0.2.12", - "http 1.5.0", + "http", "pin-project-lite", "tokio", "tracing", @@ -1094,9 +1098,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api-macros" -version = "1.0.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d7396fd9500589e62e460e987ecb671bad374934e55ec3b5f498cc7a8a8a7b7" +checksum = "ce237f890a2283c9b328955c3b0918d2d5bf66a1cb6ceccd36a0047246fbc6e6" dependencies = [ "proc-macro2", "quote", @@ -1105,34 +1109,31 @@ dependencies = [ [[package]] name = "aws-smithy-schema" -version = "0.1.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7442cb268338f0eb8278140a107c046756aa01093d8ef5e99628d34ae09c94f5" +checksum = "9543fc722ed4865ab29fb66bd7ed0bef7b029d265ba8c587144511e30006d431" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", - "http 1.5.0", + "http", ] [[package]] name = "aws-smithy-types" -version = "1.6.4" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b791f3ac597193fe1d08b82366986eb1f5bc31f2ac6c194c0855276116c76cd" +checksum = "cf183d70774ea2cfcc101ca74a8884e4c76be8b9df65cd303f6a1175c88e8f80" dependencies = [ "base64-simd", "bytes", "bytes-utils", "futures-core", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "itoa", "num-integer", "pin-project-lite", - "pin-utils", "ryu", "serde", "time", @@ -1142,22 +1143,26 @@ dependencies = [ [[package]] name = "aws-smithy-xml" -version = "0.60.15" +version = "0.64.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce02add1aa3677d022f8adf81dcbe3046a95f17a1b1e8979c145cd21d3d22b3" +checksum = "590fdc1a70546b2f7f2061c42eaf173fb6f26d935330d069edc04dbd8f01d924" dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", "xmlparser", ] [[package]] name = "aws-types" -version = "1.3.15" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4bbcaa9304ea40902d3d5f42a0428d1bd895a2b0f6999436fb279ffddc58ac" +checksum = "6ba0d970d3947bb064d2ae1d823efa186c1dbde88f88afa8f6549946e5d8deee" dependencies = [ "aws-credential-types", "aws-smithy-async", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "rustc_version", "tracing", @@ -1173,8 +1178,8 @@ dependencies = [ "axum-core 0.4.5", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-util", @@ -1207,8 +1212,8 @@ dependencies = [ "bytes", "form_urlencoded", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-util", @@ -1239,8 +1244,8 @@ dependencies = [ "async-trait", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -1259,8 +1264,8 @@ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -1312,9 +1317,9 @@ dependencies = [ [[package]] name = "base16ct" -version = "0.1.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" [[package]] name = "base64" @@ -1356,6 +1361,12 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "better_io" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef0a3155e943e341e557863e69a708999c94ede624e37865c8e2a91b94efa78f" + [[package]] name = "bigdecimal" version = "0.4.10" @@ -1417,6 +1428,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "blake3" version = "1.8.5" @@ -1460,9 +1480,9 @@ dependencies = [ [[package]] name = "brotli" -version = "3.5.0" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1471,9 +1491,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "2.5.1" +version = "6.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1803,9 +1823,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.1" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", "clap_derive", @@ -1813,9 +1833,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.0" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ "anstream", "anstyle", @@ -1825,14 +1845,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.1" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -1898,7 +1918,7 @@ checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47" dependencies = [ "crossterm", "unicode-segmentation", - "unicode-width 0.2.2", + "unicode-width 0.2.3", ] [[package]] @@ -1951,7 +1971,7 @@ dependencies = [ "encode_unicode", "libc", "once_cell", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "windows-sys 0.59.0", ] @@ -2061,6 +2081,12 @@ dependencies = [ "cfg-if 1.0.4", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -2235,26 +2261,20 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "crypto-bigint" -version = "0.4.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" dependencies = [ - "generic-array", - "rand_core 0.6.4", + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", "subtle", "zeroize", ] -[[package]] -name = "crypto-bigint" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" -dependencies = [ - "rand_core 0.6.4", - "subtle", -] - [[package]] name = "crypto-common" version = "0.1.7" @@ -2271,7 +2291,9 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", ] [[package]] @@ -2307,11 +2329,12 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.4" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", + "subtle", ] [[package]] @@ -2726,7 +2749,7 @@ dependencies = [ "arrow", "arrow-buffer", "base64 0.23.1", - "blake2", + "blake2 0.10.6", "blake3", "chrono", "chrono-tz 0.10.4", @@ -3084,16 +3107,6 @@ dependencies = [ "thiserror 2.0.18", ] -[[package]] -name = "der" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" -dependencies = [ - "const-oid 0.9.6", - "zeroize", -] - [[package]] name = "der" version = "0.7.10" @@ -3101,7 +3114,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "pem-rfc7468", + "pem-rfc7468 0.7.0", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] @@ -3188,6 +3212,15 @@ dependencies = [ "dirs-sys 0.5.0", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys 0.5.0", +] + [[package]] name = "dirs-sys" version = "0.4.1" @@ -3251,6 +3284,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "dtype_dispatch" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab23e69df104e2fd85ee63a533a22d2132ef5975dc6b36f9f3e5a7305e4a8ed7" + [[package]] name = "dunce" version = "1.0.5" @@ -3290,14 +3329,17 @@ dependencies = [ [[package]] name = "ecdsa" -version = "0.14.8" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" dependencies = [ - "der 0.6.1", + "der 0.8.3", + "digest 0.11.3", "elliptic-curve", "rfc6979", - "signature 1.6.4", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", ] [[package]] @@ -3308,19 +3350,20 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "elliptic-curve" -version = "0.12.3" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" dependencies = [ "base16ct", - "crypto-bigint 0.4.9", - "der 0.6.1", - "digest 0.10.7", + "crypto-bigint", + "crypto-common 0.2.1", + "digest 0.11.3", "ff", - "generic-array", "group", - "pkcs8 0.9.0", - "rand_core 0.6.4", + "hybrid-array", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", + "rand_core 0.10.1", "sec1", "subtle", "zeroize", @@ -3429,6 +3472,17 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + [[package]] name = "errno" version = "0.3.14" @@ -3462,11 +3516,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -3551,14 +3604,27 @@ dependencies = [ [[package]] name = "ff" -version = "0.12.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" dependencies = [ - "rand_core 0.6.4", + "rand_core 0.10.1", "subtle", ] +[[package]] +name = "file_url" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec49f140842acf886ff3e4fd47600ffdbb5f1b1ba70f6775880e688837a0b174" +dependencies = [ + "itertools 0.15.0", + "percent-encoding", + "thiserror 2.0.18", + "typed-path", + "url", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -3603,6 +3669,15 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + [[package]] name = "float8" version = "0.7.0" @@ -3662,9 +3737,9 @@ checksum = "ee1b05cbd864bcaecbd3455d6d967862d446e4ebfc3c2e5e5b9841e53cba6673" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -3734,6 +3809,15 @@ version = "1.20260804.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82eb03a32a1d50555353c85a7b9d3279a6f1e91af9890b789acdf544ed57c8d7" +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", +] + [[package]] name = "fs4" version = "0.13.1" @@ -3752,8 +3836,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4175,17 +4259,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if 1.0.4", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -4251,7 +4333,7 @@ dependencies = [ "io-uring", "itoa", "libc", - "lru", + "lru 0.16.4", "prost", "rand 0.9.5", "serde", @@ -4267,12 +4349,12 @@ dependencies = [ [[package]] name = "group" -version = "0.12.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" dependencies = [ "ff", - "rand_core 0.6.4", + "rand_core 0.10.1", "subtle", ] @@ -4287,7 +4369,7 @@ dependencies = [ "fnv", "futures-core", "futures-sink", - "http 1.5.0", + "http", "indexmap 2.14.0", "slab", "tokio", @@ -4310,6 +4392,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "halfbrown" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09" +dependencies = [ + "hashbrown 0.16.1", + "serde", +] + [[package]] name = "hash32" version = "0.3.1" @@ -4415,9 +4507,9 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" dependencies = [ - "dirs", + "dirs 6.0.0", "futures", - "http 1.5.0", + "http", "indicatif", "libc", "log", @@ -4441,7 +4533,7 @@ dependencies = [ "anyhow", "async-trait", "bytes", - "http 1.5.0", + "http", "more-asserts", "serde", "serde_json", @@ -4495,17 +4587,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.5.0" @@ -4516,17 +4597,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.1.0" @@ -4534,7 +4604,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http", ] [[package]] @@ -4545,8 +4615,8 @@ checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", ] @@ -4570,26 +4640,28 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" [[package]] name = "hybrid-array" -version = "0.4.12" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] name = "hyper" -version = "1.9.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", "futures-channel", "futures-core", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "httparse", "httpdate", "itoa", @@ -4605,7 +4677,7 @@ version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ - "http 1.5.0", + "http", "hyper", "hyper-util", "rustls", @@ -4655,8 +4727,8 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "hyper", "ipnet", "libc", @@ -4876,12 +4948,6 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -4941,7 +5007,7 @@ dependencies = [ "console", "number_prefix", "portable-atomic", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "web-time", ] @@ -5075,18 +5141,18 @@ checksum = "9028f49264629065d057f340a86acb84867925865f73bbf8d47b4d149a7e88b8" [[package]] name = "jieba-macros" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46adade69b634535a8f495cf87710ed893cff53e1dbc9dd750c2ab81c5defb82" +checksum = "38fc0f3831de71556de69643b80a08a5c8cd260a23c6b8dbeb7cd923c779cac5" dependencies = [ "phf_codegen 0.13.1", ] [[package]] name = "jieba-rs" -version = "0.10.1" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11b53580aaa8ec8b713da271da434f8947409242c537a9ab3f7b76bdbb19e8a9" +checksum = "bb5bdea4dc241d589e179f39d2a778f31490f3370aa2f626223dbd930ebc5c9d" dependencies = [ "bytecount", "cedarwood", @@ -5212,13 +5278,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if 1.0.4", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -5250,8 +5315,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arc-swap", "arrow", @@ -5292,12 +5357,14 @@ dependencies = [ "lance-datafusion", "lance-encoding", "lance-file", + "lance-geo", "lance-index", "lance-io", "lance-linalg", "lance-namespace", "lance-select", "lance-table", + "lance-table-runtime", "lance-tokenizer", "log", "moka", @@ -5306,7 +5373,6 @@ dependencies = [ "permutation", "pin-project", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rayon", @@ -5326,14 +5392,16 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-buffer", + "arrow-cast", "arrow-data", "arrow-ipc", "arrow-ord", + "arrow-row", "arrow-schema", "arrow-select", "bytemuck", @@ -5346,34 +5414,10 @@ dependencies = [ "rand 0.9.5", ] -[[package]] -name = "lance-arrow-scalar" -version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" -dependencies = [ - "arrow-array", - "arrow-buffer", - "arrow-cast", - "arrow-data", - "arrow-row", - "arrow-schema", - "half", -] - -[[package]] -name = "lance-arrow-stats" -version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" -dependencies = [ - "arrow-array", - "arrow-schema", - "lance-arrow-scalar", -] - [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrayref", "crunchy", @@ -5383,8 +5427,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-buffer", @@ -5401,6 +5445,7 @@ dependencies = [ "libc", "libm", "log", + "metrics", "moka", "num_cpus", "object_store 0.14.2", @@ -5421,8 +5466,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5447,15 +5492,14 @@ dependencies = [ "log", "pin-project", "prost", - "prost-build", "tokio", "tracing", ] [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5471,6 +5515,7 @@ dependencies = [ "half", "lance-arrow", "lance-core", + "lance-io", "lance-jsonb", "log", "pin-project", @@ -5480,8 +5525,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5493,13 +5538,13 @@ dependencies = [ "hex", "rand 0.9.5", "rand_distr 0.5.1", - "rand_xoshiro", + "rand_xoshiro 0.7.0", ] [[package]] name = "lance-derive" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "proc-macro2", "quote", @@ -5508,8 +5553,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-arith", "arrow-array", @@ -5532,8 +5577,8 @@ dependencies = [ "log", "lz4", "num-traits", + "pco", "prost", - "prost-build", "serde_json", "tokio", "tracing", @@ -5543,8 +5588,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-arith", "arrow-array", @@ -5557,7 +5602,6 @@ dependencies = [ "async-trait", "byteorder", "bytes", - "datafusion-common", "futures", "lance-arrow", "lance-core", @@ -5567,7 +5611,6 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "serde", "tokio", @@ -5576,21 +5619,40 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ + "arrow-array", + "arrow-schema", + "arrow-select", + "async-trait", + "datafusion-common", + "datafusion-execution", + "datafusion-expr", + "datafusion-physical-expr", + "datafusion-physical-plan", + "futures", "geo-traits", "geo-types", "geoarrow-array", "geoarrow-schema", + "lance-arrow", "lance-core", + "lance-datafusion-exec", + "lance-index", + "lance-index-core", + "lance-io", + "lance-select", + "prost-types", + "roaring", "serde", + "serde_json", ] [[package]] name = "lance-index" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arc-swap", "arrow", @@ -5614,25 +5676,21 @@ dependencies = [ "datafusion-functions-nested", "datafusion-physical-expr", "datafusion-physical-plan", - "dirs", + "dirs 6.0.0", "fst", "futures", - "geo-types", - "geoarrow-array", - "geoarrow-schema", "half", "hashbrown 0.16.1", "hex", "itertools 0.14.0", "jieba-rs", "lance-arrow", - "lance-arrow-stats", "lance-bitpacking", "lance-core", + "lance-datafusion", "lance-datafusion-exec", "lance-encoding", "lance-file", - "lance-geo", "lance-index-core", "lance-io", "lance-jsonb", @@ -5647,7 +5705,6 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rand_distr 0.5.1", @@ -5662,12 +5719,13 @@ dependencies = [ "tokio", "tracing", "twox-hash", + "uuid", ] [[package]] name = "lance-index-core" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-schema", @@ -5690,8 +5748,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5704,7 +5762,7 @@ dependencies = [ "chrono", "futures", "goosefs-sdk", - "http 1.5.0", + "http", "io-uring", "lance-core", "lance-namespace", @@ -5736,8 +5794,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "byteorder", "ethnum", @@ -5754,8 +5812,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5770,8 +5828,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "async-trait", @@ -5785,8 +5843,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arc-swap", "arrow", @@ -5840,8 +5898,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-buffer", @@ -5855,8 +5913,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5880,10 +5938,55 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rangemap", + "rayon", + "roaring", + "semver", + "serde", + "serde_json", + "snafu 0.9.0", + "tokio", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "lance-table-runtime" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-cast", + "arrow-data", + "arrow-ipc", + "arrow-row", + "arrow-schema", + "arrow-select", + "async-trait", + "blake3", + "byteorder", + "bytes", + "chrono", + "futures", + "humantime", + "itertools 0.14.0", + "lance-arrow", + "lance-core", + "lance-encoding", + "lance-file", + "lance-io", + "lance-namespace", + "lance-select", + "lance-table", + "log", + "object_store 0.14.2", + "prost", + "prost-types", + "rand 0.9.5", "roaring", "semver", "serde", @@ -5897,8 +6000,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-schema", @@ -5911,8 +6014,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "frostem", "icu_segmenter", @@ -5925,7 +6028,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.4" +version = "0.42.0-beta.37" dependencies = [ "ahash", "anyhow", @@ -5967,8 +6070,8 @@ dependencies = [ "futures", "half", "hf-hub", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "lance", "lance-arrow", "lance-core", @@ -6036,7 +6139,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.4" +version = "0.42.0-beta.37" dependencies = [ "anyhow", "arrow-array", @@ -6053,7 +6156,7 @@ dependencies = [ "directories", "futures", "half", - "http 1.5.0", + "http", "lancedb", "prost", "rcgen", @@ -6072,14 +6175,14 @@ dependencies = [ "toml", "tonic", "tracing", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "url", "which", ] [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.4" +version = "0.42.0-beta.37" dependencies = [ "arrow-array", "arrow-buffer", @@ -6099,12 +6202,13 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "serde", "serde_json", ] [[package]] name = "lancedb-python" -version = "0.42.0-beta.4" +version = "0.42.0-beta.37" dependencies = [ "arc-swap", "arrow", @@ -6126,6 +6230,7 @@ dependencies = [ "pyo3", "pyo3-async-runtimes", "pyo3-build-config", + "rattler_conda_types", "reqwest 0.13.5", "serde", "serde_json", @@ -6134,6 +6239,29 @@ dependencies = [ "uuid", ] +[[package]] +name = "lazy-regex" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a2cce8a22920a29fdcc8c9170aa5d29edd9fbcf8bea856e24c2cb1c2419f67" +dependencies = [ + "lazy-regex-proc_macros", + "once_cell", + "regex", +] + +[[package]] +name = "lazy-regex-proc_macros" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f1e4b1f1d8c71edb4ff2b2150ec4606445fd2ddf67ddc097655daf59286baa6" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "syn 3.0.3", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -6143,12 +6271,6 @@ dependencies = [ "spin 0.9.9", ] -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "lexical-core" version = "1.0.6" @@ -6239,9 +6361,9 @@ dependencies = [ [[package]] name = "libsais-rs" -version = "0.2.0" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40fe164dbd47ea0c20e78a121c980ef673326905f1d4fba55e3645a20ef6717f" +checksum = "ec55b7be74ed721889b8bc62d53e6a032d2b3b9bb60a4942b45b1e8362e64583" dependencies = [ "rayon", ] @@ -6373,6 +6495,15 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "lru-slab" version = "0.1.2" @@ -6557,7 +6688,7 @@ dependencies = [ "quanta", "radix_trie", "rand 0.9.5", - "rand_xoshiro", + "rand_xoshiro 0.7.0", "sketches-ddsketch", ] @@ -6595,9 +6726,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.0" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -6662,12 +6793,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fafa6961cabd9c63bcd77a45d7e3b7f3b552b70417831fb0f56db717e72407e" -[[package]] -name = "multimap" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" - [[package]] name = "multiversion" version = "0.7.4" @@ -6727,9 +6852,9 @@ dependencies = [ [[package]] name = "napi" -version = "3.15.0" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a746ad50efbfb632ade1de4025519a477decbbd798cea1a6ac41d7c44f80083" +checksum = "e4febd3f6e8b57aa986853be5b24f80a1856753535219aec431cce854cd666fc" dependencies = [ "bitflags 2.11.1", "chrono", @@ -6753,9 +6878,9 @@ checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" [[package]] name = "napi-derive" -version = "3.6.13" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff48271a0f61abb83f3e2d1989fa71169143db95f6f948c3a8903961f2855dc" +checksum = "d32eb00f92f84cf462fc328f49082b29c2a7d2eebeb1d447d19c1f9fdd9f89ee" dependencies = [ "convert_case", "ctor", @@ -6767,9 +6892,9 @@ dependencies = [ [[package]] name = "napi-derive-backend" -version = "6.1.6" +version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2639052c5aff9956a21d7b6202fc61d5e89c5f19c72d289b7a0641ea94e8159" +checksum = "d1fe28c64d8fc12e69f9b817d0febdbe7914555760f1e353106281b8ff99cc90" dependencies = [ "convert_case", "proc-macro2", @@ -6894,6 +7019,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "nom-language" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29" +dependencies = [ + "nom 8.0.0", +] + [[package]] name = "now" version = "0.1.3" @@ -7071,7 +7205,7 @@ dependencies = [ "base64 0.22.1", "chrono", "getrandom 0.2.17", - "http 1.5.0", + "http", "rand 0.8.6", "serde", "serde_json", @@ -7169,7 +7303,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "http 1.5.0", + "http", "humantime", "itertools 0.14.0", "parking_lot", @@ -7198,7 +7332,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "http 1.5.0", + "http", "http-body-util", "httparse", "humantime", @@ -7321,7 +7455,7 @@ dependencies = [ "base64 0.23.1", "bytes", "futures", - "http 1.5.0", + "http", "jiff", "log", "md-5", @@ -7344,8 +7478,8 @@ checksum = "f772ce6c137ab43647726116d505a649a88d41928fcd813438eb30b02312bcbb" dependencies = [ "bytes", "futures", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "opendal-core", "reqwest 0.13.5", ] @@ -7358,7 +7492,7 @@ checksum = "3734c648617e5ad724d49175dde8323550624f9614f50e9e81b7aafae30b1734" dependencies = [ "asyncband", "futures", - "http 1.5.0", + "http", "opendal-core", ] @@ -7401,7 +7535,7 @@ checksum = "c6cf31b02e7b44191d97c07254eea109b5da9c17210a29e478c8d0dc26dffb1f" dependencies = [ "base64 0.23.1", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "opendal-service-azure-common", @@ -7423,7 +7557,7 @@ dependencies = [ "asyncband", "base64 0.23.1", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "opendal-service-azure-common", @@ -7441,7 +7575,7 @@ version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8107324c3f3cb9970fe20526c2c341b7c5769acbd4699bab73bd525f5fd63d62" dependencies = [ - "http 1.5.0", + "http", "opendal-core", ] @@ -7452,7 +7586,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "feb737e6609b4fd42e4773b7b2d8d05031b63cd0df46c7ba68ddd64bae1dd3f3" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "quick-xml 0.41.0", @@ -7470,7 +7604,7 @@ checksum = "3d80eca6f9227bdf65d43e5b8d5fe75dca8cfab1da07571442a0420400847bea" dependencies = [ "async-trait", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "percent-encoding", @@ -7507,7 +7641,7 @@ dependencies = [ "asyncband", "bytes", "hf-xet", - "http 1.5.0", + "http", "log", "opendal-core", "percent-encoding", @@ -7522,7 +7656,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0ebfa355b1d4edb0e5b2a5b86d8de9f811fae1d7baca6d65246b230b2afc0bd" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "quick-xml 0.41.0", @@ -7541,7 +7675,7 @@ dependencies = [ "base64 0.23.1", "bytes", "crc-fast", - "http 1.5.0", + "http", "log", "md-5", "opendal-core", @@ -7647,13 +7781,15 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" [[package]] name = "p256" -version = "0.11.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ "ecdsa", "elliptic-curve", - "sha2 0.10.9", + "primefield", + "primeorder", + "sha2 0.11.0", ] [[package]] @@ -7738,6 +7874,18 @@ dependencies = [ "hmac 0.12.1", ] +[[package]] +name = "pco" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f01ab51a847e7002371c2384b2c88f50dd45982cc2764e7997751971f1bfbf" +dependencies = [ + "better_io", + "dtype_dispatch", + "half", + "rand_xoshiro 0.6.0", +] + [[package]] name = "pem" version = "3.0.6" @@ -7757,6 +7905,15 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -7902,12 +8059,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - [[package]] name = "pkcs1" version = "0.7.5" @@ -7934,16 +8085,6 @@ dependencies = [ "spki 0.7.3", ] -[[package]] -name = "pkcs8" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" -dependencies = [ - "der 0.6.1", - "spki 0.6.0", -] - [[package]] name = "pkcs8" version = "0.10.2" @@ -7956,6 +8097,16 @@ dependencies = [ "spki 0.7.3", ] +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", +] + [[package]] name = "pkg-config" version = "0.3.33" @@ -8434,13 +8585,30 @@ dependencies = [ ] [[package]] -name = "prettyplease" -version = "0.2.37" +name = "primefield" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" dependencies = [ - "proc-macro2", - "syn 2.0.117", + "crypto-bigint", + "crypto-common 0.2.1", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", ] [[package]] @@ -8471,25 +8639,6 @@ dependencies = [ "prost-derive", ] -[[package]] -name = "prost-build" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" -dependencies = [ - "heck 0.5.0", - "itertools 0.14.0", - "log", - "multimap", - "petgraph", - "prettyplease", - "prost", - "prost-types", - "regex", - "syn 2.0.117", - "tempfile", -] - [[package]] name = "prost-derive" version = "0.14.4" @@ -8565,6 +8714,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" +[[package]] +name = "purl" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60ebe4262ae91ddd28c8721111a0a6e9e58860e211fc92116c4bb85c98fd96ad" +dependencies = [ + "hex", + "percent-encoding", + "serde", + "thiserror 2.0.18", +] + [[package]] name = "pyo3" version = "0.29.3" @@ -8733,7 +8894,7 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.1", "rand_pcg", @@ -8836,7 +8997,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -8913,6 +9074,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xoshiro" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "rand_xoshiro" version = "0.7.0" @@ -8924,15 +9094,13 @@ dependencies = [ [[package]] name = "random_word" -version = "0.4.3" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07eed67a16dde2cc3c7f65c072acd8d5b2e53d4aab95067c320db851c7651f29" +checksum = "5d9299243acac3cb4f35c9f78d5ad29c87e70cd916a70f293d8526e54049c340" dependencies = [ "ahash", "brotli", - "once_cell", - "paste", - "rand 0.8.6", + "rand 0.10.1", "unicase", ] @@ -8951,6 +9119,99 @@ dependencies = [ "rustversion", ] +[[package]] +name = "rattler_conda_types" +version = "0.58.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fda631350e17df9bc789082d6b6c0fbde38e65cba580593ee3317fb6730644f2" +dependencies = [ + "ahash", + "core-foundation 0.10.1", + "dirs 7.0.0", + "fancy-regex 0.19.2", + "file_url", + "fs-err", + "glob", + "hex", + "indexmap 2.14.0", + "itertools 0.15.0", + "jiff", + "lazy-regex", + "memmap2 0.9.10", + "nom 8.0.0", + "nom-language", + "purl", + "rattler_conda_version", + "rattler_digest", + "rattler_macros", + "rattler_redaction", + "regex", + "serde", + "serde-untagged", + "serde_json", + "serde_repr", + "serde_with", + "serde_yaml", + "simd-json", + "smallvec", + "strum", + "tempfile", + "thiserror 2.0.18", + "tracing", + "typed-path", + "url", +] + +[[package]] +name = "rattler_conda_version" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee922b54cd30c198e93c542096a0d671cefba1a97600768b2ec4af3c11c44f55" +dependencies = [ + "itertools 0.15.0", + "nom 8.0.0", + "serde", + "smallvec", + "thiserror 2.0.18", +] + +[[package]] +name = "rattler_digest" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bda554663860e074665f838a4d9a89fbf671f576eaf288d29525114b345adc9" +dependencies = [ + "blake2 0.11.0", + "digest 0.11.3", + "hex", + "md-5", + "serde", + "serde-untagged", + "serde_bytes", + "serde_with", + "sha2 0.11.0", + "url", +] + +[[package]] +name = "rattler_macros" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a42690ed14c8b9d610aafc0f2eb715b85c05f3d3a2a307896e4f8d820aaa284f" +dependencies = [ + "quote", + "syn 3.0.3", +] + +[[package]] +name = "rattler_redaction" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b5ee47d0375643b037205a4fe238b90c518ca3fc83c7c240d82c49ba87d61c" +dependencies = [ + "url", +] + [[package]] name = "raw-cpuid" version = "11.6.0" @@ -9164,7 +9425,7 @@ checksum = "a5e6d659fcdbca6fe2d7ef109c2e28499b7be80501f1bb86c10caf5ec8ac1219" dependencies = [ "anyhow", "form_urlencoded", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-core", @@ -9182,7 +9443,7 @@ dependencies = [ "bytes", "form_urlencoded", "hex", - "http 1.5.0", + "http", "log", "percent-encoding", "quick-xml 0.41.0", @@ -9201,7 +9462,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff250f0fd0b913fbd565e405acc553da0f13bde30bfb5403178c9d0313cdc15f" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "quick-xml 0.41.0", "reqsign-aws-core", @@ -9219,7 +9480,7 @@ dependencies = [ "base64 0.23.1", "bytes", "form_urlencoded", - "http 1.5.0", + "http", "log", "pem", "percent-encoding", @@ -9242,7 +9503,7 @@ dependencies = [ "futures", "hex", "hmac 0.13.0", - "http 1.5.0", + "http", "jiff", "log", "mea", @@ -9274,7 +9535,7 @@ checksum = "272a5813571885c1455ffe106f0c768577e6ce69313446d4476e8d41dcf6ac5a" dependencies = [ "bytes", "form_urlencoded", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-aws-v4", @@ -9292,7 +9553,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "764629c90f7c3566a6d4e4641ebab9acd604ce02e16eda4d37c7d7e79e16ed90" dependencies = [ "anyhow", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-core", @@ -9312,8 +9573,8 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-rustls", @@ -9361,8 +9622,8 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-rustls", @@ -9417,7 +9678,7 @@ checksum = "199dda04a536b532d0cc04d7979e39b1c763ea749bf91507017069c00b96056f" dependencies = [ "anyhow", "async-trait", - "http 1.5.0", + "http", "reqwest 0.13.5", "thiserror 2.0.18", "tower-service", @@ -9425,13 +9686,12 @@ dependencies = [ [[package]] name = "rfc6979" -version = "0.3.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" dependencies = [ - "crypto-bigint 0.4.9", - "hmac 0.12.1", - "zeroize", + "crypto-bigint", + "hmac 0.13.0", ] [[package]] @@ -9838,14 +10098,14 @@ dependencies = [ [[package]] name = "sec1" -version = "0.3.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" dependencies = [ "base16ct", - "der 0.6.1", - "generic-array", - "pkcs8 0.9.0", + "ctutils", + "der 0.8.3", + "hybrid-array", "subtle", "zeroize", ] @@ -9905,6 +10165,28 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -10035,6 +10317,19 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.0", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serde_yaml_ng" version = "0.10.0" @@ -10048,6 +10343,16 @@ dependencies = [ "unsafe-libyaml", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "serial_test" version = "3.5.0" @@ -10139,7 +10444,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8" dependencies = [ "bstr", - "dirs", + "dirs 6.0.0", "os_str_bytes", ] @@ -10167,9 +10472,9 @@ dependencies = [ [[package]] name = "signature" -version = "1.6.4" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest 0.10.7", "rand_core 0.6.4", @@ -10177,12 +10482,12 @@ dependencies = [ [[package]] name = "signature" -version = "2.2.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" dependencies = [ - "digest 0.10.7", - "rand_core 0.6.4", + "digest 0.11.3", + "rand_core 0.10.1", ] [[package]] @@ -10204,6 +10509,20 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd-json" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebe141eb4a23ecc4d5de93fa5b139ac65dc07c38037a2fe9a8fb7c9d36bd832" +dependencies = [ + "halfbrown", + "ref-cast", + "serde", + "serde_json", + "simdutf8", + "value-trait", +] + [[package]] name = "simd_cesu8" version = "1.1.1" @@ -10240,9 +10559,12 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +dependencies = [ + "serde", +] [[package]] name = "smartstring" @@ -10345,16 +10667,6 @@ dependencies = [ "lock_api", ] -[[package]] -name = "spki" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" -dependencies = [ - "base64ct", - "der 0.6.1", -] - [[package]] name = "spki" version = "0.7.3" @@ -10365,6 +10677,16 @@ dependencies = [ "der 0.7.10", ] +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", +] + [[package]] name = "spm_precompiled" version = "0.1.4" @@ -10618,6 +10940,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "sysctl" version = "0.6.0" @@ -10712,7 +11045,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.2", + "getrandom 0.4.3", "once_cell", "rustix 1.1.4", "windows-sys 0.61.2", @@ -10811,9 +11144,9 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if 1.0.4", ] @@ -10881,18 +11214,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.11.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokenizers" @@ -11020,9 +11344,9 @@ dependencies = [ [[package]] name = "tokio-stream" -version = "0.1.18" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" dependencies = [ "futures-core", "pin-project-lite", @@ -11140,17 +11464,17 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "tonic" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +checksum = "e2cdfc673aabd30fe8fee92e65837b644c37c5d47f0f97ae6d5e0f1237d15e1b" dependencies = [ "async-trait", "axum 0.8.9", "base64 0.22.1", "bytes", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-timeout", @@ -11163,6 +11487,7 @@ dependencies = [ "tokio", "tokio-rustls", "tokio-stream", + "tokio-util", "tower", "tower-layer", "tower-service", @@ -11207,8 +11532,8 @@ checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "bitflags 2.11.1", "bytes", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", "tower-layer", @@ -11227,8 +11552,8 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", "tokio", @@ -11360,6 +11685,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.0" @@ -11431,15 +11762,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "unicode_categories" @@ -11486,9 +11811,9 @@ dependencies = [ [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -11527,7 +11852,7 @@ version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -11540,6 +11865,18 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "value-trait" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b" +dependencies = [ + "float-cmp", + "halfbrown", + "itoa", + "ryu", +] + [[package]] name = "vcpkg" version = "0.2.15" @@ -11570,9 +11907,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -11598,16 +11935,7 @@ version = "1.0.3+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] @@ -11621,12 +11949,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if 1.0.4", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -11634,19 +11961,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -11654,48 +11982,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -11722,23 +12028,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.11.1", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -12258,100 +12552,12 @@ version = "0.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.11.1", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "wkb" version = "0.9.2" @@ -12377,6 +12583,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.3" @@ -12404,7 +12622,7 @@ dependencies = [ "bytes", "crc32fast", "futures", - "http 1.5.0", + "http", "hyper", "more-asserts", "rand 0.10.1", @@ -12442,7 +12660,7 @@ dependencies = [ "countio", "futures", "futures-util", - "getrandom 0.4.2", + "getrandom 0.4.3", "heapify", "itertools 0.14.0", "lz4_flex 0.13.1", @@ -12472,7 +12690,7 @@ dependencies = [ "bytes", "chrono", "gearhash", - "http 1.5.0", + "http", "itertools 0.14.0", "more-asserts", "rand 0.10.1", @@ -12506,7 +12724,7 @@ dependencies = [ "colored", "const-str", "ctor", - "dirs", + "dirs 6.0.0", "futures", "git-version", "humantime", @@ -12556,9 +12774,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -12567,30 +12785,30 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", - "synstructure", + "syn 3.0.3", + "synstructure 0.14.0", ] [[package]] name = "zerocopy" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -12615,7 +12833,7 @@ dependencies = [ "proc-macro2", "quote", "syn 2.0.117", - "synstructure", + "synstructure 0.13.2", ] [[package]] @@ -12638,9 +12856,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.6" +version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ "serde", "yoke", @@ -12650,13 +12868,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.3" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -12666,7 +12884,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e408c6cc4699dd017d53dc080cd51c2cea2b5354af57a1479bd265ed42911487" dependencies = [ "crc32fast", - "getrandom 0.4.2", + "getrandom 0.4.3", "indexmap 2.14.0", "libc", "memchr", diff --git a/Cargo.toml b/Cargo.toml index ac10aab52..e21f256f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,24 +16,24 @@ repository = "https://github.com/lancedb/lancedb" description = "Serverless, low-latency vector database for AI applications" keywords = ["lancedb", "lance", "database", "vector", "search"] categories = ["database-implementations"] -rust-version = "1.95.0" +rust-version = "1.98.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.9", default-features = false, "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.9", default-features = false, "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.9", default-features = false, "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=16.0.0-beta.4", default-features = false, "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=16.0.0-beta.4", default-features = false, "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=16.0.0-beta.4", default-features = false, "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" @@ -49,8 +49,7 @@ arrow-select = "59.2.0" arrow-cast = "59.2.0" arrow-flight = { version = "59.2.0", features = ["flight-sql-experimental"] } async-trait = "0" -# Smithy JSON 0.63 requires the pre-1.7 Document representation; allow the MSRV pin. -aws-smithy-types = ">=1.3.6, <1.7" +aws-smithy-types = "1.9.1" base64 = "0.22" bytes = "1" datafusion = { version = "55.0.0", default-features = false } diff --git a/REVIEW.md b/REVIEW.md index 65aab71c6..b2e4a0d79 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -20,7 +20,20 @@ parity gaps when reviewing — but only flag real ones: * Stay silent on internal-only refactors, tests, docs, and changes with no cross-SDK surface. * Parity expectations apply to the Python and TypeScript (`nodejs`) SDKs. Java currently - implements only the remote table, not the local/embedded backend, so it is expected to - be partial — do not flag Java for missing local-only functionality. + implements only Enterprise tables, not the Embedded backend, so it is expected to + be partial — do not flag Java for missing Embedded-only functionality. * Keep parity feedback to a short, clearly-labeled note (e.g. "Possible SDK parity gap: …"). It is advisory, not a merge blocker. + +## User-facing text and API compatibility + +Check new user-facing text and public API changes against the rules in `AGENTS.md`: + +* Docs, docstrings, error messages, and examples say "Embedded" and "Enterprise", not + "local" or "remote" tables. +* Released public APIs are deprecated rather than removed, and released names are not + reused for something with a different meaning. +* User guides (`docs/web`) document only the current API, with no migration or + deprecation notices. +* Breaking changes have `!` in the PR title and a `BREAKING CHANGE:` paragraph at the + top of the PR body. diff --git a/RUST_THIRD_PARTY_LICENSES.html b/RUST_THIRD_PARTY_LICENSES.html index 2016fedcd..a1c82cfcb 100644 --- a/RUST_THIRD_PARTY_LICENSES.html +++ b/RUST_THIRD_PARTY_LICENSES.html @@ -44,19 +44,19 @@

Overview of licenses:

All license text:

@@ -65,230 +65,20 @@

BSD Zero Clause License

Used by:

-
Copyright (C) 2020 by museun <museun@outlook.com>
+                
Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
 
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted.
+Permission to use, copy, modify, and/or distribute this software for
+any purpose with or without fee is hereby granted.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-
- -
  • -

    Apache License 2.0

    -

    Used by:

    - -
    -                                 Apache License
    -                           Version 2.0, January 2004
    -                        http://www.apache.org/licenses/
    -
    -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    -
    -   1. Definitions.
    -
    -      "License" shall mean the terms and conditions for use, reproduction,
    -      and distribution as defined by Sections 1 through 9 of this document.
    -
    -      "Licensor" shall mean the copyright owner or entity authorized by
    -      the copyright owner that is granting the License.
    -
    -      "Legal Entity" shall mean the union of the acting entity and all
    -      other entities that control, are controlled by, or are under common
    -      control with that entity. For the purposes of this definition,
    -      "control" means (i) the power, direct or indirect, to cause the
    -      direction or management of such entity, whether by contract or
    -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    -      outstanding shares, or (iii) beneficial ownership of such entity.
    -
    -      "You" (or "Your") shall mean an individual or Legal Entity
    -      exercising permissions granted by this License.
    -
    -      "Source" form shall mean the preferred form for making modifications,
    -      including but not limited to software source code, documentation
    -      source, and configuration files.
    -
    -      "Object" form shall mean any form resulting from mechanical
    -      transformation or translation of a Source form, including but
    -      not limited to compiled object code, generated documentation,
    -      and conversions to other media types.
    -
    -      "Work" shall mean the work of authorship, whether in Source or
    -      Object form, made available under the License, as indicated by a
    -      copyright notice that is included in or attached to the work
    -      (an example is provided in the Appendix below).
    -
    -      "Derivative Works" shall mean any work, whether in Source or Object
    -      form, that is based on (or derived from) the Work and for which the
    -      editorial revisions, annotations, elaborations, or other modifications
    -      represent, as a whole, an original work of authorship. For the purposes
    -      of this License, Derivative Works shall not include works that remain
    -      separable from, or merely link (or bind by name) to the interfaces of,
    -      the Work and Derivative Works thereof.
    -
    -      "Contribution" shall mean any work of authorship, including
    -      the original version of the Work and any modifications or additions
    -      to that Work or Derivative Works thereof, that is intentionally
    -      submitted to Licensor for inclusion in the Work by the copyright owner
    -      or by an individual or Legal Entity authorized to submit on behalf of
    -      the copyright owner. For the purposes of this definition, "submitted"
    -      means any form of electronic, verbal, or written communication sent
    -      to the Licensor or its representatives, including but not limited to
    -      communication on electronic mailing lists, source code control systems,
    -      and issue tracking systems that are managed by, or on behalf of, the
    -      Licensor for the purpose of discussing and improving the Work, but
    -      excluding communication that is conspicuously marked or otherwise
    -      designated in writing by the copyright owner as "Not a Contribution."
    -
    -      "Contributor" shall mean Licensor and any individual or Legal Entity
    -      on behalf of whom a Contribution has been received by Licensor and
    -      subsequently incorporated within the Work.
    -
    -   2. Grant of Copyright License. Subject to the terms and conditions of
    -      this License, each Contributor hereby grants to You a perpetual,
    -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    -      copyright license to reproduce, prepare Derivative Works of,
    -      publicly display, publicly perform, sublicense, and distribute the
    -      Work and such Derivative Works in Source or Object form.
    -
    -   3. Grant of Patent License. Subject to the terms and conditions of
    -      this License, each Contributor hereby grants to You a perpetual,
    -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    -      (except as stated in this section) patent license to make, have made,
    -      use, offer to sell, sell, import, and otherwise transfer the Work,
    -      where such license applies only to those patent claims licensable
    -      by such Contributor that are necessarily infringed by their
    -      Contribution(s) alone or by combination of their Contribution(s)
    -      with the Work to which such Contribution(s) was submitted. If You
    -      institute patent litigation against any entity (including a
    -      cross-claim or counterclaim in a lawsuit) alleging that the Work
    -      or a Contribution incorporated within the Work constitutes direct
    -      or contributory patent infringement, then any patent licenses
    -      granted to You under this License for that Work shall terminate
    -      as of the date such litigation is filed.
    -
    -   4. Redistribution. You may reproduce and distribute copies of the
    -      Work or Derivative Works thereof in any medium, with or without
    -      modifications, and in Source or Object form, provided that You
    -      meet the following conditions:
    -
    -      (a) You must give any other recipients of the Work or
    -          Derivative Works a copy of this License; and
    -
    -      (b) You must cause any modified files to carry prominent notices
    -          stating that You changed the files; and
    -
    -      (c) You must retain, in the Source form of any Derivative Works
    -          that You distribute, all copyright, patent, trademark, and
    -          attribution notices from the Source form of the Work,
    -          excluding those notices that do not pertain to any part of
    -          the Derivative Works; and
    -
    -      (d) If the Work includes a "NOTICE" text file as part of its
    -          distribution, then any Derivative Works that You distribute must
    -          include a readable copy of the attribution notices contained
    -          within such NOTICE file, excluding those notices that do not
    -          pertain to any part of the Derivative Works, in at least one
    -          of the following places: within a NOTICE text file distributed
    -          as part of the Derivative Works; within the Source form or
    -          documentation, if provided along with the Derivative Works; or,
    -          within a display generated by the Derivative Works, if and
    -          wherever such third-party notices normally appear. The contents
    -          of the NOTICE file are for informational purposes only and
    -          do not modify the License. You may add Your own attribution
    -          notices within Derivative Works that You distribute, alongside
    -          or as an addendum to the NOTICE text from the Work, provided
    -          that such additional attribution notices cannot be construed
    -          as modifying the License.
    -
    -      You may add Your own copyright statement to Your modifications and
    -      may provide additional or different license terms and conditions
    -      for use, reproduction, or distribution of Your modifications, or
    -      for any such Derivative Works as a whole, provided Your use,
    -      reproduction, and distribution of the Work otherwise complies with
    -      the conditions stated in this License.
    -
    -   5. Submission of Contributions. Unless You explicitly state otherwise,
    -      any Contribution intentionally submitted for inclusion in the Work
    -      by You to the Licensor shall be under the terms and conditions of
    -      this License, without any additional terms or conditions.
    -      Notwithstanding the above, nothing herein shall supersede or modify
    -      the terms of any separate license agreement you may have executed
    -      with Licensor regarding such Contributions.
    -
    -   6. Trademarks. This License does not grant permission to use the trade
    -      names, trademarks, service marks, or product names of the Licensor,
    -      except as required for reasonable and customary use in describing the
    -      origin of the Work and reproducing the content of the NOTICE file.
    -
    -   7. Disclaimer of Warranty. Unless required by applicable law or
    -      agreed to in writing, Licensor provides the Work (and each
    -      Contributor provides its Contributions) on an "AS IS" BASIS,
    -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    -      implied, including, without limitation, any warranties or conditions
    -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    -      PARTICULAR PURPOSE. You are solely responsible for determining the
    -      appropriateness of using or redistributing the Work and assume any
    -      risks associated with Your exercise of permissions under this License.
    -
    -   8. Limitation of Liability. In no event and under no legal theory,
    -      whether in tort (including negligence), contract, or otherwise,
    -      unless required by applicable law (such as deliberate and grossly
    -      negligent acts) or agreed to in writing, shall any Contributor be
    -      liable to You for damages, including any direct, indirect, special,
    -      incidental, or consequential damages of any character arising as a
    -      result of this License or out of the use or inability to use the
    -      Work (including but not limited to damages for loss of goodwill,
    -      work stoppage, computer failure or malfunction, or any and all
    -      other commercial damages or losses), even if such Contributor
    -      has been advised of the possibility of such damages.
    -
    -   9. Accepting Warranty or Additional Liability. While redistributing
    -      the Work or Derivative Works thereof, You may choose to offer,
    -      and charge a fee for, acceptance of support, warranty, indemnity,
    -      or other liability obligations and/or rights consistent with this
    -      License. However, in accepting such obligations, You may act only
    -      on Your own behalf and on Your sole responsibility, not on behalf
    -      of any other Contributor, and only if You agree to indemnify,
    -      defend, and hold each Contributor harmless for any liability
    -      incurred by, or claims asserted against, such Contributor by reason
    -      of your accepting any such warranty or additional liability.
    -
    -   END OF TERMS AND CONDITIONS
    -
    -   APPENDIX: How to apply the Apache License to your work.
    -
    -      To apply the Apache License to your work, attach the following
    -      boilerplate notice, with the fields enclosed by brackets "[]"
    -      replaced with your own identifying information. (Don't include
    -      the brackets!)  The text should be enclosed in the appropriate
    -      comment syntax for the file format. We also recommend that a
    -      file or class name and description of purpose be included on the
    -      same "printed page" as the copyright notice for easier
    -      identification within third-party archives.
    -
    -   Copyright 2023 Jacob Pratt
    -
    -   Licensed under the Apache License, Version 2.0 (the "License");
    -   you may not use this file except in compliance with the License.
    -   You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
    +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
    +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     
  • @@ -505,7 +295,7 @@ THIS SOFTWARE.

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -715,7 +505,8 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -924,24 +715,19 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

    @@ -1152,7 +938,8 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -1364,7 +1151,15 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -1592,34 +1387,316 @@ Software.
                     

    Apache License 2.0

    Used by:

    +
    +                                 Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +Licenses for support code
    +-------------------------
    +
    +Parts of the TLS test suite are under the Go license. This code is not included
    +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
    +distributing code linked against BoringSSL does not trigger this license:
    +
    +Copyright (c) 2009 The Go Authors. All rights reserved.
    +
    +Redistribution and use in source and binary forms, with or without
    +modification, are permitted provided that the following conditions are
    +met:
    +
    +   * Redistributions of source code must retain the above copyright
    +notice, this list of conditions and the following disclaimer.
    +   * Redistributions in binary form must reproduce the above
    +copyright notice, this list of conditions and the following disclaimer
    +in the documentation and/or other materials provided with the
    +distribution.
    +   * Neither the name of Google Inc. nor the names of its
    +contributors may be used to endorse or promote products derived from
    +this software without specific prior written permission.
    +
    +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    +
    +
    +BoringSSL uses the Chromium test infrastructure to run a continuous build,
    +trybots etc. The scripts which manage this, and the script for generating build
    +metadata, are under the Chromium license. Distributing code linked against
    +BoringSSL does not trigger this license.
    +
    +Copyright 2015 The Chromium Authors. All rights reserved.
    +
    +Redistribution and use in source and binary forms, with or without
    +modification, are permitted provided that the following conditions are
    +met:
    +
    +   * Redistributions of source code must retain the above copyright
    +notice, this list of conditions and the following disclaimer.
    +   * Redistributions in binary form must reproduce the above
    +copyright notice, this list of conditions and the following disclaimer
    +in the documentation and/or other materials provided with the
    +distribution.
    +   * Neither the name of Google Inc. nor the names of its
    +contributors may be used to endorse or promote products derived from
    +this software without specific prior written permission.
    +
    +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                      Apache License
    @@ -1833,6 +1910,238 @@ This project includes code from Apache Aurora.
     Copyright: 2016 The Apache Software Foundation.
     Home page: https://aurora.apache.org/
     License: http://www.apache.org/licenses/LICENSE-2.0
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
    +                                 Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +--------------------------------------------------------------------------------
    +
    +arrow-array/src/delta.rs: MIT
    +
    +This file is derived from the chronoutil crate. The full MIT license
    +text is in arrow-array/LICENSE-MIT.
     
  • @@ -1840,9 +2149,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

    Used by:

                                      Apache License
    @@ -2052,7 +2359,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -2252,7 +2559,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Used by:

                                      Apache License
    @@ -2462,41 +2768,39 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -2705,7 +3009,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -2914,7 +3218,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3104,7 +3409,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
           same "printed page" as the copyright notice for easier
           identification within third-party archives.
     
    -   Copyright 2020 - 2025 Tatsuya Kawano
    +   Copyright 2019 TiKV Project Authors.
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 - 2026 Tatsuya Kawano
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 Sébastien Crozet
     
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
    @@ -3124,7 +3847,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3332,8 +4054,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3752,7 +4474,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3961,9 +4683,21 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -4172,7 +4906,456 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +------------------------------------------------------------------------------------
    +This product bundles third-party components under other open source licenses.
    +This section summarizes those components and their licenses. See the referenced
    +license files for text of these licenses.
    +
    +
    +Creative Commons Zero v1.0 Universal
    +------------------------------------
    +
    +bindings/dotnet/.gitignore
    +
    +The above file is derived from VisualStudio.gitignore in
    +https://github.com/github/gitignore. Its license text is in
    +bindings/dotnet/LICENSE-CC0-1.0.txt.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +   
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                     Apache License
                                Version 2.0, January 2004
    @@ -4381,6 +5564,219 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "{}"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright Individual contributors
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                     Apache License
    @@ -4590,22 +5986,38 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -4815,12 +6227,419 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   Copyright 2019 Yoshua Wuyts
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 Sébastien Crozet
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                    Apache License
                                Version 2.0, January 2004
    @@ -5030,7 +6849,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                   Apache License
                                Version 2.0, January 2004
    @@ -5448,15 +7267,15 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -5666,7 +7485,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -5874,7 +7693,8 @@ limitations under the License.

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6083,8 +7903,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6293,7 +8112,6 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
    @@ -6503,7 +8321,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6693,7 +8511,7 @@ APPENDIX: How to apply the Apache License to your work.
        same "printed page" as the copyright notice for easier
        identification within third-party archives.
     
    -Copyright 2018 The pin-utils authors
    +Copyright 2018 Brian Myers
     
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
    @@ -6712,8 +8530,8 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7120,6 +8938,215 @@ You may obtain a copy of the License at
     
        http://www.apache.org/licenses/LICENSE-2.0
     
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                  Apache License
    +                        Version 2.0, January 2004
    +                     http://www.apache.org/licenses/
    +
    +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +1. Definitions.
    +
    +   "License" shall mean the terms and conditions for use, reproduction,
    +   and distribution as defined by Sections 1 through 9 of this document.
    +
    +   "Licensor" shall mean the copyright owner or entity authorized by
    +   the copyright owner that is granting the License.
    +
    +   "Legal Entity" shall mean the union of the acting entity and all
    +   other entities that control, are controlled by, or are under common
    +   control with that entity. For the purposes of this definition,
    +   "control" means (i) the power, direct or indirect, to cause the
    +   direction or management of such entity, whether by contract or
    +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +   outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +   "You" (or "Your") shall mean an individual or Legal Entity
    +   exercising permissions granted by this License.
    +
    +   "Source" form shall mean the preferred form for making modifications,
    +   including but not limited to software source code, documentation
    +   source, and configuration files.
    +
    +   "Object" form shall mean any form resulting from mechanical
    +   transformation or translation of a Source form, including but
    +   not limited to compiled object code, generated documentation,
    +   and conversions to other media types.
    +
    +   "Work" shall mean the work of authorship, whether in Source or
    +   Object form, made available under the License, as indicated by a
    +   copyright notice that is included in or attached to the work
    +   (an example is provided in the Appendix below).
    +
    +   "Derivative Works" shall mean any work, whether in Source or Object
    +   form, that is based on (or derived from) the Work and for which the
    +   editorial revisions, annotations, elaborations, or other modifications
    +   represent, as a whole, an original work of authorship. For the purposes
    +   of this License, Derivative Works shall not include works that remain
    +   separable from, or merely link (or bind by name) to the interfaces of,
    +   the Work and Derivative Works thereof.
    +
    +   "Contribution" shall mean any work of authorship, including
    +   the original version of the Work and any modifications or additions
    +   to that Work or Derivative Works thereof, that is intentionally
    +   submitted to Licensor for inclusion in the Work by the copyright owner
    +   or by an individual or Legal Entity authorized to submit on behalf of
    +   the copyright owner. For the purposes of this definition, "submitted"
    +   means any form of electronic, verbal, or written communication sent
    +   to the Licensor or its representatives, including but not limited to
    +   communication on electronic mailing lists, source code control systems,
    +   and issue tracking systems that are managed by, or on behalf of, the
    +   Licensor for the purpose of discussing and improving the Work, but
    +   excluding communication that is conspicuously marked or otherwise
    +   designated in writing by the copyright owner as "Not a Contribution."
    +
    +   "Contributor" shall mean Licensor and any individual or Legal Entity
    +   on behalf of whom a Contribution has been received by Licensor and
    +   subsequently incorporated within the Work.
    +
    +2. Grant of Copyright License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   copyright license to reproduce, prepare Derivative Works of,
    +   publicly display, publicly perform, sublicense, and distribute the
    +   Work and such Derivative Works in Source or Object form.
    +
    +3. Grant of Patent License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   (except as stated in this section) patent license to make, have made,
    +   use, offer to sell, sell, import, and otherwise transfer the Work,
    +   where such license applies only to those patent claims licensable
    +   by such Contributor that are necessarily infringed by their
    +   Contribution(s) alone or by combination of their Contribution(s)
    +   with the Work to which such Contribution(s) was submitted. If You
    +   institute patent litigation against any entity (including a
    +   cross-claim or counterclaim in a lawsuit) alleging that the Work
    +   or a Contribution incorporated within the Work constitutes direct
    +   or contributory patent infringement, then any patent licenses
    +   granted to You under this License for that Work shall terminate
    +   as of the date such litigation is filed.
    +
    +4. Redistribution. You may reproduce and distribute copies of the
    +   Work or Derivative Works thereof in any medium, with or without
    +   modifications, and in Source or Object form, provided that You
    +   meet the following conditions:
    +
    +   (a) You must give any other recipients of the Work or
    +       Derivative Works a copy of this License; and
    +
    +   (b) You must cause any modified files to carry prominent notices
    +       stating that You changed the files; and
    +
    +   (c) You must retain, in the Source form of any Derivative Works
    +       that You distribute, all copyright, patent, trademark, and
    +       attribution notices from the Source form of the Work,
    +       excluding those notices that do not pertain to any part of
    +       the Derivative Works; and
    +
    +   (d) If the Work includes a "NOTICE" text file as part of its
    +       distribution, then any Derivative Works that You distribute must
    +       include a readable copy of the attribution notices contained
    +       within such NOTICE file, excluding those notices that do not
    +       pertain to any part of the Derivative Works, in at least one
    +       of the following places: within a NOTICE text file distributed
    +       as part of the Derivative Works; within the Source form or
    +       documentation, if provided along with the Derivative Works; or,
    +       within a display generated by the Derivative Works, if and
    +       wherever such third-party notices normally appear. The contents
    +       of the NOTICE file are for informational purposes only and
    +       do not modify the License. You may add Your own attribution
    +       notices within Derivative Works that You distribute, alongside
    +       or as an addendum to the NOTICE text from the Work, provided
    +       that such additional attribution notices cannot be construed
    +       as modifying the License.
    +
    +   You may add Your own copyright statement to Your modifications and
    +   may provide additional or different license terms and conditions
    +   for use, reproduction, or distribution of Your modifications, or
    +   for any such Derivative Works as a whole, provided Your use,
    +   reproduction, and distribution of the Work otherwise complies with
    +   the conditions stated in this License.
    +
    +5. Submission of Contributions. Unless You explicitly state otherwise,
    +   any Contribution intentionally submitted for inclusion in the Work
    +   by You to the Licensor shall be under the terms and conditions of
    +   this License, without any additional terms or conditions.
    +   Notwithstanding the above, nothing herein shall supersede or modify
    +   the terms of any separate license agreement you may have executed
    +   with Licensor regarding such Contributions.
    +
    +6. Trademarks. This License does not grant permission to use the trade
    +   names, trademarks, service marks, or product names of the Licensor,
    +   except as required for reasonable and customary use in describing the
    +   origin of the Work and reproducing the content of the NOTICE file.
    +
    +7. Disclaimer of Warranty. Unless required by applicable law or
    +   agreed to in writing, Licensor provides the Work (and each
    +   Contributor provides its Contributions) on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +   implied, including, without limitation, any warranties or conditions
    +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +   PARTICULAR PURPOSE. You are solely responsible for determining the
    +   appropriateness of using or redistributing the Work and assume any
    +   risks associated with Your exercise of permissions under this License.
    +
    +8. Limitation of Liability. In no event and under no legal theory,
    +   whether in tort (including negligence), contract, or otherwise,
    +   unless required by applicable law (such as deliberate and grossly
    +   negligent acts) or agreed to in writing, shall any Contributor be
    +   liable to You for damages, including any direct, indirect, special,
    +   incidental, or consequential damages of any character arising as a
    +   result of this License or out of the use or inability to use the
    +   Work (including but not limited to damages for loss of goodwill,
    +   work stoppage, computer failure or malfunction, or any and all
    +   other commercial damages or losses), even if such Contributor
    +   has been advised of the possibility of such damages.
    +
    +9. Accepting Warranty or Additional Liability. While redistributing
    +   the Work or Derivative Works thereof, You may choose to offer,
    +   and charge a fee for, acceptance of support, warranty, indemnity,
    +   or other liability obligations and/or rights consistent with this
    +   License. However, in accepting such obligations, You may act only
    +   on Your own behalf and on Your sole responsibility, not on behalf
    +   of any other Contributor, and only if You agree to indemnify,
    +   defend, and hold each Contributor harmless for any liability
    +   incurred by, or claims asserted against, such Contributor by reason
    +   of your accepting any such warranty or additional liability.
    +
    +END OF TERMS AND CONDITIONS
    +
    +APPENDIX: How to apply the Apache License to your work.
    +
    +   To apply the Apache License to your work, attach the following
    +   boilerplate notice, with the fields enclosed by brackets "[]"
    +   replaced with your own identifying information. (Don't include
    +   the brackets!)  The text should be enclosed in the appropriate
    +   comment syntax for the file format. We also recommend that a
    +   file or class name and description of purpose be included on the
    +   same "printed page" as the copyright notice for easier
    +   identification within third-party archives.
    +
    +Copyright 2019 quininer kel
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +	http://www.apache.org/licenses/LICENSE-2.0
    +
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    @@ -7132,7 +9159,9 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7342,7 +9371,7 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7760,7 +9789,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7969,7 +9998,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -8180,7 +10209,216 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

    +
                                  Apache License
    +                        Version 2.0, January 2004
    +                     http://www.apache.org/licenses/
    +
    +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +1. Definitions.
    +
    +   "License" shall mean the terms and conditions for use, reproduction,
    +   and distribution as defined by Sections 1 through 9 of this document.
    +
    +   "Licensor" shall mean the copyright owner or entity authorized by
    +   the copyright owner that is granting the License.
    +
    +   "Legal Entity" shall mean the union of the acting entity and all
    +   other entities that control, are controlled by, or are under common
    +   control with that entity. For the purposes of this definition,
    +   "control" means (i) the power, direct or indirect, to cause the
    +   direction or management of such entity, whether by contract or
    +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +   outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +   "You" (or "Your") shall mean an individual or Legal Entity
    +   exercising permissions granted by this License.
    +
    +   "Source" form shall mean the preferred form for making modifications,
    +   including but not limited to software source code, documentation
    +   source, and configuration files.
    +
    +   "Object" form shall mean any form resulting from mechanical
    +   transformation or translation of a Source form, including but
    +   not limited to compiled object code, generated documentation,
    +   and conversions to other media types.
    +
    +   "Work" shall mean the work of authorship, whether in Source or
    +   Object form, made available under the License, as indicated by a
    +   copyright notice that is included in or attached to the work
    +   (an example is provided in the Appendix below).
    +
    +   "Derivative Works" shall mean any work, whether in Source or Object
    +   form, that is based on (or derived from) the Work and for which the
    +   editorial revisions, annotations, elaborations, or other modifications
    +   represent, as a whole, an original work of authorship. For the purposes
    +   of this License, Derivative Works shall not include works that remain
    +   separable from, or merely link (or bind by name) to the interfaces of,
    +   the Work and Derivative Works thereof.
    +
    +   "Contribution" shall mean any work of authorship, including
    +   the original version of the Work and any modifications or additions
    +   to that Work or Derivative Works thereof, that is intentionally
    +   submitted to Licensor for inclusion in the Work by the copyright owner
    +   or by an individual or Legal Entity authorized to submit on behalf of
    +   the copyright owner. For the purposes of this definition, "submitted"
    +   means any form of electronic, verbal, or written communication sent
    +   to the Licensor or its representatives, including but not limited to
    +   communication on electronic mailing lists, source code control systems,
    +   and issue tracking systems that are managed by, or on behalf of, the
    +   Licensor for the purpose of discussing and improving the Work, but
    +   excluding communication that is conspicuously marked or otherwise
    +   designated in writing by the copyright owner as "Not a Contribution."
    +
    +   "Contributor" shall mean Licensor and any individual or Legal Entity
    +   on behalf of whom a Contribution has been received by Licensor and
    +   subsequently incorporated within the Work.
    +
    +2. Grant of Copyright License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   copyright license to reproduce, prepare Derivative Works of,
    +   publicly display, publicly perform, sublicense, and distribute the
    +   Work and such Derivative Works in Source or Object form.
    +
    +3. Grant of Patent License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   (except as stated in this section) patent license to make, have made,
    +   use, offer to sell, sell, import, and otherwise transfer the Work,
    +   where such license applies only to those patent claims licensable
    +   by such Contributor that are necessarily infringed by their
    +   Contribution(s) alone or by combination of their Contribution(s)
    +   with the Work to which such Contribution(s) was submitted. If You
    +   institute patent litigation against any entity (including a
    +   cross-claim or counterclaim in a lawsuit) alleging that the Work
    +   or a Contribution incorporated within the Work constitutes direct
    +   or contributory patent infringement, then any patent licenses
    +   granted to You under this License for that Work shall terminate
    +   as of the date such litigation is filed.
    +
    +4. Redistribution. You may reproduce and distribute copies of the
    +   Work or Derivative Works thereof in any medium, with or without
    +   modifications, and in Source or Object form, provided that You
    +   meet the following conditions:
    +
    +   (a) You must give any other recipients of the Work or
    +       Derivative Works a copy of this License; and
    +
    +   (b) You must cause any modified files to carry prominent notices
    +       stating that You changed the files; and
    +
    +   (c) You must retain, in the Source form of any Derivative Works
    +       that You distribute, all copyright, patent, trademark, and
    +       attribution notices from the Source form of the Work,
    +       excluding those notices that do not pertain to any part of
    +       the Derivative Works; and
    +
    +   (d) If the Work includes a "NOTICE" text file as part of its
    +       distribution, then any Derivative Works that You distribute must
    +       include a readable copy of the attribution notices contained
    +       within such NOTICE file, excluding those notices that do not
    +       pertain to any part of the Derivative Works, in at least one
    +       of the following places: within a NOTICE text file distributed
    +       as part of the Derivative Works; within the Source form or
    +       documentation, if provided along with the Derivative Works; or,
    +       within a display generated by the Derivative Works, if and
    +       wherever such third-party notices normally appear. The contents
    +       of the NOTICE file are for informational purposes only and
    +       do not modify the License. You may add Your own attribution
    +       notices within Derivative Works that You distribute, alongside
    +       or as an addendum to the NOTICE text from the Work, provided
    +       that such additional attribution notices cannot be construed
    +       as modifying the License.
    +
    +   You may add Your own copyright statement to Your modifications and
    +   may provide additional or different license terms and conditions
    +   for use, reproduction, or distribution of Your modifications, or
    +   for any such Derivative Works as a whole, provided Your use,
    +   reproduction, and distribution of the Work otherwise complies with
    +   the conditions stated in this License.
    +
    +5. Submission of Contributions. Unless You explicitly state otherwise,
    +   any Contribution intentionally submitted for inclusion in the Work
    +   by You to the Licensor shall be under the terms and conditions of
    +   this License, without any additional terms or conditions.
    +   Notwithstanding the above, nothing herein shall supersede or modify
    +   the terms of any separate license agreement you may have executed
    +   with Licensor regarding such Contributions.
    +
    +6. Trademarks. This License does not grant permission to use the trade
    +   names, trademarks, service marks, or product names of the Licensor,
    +   except as required for reasonable and customary use in describing the
    +   origin of the Work and reproducing the content of the NOTICE file.
    +
    +7. Disclaimer of Warranty. Unless required by applicable law or
    +   agreed to in writing, Licensor provides the Work (and each
    +   Contributor provides its Contributions) on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +   implied, including, without limitation, any warranties or conditions
    +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +   PARTICULAR PURPOSE. You are solely responsible for determining the
    +   appropriateness of using or redistributing the Work and assume any
    +   risks associated with Your exercise of permissions under this License.
    +
    +8. Limitation of Liability. In no event and under no legal theory,
    +   whether in tort (including negligence), contract, or otherwise,
    +   unless required by applicable law (such as deliberate and grossly
    +   negligent acts) or agreed to in writing, shall any Contributor be
    +   liable to You for damages, including any direct, indirect, special,
    +   incidental, or consequential damages of any character arising as a
    +   result of this License or out of the use or inability to use the
    +   Work (including but not limited to damages for loss of goodwill,
    +   work stoppage, computer failure or malfunction, or any and all
    +   other commercial damages or losses), even if such Contributor
    +   has been advised of the possibility of such damages.
    +
    +9. Accepting Warranty or Additional Liability. While redistributing
    +   the Work or Derivative Works thereof, You may choose to offer,
    +   and charge a fee for, acceptance of support, warranty, indemnity,
    +   or other liability obligations and/or rights consistent with this
    +   License. However, in accepting such obligations, You may act only
    +   on Your own behalf and on Your sole responsibility, not on behalf
    +   of any other Contributor, and only if You agree to indemnify,
    +   defend, and hold each Contributor harmless for any liability
    +   incurred by, or claims asserted against, such Contributor by reason
    +   of your accepting any such warranty or additional liability.
    +
    +END OF TERMS AND CONDITIONS
    +
    +APPENDIX: How to apply the Apache License to your work.
    +
    +   To apply the Apache License to your work, attach the following
    +   boilerplate notice, with the fields enclosed by brackets "[]"
    +   replaced with your own identifying information. (Don't include
    +   the brackets!)  The text should be enclosed in the appropriate
    +   comment syntax for the file format. We also recommend that a
    +   file or class name and description of purpose be included on the
    +   same "printed page" as the copyright notice for easier
    +   identification within third-party archives.
    +
    +Copyright 2024 Liam Gray <gmail@liamg.me>
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +	http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                  Apache License
                             Version 2.0, January 2004
    @@ -8390,7 +10628,8 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -8598,156 +10837,175 @@ limitations under the License.

    Apache License 2.0

    Used by:

      +
    • addr2line 0.25.1
    • ahash 0.8.12
    • -
    • arc-swap 1.7.1
    • -
    • arrayvec 0.7.6
    • +
    • arc-swap 1.9.3
    • +
    • arrayvec 0.7.8
    • async-channel 2.5.0
    • -
    • async-compression 0.4.19
    • -
    • async-lock 3.4.1
    • +
    • async-compression 0.4.42
    • +
    • async-lock 3.4.2
    • atomic-waker 1.1.2
    • autocfg 1.5.0
    • -
    • base64 0.21.7
    • +
    • backtrace 0.3.76
    • base64 0.22.1
    • -
    • bitflags 2.9.4
    • -
    • bumpalo 3.19.0
    • +
    • base64 0.23.1
    • +
    • bitflags 1.3.2
    • +
    • bitflags 2.11.1
    • +
    • bstr 1.12.1
    • +
    • bumpalo 3.20.2
    • bytes-utils 0.1.4
    • -
    • cc 1.2.40
    • -
    • cexpr 0.6.0
    • -
    • cfg-if 1.0.3
    • -
    • cmake 0.1.54
    • +
    • cast 0.3.0
    • +
    • cc 1.2.62
    • +
    • cfg-if 0.1.10
    • +
    • cfg-if 1.0.4
    • +
    • cmake 0.1.58
    • +
    • compression-codecs 0.4.38
    • +
    • compression-core 0.4.32
    • concurrent-queue 2.5.0
    • const-random-macro 0.1.16
    • const-random 0.1.18
    • core-foundation-sys 0.8.7
    • core-foundation 0.10.1
    • core-foundation 0.9.4
    • +
    • cpp_demangle 0.4.5
    • +
    • criterion-plot 0.8.2
    • +
    • criterion 0.8.2
    • crossbeam-channel 0.5.15
    • crossbeam-deque 0.8.6
    • -
    • crossbeam-epoch 0.9.18
    • +
    • crossbeam-epoch 0.9.20
    • crossbeam-queue 0.3.12
    • +
    • crossbeam-skiplist 0.1.3
    • crossbeam-utils 0.8.21
    • +
    • debugid 0.8.0
    • displaydoc 0.2.5
    • either 1.15.0
    • +
    • encoding_rs_io 0.1.7
    • equivalent 1.0.2
    • errno 0.3.14
    • event-listener-strategy 0.5.4
    • -
    • event-listener 5.4.1
    • -
    • fastrand 2.3.0
    • -
    • find-msvc-tools 0.1.3
    • +
    • event-listener 5.4.2
    • +
    • fastrand 2.4.1
    • +
    • find-msvc-tools 0.1.9
    • +
    • findshlibs 0.10.2
    • fixedbitset 0.5.7
    • +
    • flate2 1.1.9
    • fnv 1.0.7
    • form_urlencoded 1.2.2
    • -
    • fs4 0.8.4
    • +
    • foyer-intrusive-collections 0.10.0-dev
    • +
    • fs4 0.13.1
    • futures-timer 3.0.3
    • -
    • geohash 0.13.1
    • +
    • geohash 0.13.2
    • +
    • gimli 0.32.3
    • glob 0.3.3
    • -
    • group 0.12.1
    • +
    • group 0.14.0
    • hash32 0.3.1
    • hashbrown 0.14.5
    • hashbrown 0.15.5
    • -
    • hashbrown 0.16.0
    • +
    • hashbrown 0.16.1
    • +
    • hashbrown 0.17.1
    • heapless 0.8.0
    • heck 0.5.0
    • hermit-abi 0.5.2
    • httparse 1.10.1
    • -
    • hyper-rustls 0.24.2
    • -
    • hyper-rustls 0.27.7
    • +
    • hyper-rustls 0.27.9
    • +
    • hyper-timeout 0.5.2
    • +
    • hyper-tls 0.6.0
    • idna 1.1.0
    • -
    • idna_adapter 1.2.1
    • -
    • indexmap 2.12.0
    • -
    • itertools 0.11.0
    • -
    • itertools 0.12.1
    • +
    • idna_adapter 1.2.2
    • +
    • indexmap 2.14.0
    • itertools 0.13.0
    • itertools 0.14.0
    • +
    • itertools 0.15.0
    • jobserver 0.1.34
    • -
    • js-sys 0.3.81
    • +
    • js-sys 0.3.107
    • lazy_static 1.5.0
    • -
    • lazycell 1.3.0
    • -
    • linux-raw-sys 0.11.0
    • +
    • linux-raw-sys 0.12.1
    • linux-raw-sys 0.4.15
    • lock_api 0.4.14
    • -
    • log 0.4.28
    • +
    • log 0.4.34
    • lzma-sys 0.1.20
    • matrixmultiply 0.3.10
    • mime 0.3.17
    • -
    • multimap 0.10.1
    • ndarray 0.16.1
    • -
    • num-bigint-dig 0.8.4
    • +
    • num-bigint-dig 0.8.6
    • num-bigint 0.4.6
    • +
    • num-bigint 0.5.1
    • num-complex 0.4.6
    • num-integer 0.1.46
    • num-iter 0.1.45
    • +
    • num-rational 0.4.2
    • num-traits 0.2.19
    • num_cpus 1.17.0
    • -
    • once_cell 1.21.3
    • -
    • openssl-probe 0.1.6
    • +
    • oauth2 5.0.0
    • +
    • object 0.37.3
    • +
    • once_cell 1.21.4
    • +
    • openssl-probe 0.2.1
    • parking 2.2.1
    • parking_lot 0.12.5
    • parking_lot_core 0.9.12
    • percent-encoding 2.3.2
    • petgraph 0.8.3
    • -
    • pkg-config 0.3.32
    • -
    • prost-build 0.14.3
    • -
    • prost-derive 0.14.3
    • +
    • pkg-config 0.3.33
    • +
    • prost-derive 0.14.4
    • prost-types 0.14.3
    • -
    • prost 0.14.3
    • +
    • prost 0.14.4
    • +
    • rand_xoshiro 0.6.0
    • rawpointer 0.2.1
    • rayon-core 1.13.0
    • -
    • rayon 1.11.0
    • -
    • regex-automata 0.4.13
    • -
    • regex-lite 0.1.7
    • -
    • regex-syntax 0.8.6
    • -
    • regex 1.12.2
    • +
    • rayon 1.12.0
    • +
    • regex-automata 0.4.16
    • +
    • regex-lite 0.1.9
    • +
    • regex-syntax 0.8.11
    • +
    • regex 1.13.1
    • ring 0.17.14
    • +
    • roaring 0.11.5
    • robust 1.2.0
    • -
    • rustc-hash 1.1.0
    • +
    • rustc-demangle 0.1.27
    • rustc_version 0.4.1
    • rustix 0.38.44
    • -
    • rustix 1.1.2
    • -
    • rustls-native-certs 0.6.3
    • -
    • rustls-native-certs 0.8.1
    • -
    • rustls-pemfile 1.0.4
    • -
    • rustls-pemfile 2.2.0
    • -
    • rustls 0.21.12
    • -
    • rustls 0.23.31
    • +
    • rustix 1.1.4
    • +
    • rustls-native-certs 0.8.3
    • +
    • rustls 0.23.46
    • scoped-tls 1.0.1
    • scopeguard 1.2.0
    • -
    • sct 0.7.1
    • -
    • security-framework-sys 2.15.0
    • -
    • security-framework 2.11.1
    • -
    • security-framework 3.5.1
    • -
    • serde_with 3.15.0
    • -
    • serde_with_macros 3.15.0
    • -
    • shellexpand 3.1.1
    • -
    • signal-hook-registry 1.4.6
    • -
    • smallvec 1.15.1
    • -
    • socket2 0.5.10
    • -
    • socket2 0.6.0
    • -
    • sqlparser 0.59.0
    • -
    • sqlparser_derive 0.3.0
    • -
    • stable_deref_trait 1.2.0
    • -
    • syn 1.0.109
    • +
    • security-framework-sys 2.17.0
    • +
    • security-framework 3.7.0
    • +
    • serde_with 3.24.0
    • +
    • serde_with_macros 3.24.0
    • +
    • shellexpand 3.1.2
    • +
    • signal-hook-registry 1.4.8
    • +
    • simd_cesu8 1.1.1
    • +
    • smallvec 1.16.5
    • +
    • socket2 0.6.3
    • +
    • sqlparser 0.62.0
    • +
    • sqlparser_derive 0.5.0
    • +
    • stable_deref_trait 1.2.1
    • +
    • str_stack 0.1.1
    • +
    • symlink 0.1.0
    • system-configuration-sys 0.6.0
    • -
    • system-configuration 0.6.1
    • -
    • tempfile 3.23.0
    • +
    • system-configuration 0.7.0
    • +
    • tempfile 3.27.0
    • thread-tree 0.3.3
    • -
    • thread_local 1.1.9
    • -
    • unicase 2.8.1
    • -
    • unicode-segmentation 1.12.0
    • -
    • unicode-width 0.2.2
    • -
    • url 2.5.7
    • -
    • uuid 1.18.1
    • +
    • thread_local 1.1.10
    • +
    • tinytemplate 1.2.1
    • +
    • unicase 2.9.0
    • +
    • unicode-normalization 0.1.25
    • +
    • unicode-segmentation 1.13.2
    • +
    • unicode-width 0.1.14
    • +
    • unicode-width 0.2.3
    • +
    • url 2.5.8
    • +
    • uuid 1.29.0
    • version_check 0.9.5
    • wasi 0.11.1+wasi-snapshot-preview1
    • wasi 0.14.7+wasi-0.2.4
    • -
    • wasm-bindgen-backend 0.2.104
    • -
    • wasm-bindgen-futures 0.4.54
    • -
    • wasm-bindgen-macro-support 0.2.104
    • -
    • wasm-bindgen-macro 0.2.104
    • -
    • wasm-bindgen-shared 0.2.104
    • -
    • wasm-bindgen 0.2.104
    • -
    • web-sys 0.3.81
    • -
    • wit-bindgen 0.46.0
    • +
    • wasip2 1.0.3+wasi-0.2.9
    • +
    • wasm-bindgen-futures 0.4.80
    • +
    • wasm-bindgen-macro-support 0.2.130
    • +
    • wasm-bindgen-macro 0.2.130
    • +
    • wasm-bindgen-shared 0.2.130
    • +
    • wasm-bindgen 0.2.130
    • +
    • web-sys 0.3.107
    • +
    • wit-bindgen 0.57.1
    • wkb 0.9.2
    • wkt 0.14.0
    • xmlparser 0.13.6
    • @@ -8959,7 +11217,7 @@ limitations under the License.

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9169,14 +11427,14 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9386,41 +11644,56 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9629,10 +11902,209 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +Copyright (c) 2015-2022 Amod Malviya
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      + +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                    Apache License
                               Version 2.0, January 2004
      @@ -9827,11 +12299,13 @@ APPENDIX: How to apply the Apache License to your work.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -10040,8 +12514,8 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -10250,7 +12724,427 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright [yyyy] [name of copyright owner]
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright [yyyy] [name of copyright owner]
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
         Copyright (c) 2017-present PyO3 Project and Contributors.  https://github.com/PyO3
       
      @@ -10447,7 +13341,9 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
                                  Version 2.0, January 2004
      @@ -10656,7 +13552,9 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
       Version 2.0, January 2004
      @@ -10935,137 +13833,190 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
       Version 2.0, January 2004
      @@ -11382,10 +14333,10 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Rust-chrono is dual-licensed under The MIT License [1] and
      -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
      +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
       contributors.
       
       Nota Bene: This is same as the Rust Project's own license.
      @@ -11624,6 +14575,40 @@ See the License for the specific language governing permissions and
       limitations under the License.
       ~~~~
       
      +
      +
    • +
    • +

      BSD 2-Clause "Simplified" License

      +

      Used by:

      + +
      Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +1. Redistributions of source code must retain the above copyright
      +   notice, this list of conditions and the following disclaimer.
      +
      +2. Redistributions in binary form must reproduce the above copyright
      +   notice, this list of conditions and the following disclaimer in the
      +   documentation and/or other materials provided with the
      +   distribution.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    • @@ -11658,6 +14643,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
    • + +
    • +

      BSD 2-Clause "Simplified" License

      +

      Used by:

      + +
      Copyright (c) 2017-2020
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are met:
      +
      +1. Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +2. Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
      +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      + +
      // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
      +//
      +// Redistribution and use in source and binary forms, with or without
      +// modification, are permitted provided that the following conditions are met:
      +//
      +// 1. Redistributions of source code must retain the above copyright notice, this
      +//    list of conditions and the following disclaimer.
      +//
      +// 2. Redistributions in binary form must reproduce the above copyright notice,
      +//    this list of conditions and the following disclaimer in the documentation
      +//    and/or other materials provided with the distribution.
      +//
      +// 3. Neither the name of the copyright holder nor the names of its
      +//    contributors may be used to endorse or promote products derived from
      +//    this software without specific prior written permission.
      +//
      +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
      +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
      +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
      +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
      +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
      +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +/// The PUA code points special-cased in the GB18030 encoder.
      +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
      +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
      +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
      +];
      +
      +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
      +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
      +    [0xA6, 0xD9],
      +    [0xA6, 0xDA],
      +    [0xA6, 0xDB],
      +    [0xA6, 0xDC],
      +    [0xA6, 0xDD],
      +    [0xA6, 0xDE],
      +    [0xA6, 0xDF],
      +    [0xA6, 0xEC],
      +    [0xA6, 0xED],
      +    [0xA6, 0xF3],
      +    [0xFE, 0x59],
      +    [0xFE, 0x61],
      +    [0xFE, 0x66],
      +    [0xFE, 0x67],
      +    [0xFE, 0x6D],
      +    [0xFE, 0x7E],
      +    [0xFE, 0x90],
      +    [0xFE, 0xA0],
      +];
       
    • @@ -11665,6 +14743,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

      Used by:

      BSD 3-Clause License
       
      @@ -11701,26 +14780,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      BSD 3-Clause License
       
      -Copyright (c) 2013, Jyun-Yan You
      -All rights reserved.
      +Copyright (c) 2026, Alexandre Bury
       
       Redistribution and use in source and binary forms, with or without
       modification, are permitted provided that the following conditions are met:
       
      -* Redistributions of source code must retain the above copyright notice, this
      -  list of conditions and the following disclaimer.
      +1. Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
       
      -* Redistributions in binary form must reproduce the above copyright notice,
      -  this list of conditions and the following disclaimer in the documentation
      -  and/or other materials provided with the distribution.
      +2. Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
       
      -* Neither the name of the copyright holder nor the names of its
      -  contributors may be used to endorse or promote products derived from
      -  this software without specific prior written permission.
      +3. Neither the name of the copyright holder nor the names of its
      +   contributors may be used to endorse or promote products derived from
      +   this software without specific prior written permission.
       
       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
       AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      @@ -11738,10 +14818,50 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      +
      BSD License
      +
      +For Zstandard software
      +
      +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without modification,
      +are permitted provided that the following conditions are met:
      +
      + * Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +
      + * Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      + * Neither the name Facebook, nor Meta, nor the names of its contributors may
      +   be used to endorse or promote products derived from this software without
      +   specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      +
      Copyright (c) 2001, Dr Martin Porter
       Copyright (c) 2004,2005, Richard Boulton
      +Copyright (c) 2013, Yoshiki Shibukawa
      +Copyright (c) 2006-2025, Olly Betts
       All rights reserved.
       
       Redistribution and use in source and binary forms, with or without
      @@ -11766,16 +14886,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
       LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
       ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
       (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
    • BSD 3-Clause "New" or "Revised" License

      Used by:

      Copyright (c) 2016 Dropbox, Inc.
       All rights reserved.
      @@ -11832,8 +14952,53 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      +
      Copyright (c) 2026, frostem contributors
      +Copyright (c) 2001, Dr Martin Porter
      +Copyright (c) 2004,2005, Richard Boulton
      +Copyright (c) 2013, Yoshiki Shibukawa
      +Copyright (c) 2006-2025, Olly Betts
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions
      +are met:
      +
      +  1. Redistributions of source code must retain the above copyright notice,
      +     this list of conditions and the following disclaimer.
      +  2. Redistributions in binary form must reproduce the above copyright notice,
      +     this list of conditions and the following disclaimer in the documentation
      +     and/or other materials provided with the distribution.
      +  3. Neither the name of the Snowball project nor the names of its contributors
      +     may be used to endorse or promote products derived from this software
      +     without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      +
      Copyright (c) <year> <owner>. 
       
      @@ -11880,13 +15045,54 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
       CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
       OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
       OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      + +
      The auto-generated bindings are under the 3-clause BSD license:
      +
      +BSD License
      +
      +For Zstandard software
      +
      +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without modification,
      +are permitted provided that the following conditions are met:
      +
      + * Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +
      + * Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      + * Neither the name Facebook, nor Meta, nor the names of its contributors may
      +   be used to endorse or promote products derived from this software without
      +   specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    • Boost Software License 1.0

      Used by:

      Boost Software License - Version 1.0 - August 17th, 2003
       
      @@ -11911,6 +15117,21 @@ SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
       FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
       ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
       DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      Boost Software License 1.0

      +

      Used by:

      + +
      Boost Software License - Version 1.0 - August 17th, 2003
      +
      +Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following:
      +
      +The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor.
      +
      +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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
       
    • @@ -12040,13 +15261,405 @@ express Statement of Purpose. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. +
    • + +
    • +

      Common Development and Distribution License 1.0

      +

      Used by:

      + +
      Unless otherwise noted, all files in this distribution are released
      +under the Common Development and Distribution License (CDDL).
      +Exceptions are noted within the associated source files.
      +
      +--------------------------------------------------------------------
      +
      +
      +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
      +
      +1. Definitions.
      +
      +    1.1. "Contributor" means each individual or entity that creates
      +         or contributes to the creation of Modifications.
      +
      +    1.2. "Contributor Version" means the combination of the Original
      +         Software, prior Modifications used by a Contributor (if any),
      +         and the Modifications made by that particular Contributor.
      +
      +    1.3. "Covered Software" means (a) the Original Software, or (b)
      +         Modifications, or (c) the combination of files containing
      +         Original Software with files containing Modifications, in
      +         each case including portions thereof.
      +
      +    1.4. "Executable" means the Covered Software in any form other
      +         than Source Code.
      +
      +    1.5. "Initial Developer" means the individual or entity that first
      +         makes Original Software available under this License.
      +
      +    1.6. "Larger Work" means a work which combines Covered Software or
      +         portions thereof with code not governed by the terms of this
      +         License.
      +
      +    1.7. "License" means this document.
      +
      +    1.8. "Licensable" means having the right to grant, to the maximum
      +         extent possible, whether at the time of the initial grant or
      +         subsequently acquired, any and all of the rights conveyed
      +         herein.
      +
      +    1.9. "Modifications" means the Source Code and Executable form of
      +         any of the following:
      +
      +        A. Any file that results from an addition to, deletion from or
      +           modification of the contents of a file containing Original
      +           Software or previous Modifications;
      +
      +        B. Any new file that contains any part of the Original
      +           Software or previous Modifications; or
      +
      +        C. Any new file that is contributed or otherwise made
      +           available under the terms of this License.
      +
      +    1.10. "Original Software" means the Source Code and Executable
      +          form of computer software code that is originally released
      +          under this License.
      +
      +    1.11. "Patent Claims" means any patent claim(s), now owned or
      +          hereafter acquired, including without limitation, method,
      +          process, and apparatus claims, in any patent Licensable by
      +          grantor.
      +
      +    1.12. "Source Code" means (a) the common form of computer software
      +          code in which modifications are made and (b) associated
      +          documentation included in or with such code.
      +
      +    1.13. "You" (or "Your") means an individual or a legal entity
      +          exercising rights under, and complying with all of the terms
      +          of, this License.  For legal entities, "You" includes any
      +          entity which controls, is controlled by, or is under common
      +          control with You.  For purposes of this definition,
      +          "control" means (a) the power, direct or indirect, to cause
      +          the direction or management of such entity, whether by
      +          contract or otherwise, or (b) ownership of more than fifty
      +          percent (50%) of the outstanding shares or beneficial
      +          ownership of such entity.
      +
      +2. License Grants.
      +
      +    2.1. The Initial Developer Grant.
      +
      +    Conditioned upon Your compliance with Section 3.1 below and
      +    subject to third party intellectual property claims, the Initial
      +    Developer hereby grants You a world-wide, royalty-free,
      +    non-exclusive license:
      +
      +        (a) under intellectual property rights (other than patent or
      +            trademark) Licensable by Initial Developer, to use,
      +            reproduce, modify, display, perform, sublicense and
      +            distribute the Original Software (or portions thereof),
      +            with or without Modifications, and/or as part of a Larger
      +            Work; and
      +
      +        (b) under Patent Claims infringed by the making, using or
      +            selling of Original Software, to make, have made, use,
      +            practice, sell, and offer for sale, and/or otherwise
      +            dispose of the Original Software (or portions thereof).
      +
      +        (c) The licenses granted in Sections 2.1(a) and (b) are
      +            effective on the date Initial Developer first distributes
      +            or otherwise makes the Original Software available to a
      +            third party under the terms of this License.
      +
      +        (d) Notwithstanding Section 2.1(b) above, no patent license is
      +            granted: (1) for code that You delete from the Original
      +            Software, or (2) for infringements caused by: (i) the
      +            modification of the Original Software, or (ii) the
      +            combination of the Original Software with other software
      +            or devices.
      +
      +    2.2. Contributor Grant.
      +
      +    Conditioned upon Your compliance with Section 3.1 below and
      +    subject to third party intellectual property claims, each
      +    Contributor hereby grants You a world-wide, royalty-free,
      +    non-exclusive license:
      +
      +        (a) under intellectual property rights (other than patent or
      +            trademark) Licensable by Contributor to use, reproduce,
      +            modify, display, perform, sublicense and distribute the
      +            Modifications created by such Contributor (or portions
      +            thereof), either on an unmodified basis, with other
      +            Modifications, as Covered Software and/or as part of a
      +            Larger Work; and
      +
      +        (b) under Patent Claims infringed by the making, using, or
      +            selling of Modifications made by that Contributor either
      +            alone and/or in combination with its Contributor Version
      +            (or portions of such combination), to make, use, sell,
      +            offer for sale, have made, and/or otherwise dispose of:
      +            (1) Modifications made by that Contributor (or portions
      +            thereof); and (2) the combination of Modifications made by
      +            that Contributor with its Contributor Version (or portions
      +            of such combination).
      +
      +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
      +            effective on the date Contributor first distributes or
      +            otherwise makes the Modifications available to a third
      +            party.
      +
      +        (d) Notwithstanding Section 2.2(b) above, no patent license is
      +            granted: (1) for any code that Contributor has deleted
      +            from the Contributor Version; (2) for infringements caused
      +            by: (i) third party modifications of Contributor Version,
      +            or (ii) the combination of Modifications made by that
      +            Contributor with other software (except as part of the
      +            Contributor Version) or other devices; or (3) under Patent
      +            Claims infringed by Covered Software in the absence of
      +            Modifications made by that Contributor.
      +
      +3. Distribution Obligations.
      +
      +    3.1. Availability of Source Code.
      +
      +    Any Covered Software that You distribute or otherwise make
      +    available in Executable form must also be made available in Source
      +    Code form and that Source Code form must be distributed only under
      +    the terms of this License.  You must include a copy of this
      +    License with every copy of the Source Code form of the Covered
      +    Software You distribute or otherwise make available.  You must
      +    inform recipients of any such Covered Software in Executable form
      +    as to how they can obtain such Covered Software in Source Code
      +    form in a reasonable manner on or through a medium customarily
      +    used for software exchange.
      +
      +    3.2. Modifications.
      +
      +    The Modifications that You create or to which You contribute are
      +    governed by the terms of this License.  You represent that You
      +    believe Your Modifications are Your original creation(s) and/or
      +    You have sufficient rights to grant the rights conveyed by this
      +    License.
      +
      +    3.3. Required Notices.
      +
      +    You must include a notice in each of Your Modifications that
      +    identifies You as the Contributor of the Modification.  You may
      +    not remove or alter any copyright, patent or trademark notices
      +    contained within the Covered Software, or any notices of licensing
      +    or any descriptive text giving attribution to any Contributor or
      +    the Initial Developer.
      +
      +    3.4. Application of Additional Terms.
      +
      +    You may not offer or impose any terms on any Covered Software in
      +    Source Code form that alters or restricts the applicable version
      +    of this License or the recipients' rights hereunder.  You may
      +    choose to offer, and to charge a fee for, warranty, support,
      +    indemnity or liability obligations to one or more recipients of
      +    Covered Software.  However, you may do so only on Your own behalf,
      +    and not on behalf of the Initial Developer or any Contributor.
      +    You must make it absolutely clear that any such warranty, support,
      +    indemnity or liability obligation is offered by You alone, and You
      +    hereby agree to indemnify the Initial Developer and every
      +    Contributor for any liability incurred by the Initial Developer or
      +    such Contributor as a result of warranty, support, indemnity or
      +    liability terms You offer.
      +
      +    3.5. Distribution of Executable Versions.
      +
      +    You may distribute the Executable form of the Covered Software
      +    under the terms of this License or under the terms of a license of
      +    Your choice, which may contain terms different from this License,
      +    provided that You are in compliance with the terms of this License
      +    and that the license for the Executable form does not attempt to
      +    limit or alter the recipient's rights in the Source Code form from
      +    the rights set forth in this License.  If You distribute the
      +    Covered Software in Executable form under a different license, You
      +    must make it absolutely clear that any terms which differ from
      +    this License are offered by You alone, not by the Initial
      +    Developer or Contributor.  You hereby agree to indemnify the
      +    Initial Developer and every Contributor for any liability incurred
      +    by the Initial Developer or such Contributor as a result of any
      +    such terms You offer.
      +
      +    3.6. Larger Works.
      +
      +    You may create a Larger Work by combining Covered Software with
      +    other code not governed by the terms of this License and
      +    distribute the Larger Work as a single product.  In such a case,
      +    You must make sure the requirements of this License are fulfilled
      +    for the Covered Software.
      +
      +4. Versions of the License.
      +
      +    4.1. New Versions.
      +
      +    Sun Microsystems, Inc. is the initial license steward and may
      +    publish revised and/or new versions of this License from time to
      +    time.  Each version will be given a distinguishing version number.
      +    Except as provided in Section 4.3, no one other than the license
      +    steward has the right to modify this License.
      +
      +    4.2. Effect of New Versions.
      +
      +    You may always continue to use, distribute or otherwise make the
      +    Covered Software available under the terms of the version of the
      +    License under which You originally received the Covered Software.
      +    If the Initial Developer includes a notice in the Original
      +    Software prohibiting it from being distributed or otherwise made
      +    available under any subsequent version of the License, You must
      +    distribute and make the Covered Software available under the terms
      +    of the version of the License under which You originally received
      +    the Covered Software.  Otherwise, You may also choose to use,
      +    distribute or otherwise make the Covered Software available under
      +    the terms of any subsequent version of the License published by
      +    the license steward.
      +
      +    4.3. Modified Versions.
      +
      +    When You are an Initial Developer and You want to create a new
      +    license for Your Original Software, You may create and use a
      +    modified version of this License if You: (a) rename the license
      +    and remove any references to the name of the license steward
      +    (except to note that the license differs from this License); and
      +    (b) otherwise make it clear that the license contains terms which
      +    differ from this License.
      +
      +5. DISCLAIMER OF WARRANTY.
      +
      +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
      +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
      +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
      +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
      +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
      +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
      +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
      +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
      +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
      +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
      +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
      +    DISCLAIMER.
      +
      +6. TERMINATION.
      +
      +    6.1. This License and the rights granted hereunder will terminate
      +    automatically if You fail to comply with terms herein and fail to
      +    cure such breach within 30 days of becoming aware of the breach.
      +    Provisions which, by their nature, must remain in effect beyond
      +    the termination of this License shall survive.
      +
      +    6.2. If You assert a patent infringement claim (excluding
      +    declaratory judgment actions) against Initial Developer or a
      +    Contributor (the Initial Developer or Contributor against whom You
      +    assert such claim is referred to as "Participant") alleging that
      +    the Participant Software (meaning the Contributor Version where
      +    the Participant is a Contributor or the Original Software where
      +    the Participant is the Initial Developer) directly or indirectly
      +    infringes any patent, then any and all rights granted directly or
      +    indirectly to You by such Participant, the Initial Developer (if
      +    the Initial Developer is not the Participant) and all Contributors
      +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
      +    notice from Participant terminate prospectively and automatically
      +    at the expiration of such 60 day notice period, unless if within
      +    such 60 day period You withdraw Your claim with respect to the
      +    Participant Software against such Participant either unilaterally
      +    or pursuant to a written agreement with Participant.
      +
      +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
      +    all end user licenses that have been validly granted by You or any
      +    distributor hereunder prior to termination (excluding licenses
      +    granted to You by any distributor) shall survive termination.
      +
      +7. LIMITATION OF LIABILITY.
      +
      +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
      +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
      +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
      +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
      +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
      +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
      +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
      +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
      +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
      +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
      +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
      +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
      +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
      +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
      +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
      +    APPLY TO YOU.
      +
      +8. U.S. GOVERNMENT END USERS.
      +
      +    The Covered Software is a "commercial item," as that term is
      +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
      +    computer software" (as that term is defined at 48
      +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
      +    documentation" as such terms are used in 48 C.F.R. 12.212
      +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
      +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
      +    U.S. Government End Users acquire Covered Software with only those
      +    rights set forth herein.  This U.S. Government Rights clause is in
      +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
      +    provision that addresses Government rights in computer software
      +    under this License.
      +
      +9. MISCELLANEOUS.
      +
      +    This License represents the complete agreement concerning subject
      +    matter hereof.  If any provision of this License is held to be
      +    unenforceable, such provision shall be reformed only to the extent
      +    necessary to make it enforceable.  This License shall be governed
      +    by the law of the jurisdiction specified in a notice contained
      +    within the Original Software (except to the extent applicable law,
      +    if any, provides otherwise), excluding such jurisdiction's
      +    conflict-of-law provisions.  Any litigation relating to this
      +    License shall be subject to the jurisdiction of the courts located
      +    in the jurisdiction and venue specified in a notice contained
      +    within the Original Software, with the losing party responsible
      +    for costs, including, without limitation, court costs and
      +    reasonable attorneys' fees and expenses.  The application of the
      +    United Nations Convention on Contracts for the International Sale
      +    of Goods is expressly excluded.  Any law or regulation which
      +    provides that the language of a contract shall be construed
      +    against the drafter shall not apply to this License.  You agree
      +    that You alone are responsible for compliance with the United
      +    States export administration regulations (and the export control
      +    laws and regulation of any other countries) when You use,
      +    distribute or otherwise make available any Covered Software.
      +
      +10. RESPONSIBILITY FOR CLAIMS.
      +
      +    As between Initial Developer and the Contributors, each party is
      +    responsible for claims and damages arising, directly or
      +    indirectly, out of its utilization of rights under this License
      +    and You agree to work with Initial Developer and Contributors to
      +    distribute such responsibility on an equitable basis.  Nothing
      +    herein is intended or shall be deemed to constitute any admission
      +    of liability.
      +
      +--------------------------------------------------------------------
      +
      +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
      +DISTRIBUTION LICENSE (CDDL)
      +
      +For Covered Software in this distribution, this License shall
      +be governed by the laws of the State of California (excluding
      +conflict-of-law provisions).
      +
      +Any litigation relating to this License shall be subject to the
      +jurisdiction of the Federal Courts of the Northern District of
      +California and the state courts of the State of California, with
      +venue lying in Santa Clara County, California.
       
    • Community Data License Agreement Permissive 2.0

      Used by:

      # Community Data License Agreement - Permissive - Version 2.0
       
      @@ -12115,9 +15728,9 @@ insights.
                       

      ISC License

      Used by:

      -
      /* Copyright (c) 2018, Google Inc.
      +                
      /* Copyright (c) 2014, Intel Corporation.
        *
        * Permission to use, copy, modify, and/or distribute this software for any
        * purpose with or without fee is hereby granted, provided that the above
      @@ -12131,15 +15744,65 @@ insights.
        * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
       
      -#include <openssl/crypto.h>
      +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
      +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
       
      -#include <gtest/gtest.h>
      +#include "../../limbs/limbs.h"
      +
      +#define P384_LIMBS (384u / LIMB_BITS)
      +
      +typedef struct {
      +  Limb X[P384_LIMBS];
      +  Limb Y[P384_LIMBS];
      +  Limb Z[P384_LIMBS];
      +} P384_POINT;
      +
      +typedef struct {
      +  Limb X[P384_LIMBS];
      +  Limb Y[P384_LIMBS];
      +} P384_POINT_AFFINE;
       
       
      -TEST(SelfTests, KAT) {
      -#if !defined(_MSC_VER)
      -  EXPECT_TRUE(BORINGSSL_self_test());
      -#endif
      +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2015-2016 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! EdDSA Signatures.
      +
      +use super::ops::ELEM_LEN;
      +use crate::digest;
      +
      +pub mod signing;
      +pub mod verification;
      +
      +/// The length of an Ed25519 public key.
      +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
      +
      +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
      +    let mut ctx = digest::Context::new(&digest::SHA512);
      +    ctx.update(signature_r);
      +    ctx.update(public_key);
      +    ctx.update(msg);
      +    ctx.finish()
       }
       
    • @@ -12169,29 +15832,44 @@ TEST(SelfTests, KAT) {

      ISC License

      Used by:

      -
      // Copyright 2021 Brian Smith.
      +                
      // Copyright 2015-2022 Brian Smith.
       //
       // Permission to use, copy, modify, and/or distribute this software for any
       // purpose with or without fee is hereby granted, provided that the above
       // copyright notice and this permission notice appear in all copies.
       //
      -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
       // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
      -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
      -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
      -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
      -#[test]
      -fn cert_without_extensions_test() {
      -    // Check the certificate is valid with
      -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
      -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
      +use crate::limb::Limb;
       
      -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
      +#[derive(Clone, Copy)]
      +#[repr(transparent)]
      +pub struct N0([Limb; 2]);
      +
      +impl N0 {
      +    #[cfg(feature = "alloc")]
      +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
      +
      +    #[inline]
      +    pub const fn precalculated(n0: u64) -> Self {
      +        #[cfg(target_pointer_width = "64")]
      +        {
      +            Self([n0, 0])
      +        }
      +
      +        #[cfg(target_pointer_width = "32")]
      +        {
      +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
      +        }
      +    }
       }
       
      @@ -12199,21 +15877,372 @@ fn cert_without_extensions_test() {

      ISC License

      Used by:

      -
      Copyright (c) 2017 Adam Wick
      +                
      // Copyright 2015-2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
      -Permission to use, copy, modify, and/or distribute this software for any purpose
      -with or without fee is hereby granted, provided that the above copyright notice
      -and this permission notice appear in all copies.
      +use crate::{bb, error};
       
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
      -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
      -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
      -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
      -THIS SOFTWARE.
      +#[deprecated(
      +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
      +)]
      +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
      +    bb::verify_slices_are_equal(a, b)
      +}
      +
      + +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2016 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Elliptic curve operations and schemes using Curve25519.
      +
      +pub mod ed25519;
      +
      +pub mod x25519;
      +
      +mod ops;
      +mod scalar;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2016-2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +use crate::error::{KeyRejected, Unspecified};
      +
      +impl From<untrusted::EndOfInput> for Unspecified {
      +    fn from(source: untrusted::EndOfInput) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +impl From<core::array::TryFromSliceError> for Unspecified {
      +    fn from(source: core::array::TryFromSliceError) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +impl From<KeyRejected> for Unspecified {
      +    fn from(source: KeyRejected) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2018 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Serialization and deserialization.
      +
      +#[doc(hidden)]
      +pub mod der;
      +
      +#[cfg(feature = "alloc")]
      +mod writer;
      +
      +#[cfg(feature = "alloc")]
      +pub(crate) mod der_writer;
      +
      +pub(crate) mod positive;
      +
      +pub use self::positive::Positive;
      +
      +#[cfg(feature = "alloc")]
      +pub(crate) use self::writer::TooLongError;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2019-2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +use super::BlockLen;
      +
      +pub(super) use self::{
      +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
      +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
      +};
      +
      +pub(super) const CHAINING_WORDS: usize = 8;
      +
      +#[cfg(any(
      +    all(target_arch = "aarch64", target_endian = "little"),
      +    all(target_arch = "arm", target_endian = "little"),
      +    target_arch = "x86_64"
      +))]
      +#[macro_use]
      +mod ffi;
      +
      +pub(super) mod fallback;
      +mod sha2_32;
      +mod sha2_64;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
      +#[allow(dead_code)]
      +#[inline(always)]
      +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
      +    r
      +}
      +
      +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
      +#[allow(dead_code)]
      +#[inline(always)]
      +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
      +    r
      +}
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Integration tests for non-public APIs.
      +
      +mod bits_tests;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +pub use self::{
      +    array::Array,
      +    base::{IndexError, Overlapping},
      +    partial_block::PartialBlock,
      +};
      +
      +mod array;
      +mod base;
      +mod partial_block;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
      +
      +pub(in super::super) mod mont;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +#![cfg(target_arch = "x86_64")]
      +
      +pub(in super::super::super) mod mont;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +mod storage;
      +
      +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +pub(super) mod aarch64;
      +pub(super) mod x86_64;
       
    • @@ -12241,7 +16270,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

      ISC License

      Used by:

      Copyright © 2015, Simonas Kazlauskas
       
      @@ -12261,7 +16290,7 @@ THIS SOFTWARE.
                       

      ISC License

      Used by:

      Except as otherwise noted, this project is licensed under the following
       (ISC-style) terms:
      @@ -12288,12 +16317,12 @@ third-party/chromium/LICENSE.
                       

      ISC License

      Used by:

      ISC License
       
       Copyright (c) 2016, Mapbox
      -Copyright (c) 2018, Tree Cricket
      +Copyright (c) 2023, Taku Fukada
       
       Permission to use, copy, modify, and/or distribute this software for any purpose
       with or without fee is hereby granted, provided that the above copyright notice
      @@ -12312,7 +16341,8 @@ THIS SOFTWARE.
                       

      ISC License

      Used by:

      ISC License:
       
      @@ -12328,7 +16358,581 @@ THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
                       

      MIT License

      Used by:

      +
                                        MIT License
      +
      +Copyright 2024 Antoine Catton
      +Copyright 2016-2024 David Tolnay
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      # 3rd Party Notices
      +
      +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
      +
      +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
      +
      +    tectonic_cfg_support is licensed under the MIT License.
      +
      +    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.
      +---
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +//! Codegen exports used by `tonic-build`.
      +
      +pub use async_trait::async_trait;
      +pub use tokio_stream;
      +
      +pub use std::future::Future;
      +pub use std::pin::Pin;
      +pub use std::sync::Arc;
      +pub use std::task::{Context, Poll};
      +pub use tower_service::Service;
      +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
      +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
      +pub use crate::extensions::GrpcMethod;
      +pub use crate::service::interceptor::InterceptedService;
      +pub use bytes::Bytes;
      +pub use http;
      +pub use http_body::Body;
      +
      +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
      +pub type BoxStream<T> =
      +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +//! Utilities for using Tower services with Tonic.
      +
      +pub mod interceptor;
      +pub(crate) mod layered;
      +#[cfg(feature = "router")]
      +pub(crate) mod router;
      +
      +#[doc(inline)]
      +pub use self::interceptor::{Interceptor, InterceptorLayer};
      +pub use self::layered::{LayerExt, Layered};
      +#[doc(inline)]
      +#[cfg(feature = "router")]
      +pub use self::router::{Routes, RoutesBuilder};
      +#[cfg(feature = "router")]
      +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
      +
      +pub mod recover_error;
      +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +//! Various utilities used throughout tonic.
      +
      +// some combinations of features might cause things here not to be used
      +#![allow(dead_code)]
      +
      +pub(crate) mod base64 {
      +    use base64::{
      +        alphabet,
      +        engine::{
      +            DecodePaddingMode,
      +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
      +        },
      +    };
      +
      +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
      +        &alphabet::STANDARD,
      +        GeneralPurposeConfig::new()
      +            .with_encode_padding(true)
      +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
      +    );
      +
      +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
      +        &alphabet::STANDARD,
      +        GeneralPurposeConfig::new()
      +            .with_encode_padding(false)
      +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
      +    );
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +/// A gRPC Method info extension.
      +#[derive(Debug, Clone)]
      +pub struct GrpcMethod<'a> {
      +    service: &'a str,
      +    method: &'a str,
      +}
      +
      +impl<'a> GrpcMethod<'a> {
      +    /// Create a new `GrpcMethod` extension.
      +    #[doc(hidden)]
      +    pub fn new(service: &'a str, method: &'a str) -> Self {
      +        Self { service, method }
      +    }
      +
      +    /// gRPC service name
      +    pub fn service(&self) -> &str {
      +        self.service
      +    }
      +    /// gRPC method name
      +    pub fn method(&self) -> &str {
      +        self.method
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +mod add_origin;
      +use self::add_origin::AddOrigin;
      +
      +mod user_agent;
      +use self::user_agent::UserAgent;
      +
      +mod reconnect;
      +use self::reconnect::Reconnect;
      +
      +mod connection;
      +pub(super) use self::connection::Connection;
      +
      +mod discover;
      +pub use self::discover::Change;
      +pub(super) use self::discover::DynamicServiceStream;
      +
      +mod io;
      +use self::io::BoxedIo;
      +
      +mod connector;
      +pub(crate) use self::connector::Connector;
      +
      +mod executor;
      +pub(super) use self::executor::{Executor, SharedExec};
      +
      +#[cfg(feature = "_tls-any")]
      +mod tls;
      +#[cfg(feature = "_tls-any")]
      +pub(super) use self::tls::TlsConnector;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +mod io;
      +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
      +
      +#[cfg(feature = "_tls-any")]
      +mod tls;
      +#[cfg(feature = "_tls-any")]
      +pub(crate) use self::tls::TlsAcceptor;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +pub(crate) mod grpc_timeout;
      +#[cfg(feature = "_tls-any")]
      +pub(crate) mod tls;
      +
      +pub(crate) use self::grpc_timeout::GrpcTimeout;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +use crate::transport::channel::BoxFuture;
      +use hyper_util::rt::TokioExecutor;
      +use std::{future::Future, sync::Arc};
      +
      +pub(crate) use hyper::rt::Executor;
      +
      +#[derive(Clone)]
      +pub(crate) struct SharedExec {
      +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
      +}
      +
      +impl SharedExec {
      +    pub(crate) fn new<E>(exec: E) -> Self
      +    where
      +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
      +    {
      +        Self {
      +            inner: Arc::new(exec),
      +        }
      +    }
      +
      +    pub(crate) fn tokio() -> Self {
      +        Self::new(TokioExecutor::new())
      +    }
      +}
      +
      +impl<F> Executor<F> for SharedExec
      +where
      +    F: Future<Output = ()> + Send + 'static,
      +{
      +    fn execute(&self, fut: F) {
      +        self.inner.execute(Box::pin(fut))
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +use super::Connected;
      +use std::sync::Arc;
      +
      +/// Connection info for Unix domain socket streams.
      +///
      +/// This type will be accessible through [request extensions][ext] if you're using
      +/// a unix stream.
      +///
      +/// See [Connected] for more details.
      +///
      +/// [ext]: crate::Request::extensions
      +#[derive(Clone, Debug)]
      +pub struct UdsConnectInfo {
      +    /// Peer address. This will be "unnamed" for client unix sockets.
      +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
      +    /// Process credentials for the unix socket.
      +    pub peer_cred: Option<tokio::net::unix::UCred>,
      +}
      +
      +impl Connected for tokio::net::UnixStream {
      +    type ConnectInfo = UdsConnectInfo;
      +
      +    fn connect_info(&self) -> Self::ConnectInfo {
      +        UdsConnectInfo {
      +            peer_addr: self.peer_addr().ok().map(Arc::new),
      +            peer_cred: self.peer_cred().ok(),
      +        }
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      // Copyright (c) 2019 Nuclear Furnace
      +//
      +// 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
       
      @@ -12355,7 +16959,40 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      +
      Copyright (c) 2014 Alex Crichton
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2014 Carl Lerche and other MIO contributors
       
      @@ -12382,7 +17019,6 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      Copyright (c) 2014-2019 Geoffroy Couprie
      @@ -12411,9 +17047,36 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2014-2021 Sean McArthur
      +                
      Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2014-2026 Sean McArthur
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -12438,34 +17101,8 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2014-2025 Sean McArthur
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2015 Jonathan Reem
       
      @@ -12498,34 +17135,34 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2015 fangyuanziti
      -
      -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.
      +                
      Copyright (c) 2015 fangyuanziti
      +
      +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.
       
    • MIT License

      Used by:

      Copyright (c) 2015 steffengy
       
      @@ -12540,16 +17177,28 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES
                       

      MIT License

      Used by:

      -
      Copyright (c) 2016 Paul Masurel
      +                
      Copyright (c) 2015-2024 Doug Tangren
       
      -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:
      +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 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.
      -
      +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.
    • MIT License

      @@ -12611,8 +17260,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

      MIT License

      Used by:

      Copyright (c) 2017 h2 authors
       
      @@ -12645,7 +17293,7 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      Copyright (c) 2018 Carl Lerche
       
      @@ -12678,52 +17326,34 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2018 Paul Masurel
      +                
      Copyright (c) 2018 Tom Parker-Shemilt
       
      -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:
      +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 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.
      -
      +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.
    • MIT License

      Used by:

      -
      Copyright (c) 2018 by Quickwit, Inc. 
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2018-2019 Sean McArthur
       
      @@ -12814,7 +17444,7 @@ DEALINGS IN THE SOFTWARE.
                       

      Used by:

      Copyright (c) 2019 Carl Lerche
       
      @@ -12901,44 +17531,14 @@ SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019 Hyper Contributors
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2019 Tokio Contributors
       
      @@ -12973,7 +17573,7 @@ DEALINGS IN THE SOFTWARE.
                       
                       
      Copyright (c) 2019 Tower Contributors
       
      @@ -13006,10 +17606,9 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019-2021 Tower Contributors
      +                
      Copyright (c) 2019 axum Contributors
       
       Permission is hereby granted, free of charge, to any
       person obtaining a copy of this software and associated
      @@ -13040,9 +17639,10 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
      +                
      Copyright (c) 2019-2021 Tower Contributors
       
       Permission is hereby granted, free of charge, to any
       person obtaining a copy of this software and associated
      @@ -13106,7 +17706,94 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      +
      Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias
      +
      +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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2021 Metrics Contributors
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2023-2025 Sean McArthur
       
      @@ -13127,36 +17814,6 @@ 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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2024 by Quickwit Inc.
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2024-Present Paul Masurel
      -
      -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.
       
    • @@ -13164,6 +17821,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

      Used by:

      Copyright 2016 Nika Layzell
       
      @@ -13171,6 +17829,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
       
       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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2019 gRPC authors.
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2020 David Koloski
      +
      +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.
       
    • @@ -13193,25 +17893,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

      MIT License

      Used by:

      -
      Includes portions of humantime
      -Copyright (c) 2016 The humantime Developers
      +                
      Copyright 2021 David Koloski
       
       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.
      -
      -
       
    • MIT License

      Used by:

      +
      Copyright 2023 David Koloski
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2023 David Koloski
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2024 David Koloski
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13234,6 +17982,65 @@ 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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2016 Michael Ma
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2016 fengcen
      +Copyright (c) 2019 svartalf
      +
      +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.
      +
    • MIT License

      @@ -13356,9 +18163,41 @@ SOFTWARE.

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2017 Sam Rijs
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13374,6 +18213,35 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2018 Canop
      +
      +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
      @@ -13417,7 +18285,36 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2018 sgodwincs
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13446,7 +18343,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13475,36 +18372,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      -
      MIT License
      -
      -Copyright (c) 2019 Aeledfyr
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      MIT License
       
      @@ -13533,8 +18401,37 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2019 Kornel
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13563,7 +18460,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13617,6 +18514,40 @@ 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.
       
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2019–2025 axum Contributors
      +
      +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.
    • MIT License

      @@ -13651,11 +18582,31 @@ SOFTWARE.

      MIT License

      Used by:

      MIT License
       
      -Copyright (c) 2020 David Purdum
      +Copyright (c) 2020 Katharos Technology
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020 Scripta Qumranica Electronica
      +
      +Created by Bronson Brown-deVost
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -13680,13 +18631,11 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      -Copyright (c) 2020 Scripta Qumranica Electronica
      -
      -Created by Bronson Brown-deVost
      +Copyright (c) 2020 magiclen.org (Ron Li)
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -13727,6 +18676,93 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020-2022 Oliver Margetts
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020-2026 Nugine
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2021 Adel Prokurov
      +
      +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
      @@ -13756,6 +18792,35 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2022 Arthur Silva
      +
      +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
      @@ -13770,6 +18835,7 @@ SOFTWARE.
                       

      Used by:

      MIT License
       
      @@ -13785,6 +18851,35 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2022 Jeroen Van Der Donckt
      +
      +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
      @@ -13826,7 +18921,36 @@ SOFTWARE.

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2022 sarah
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13855,8 +18979,8 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13885,8 +19009,66 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2023 sarah
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2024 Spire Team
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13910,30 +19092,67 @@ 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.
       
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2025 rutrum
      +
      +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.
    • MIT License

      Used by:

      MIT License
      @@ -13960,9 +19179,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13991,7 +19210,100 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) [2021] [Marvin Countryman]
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Permission is hereby granted, free of charge, to any person obtaining
       a copy of this software and associated documentation files (the
      @@ -14017,12 +19329,42 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      The MIT License (MIT)
      +                
      Portions of this project are derived from atty, which bears the following
      +copyright notice and permission notice:
       
      -Copyright (c) 2014 Benjamin Sago
      -Copyright (c) 2021-2022 The Nushell Project Developers
      +Copyright (c) 2015-2019 Doug Tangren
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License
      +
      +Copyright 2015 The Fancy Regex Authors.
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14031,23 +19373,24 @@ 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 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.
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
       
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14070,13 +19413,63 @@ 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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Mathijs van de Nes
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Y. T. CHUNG
      +
      +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.
      +
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14104,21 +19497,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
       
      -Copyright (c) 2015 Andrew Gallant
      +Copyright (c) 2015 
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14127,28 +19510,39 @@ 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 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.
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
       
    • MIT License

      Used by:

      The MIT License (MIT)
       
       Copyright (c) 2015 Andrew Gallant
      -Copyright (c) 2019 Paul Masurel
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14198,6 +19592,37 @@ 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.
       
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Carl Lerche + nix-rust Authors
      +
      +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.
       
    • @@ -14229,6 +19654,64 @@ 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. +
    • + +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Gerd Zellweger
      +
      +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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Guillaume Gomez
      +
      +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.
      +
       
    • @@ -14264,11 +19747,102 @@ SOFTWARE.

      MIT License

      Used by:

      The MIT License (MIT)
       
      -Copyright (c) 2015 Vincent Prouillet
      +Copyright (c) 2015 Katsu Kawakami & Rustyline authors
      +
      +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.
      +
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Markus Westerlind
      +
      +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.
      +
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Michael Sproul
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015-2020 the fiat-crypto authors (see
      +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14293,7 +19867,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14309,6 +19883,35 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2016 nabijaczleweli
      +
      +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
      @@ -14352,6 +19955,7 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
      @@ -14382,8 +19986,36 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      The MIT License (MIT)
      +
      +Copyright (c) 2019 Simon Heath
      +
      +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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      The MIT License (MIT)
       
      @@ -14450,6 +20082,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
       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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Benjamin Sago
      +Copyright (c) 2021-2022 The Nushell Project 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.
       
    • @@ -14514,8 +20176,9 @@ SOFTWARE.
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14568,6 +20231,387 @@ 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.
      +
      + +
    • +

      Mozilla Public License 2.0

      +

      Used by:

      + +
      Mozilla Public License Version 2.0
      +==================================
      +
      +1. Definitions
      +--------------
      +
      +1.1. "Contributor"
      +    means each individual or legal entity that creates, contributes to
      +    the creation of, or owns Covered Software.
      +
      +1.2. "Contributor Version"
      +    means the combination of the Contributions of others (if any) used
      +    by a Contributor and that particular Contributor's Contribution.
      +
      +1.3. "Contribution"
      +    means Covered Software of a particular Contributor.
      +
      +1.4. "Covered Software"
      +    means Source Code Form to which the initial Contributor has attached
      +    the notice in Exhibit A, the Executable Form of such Source Code
      +    Form, and Modifications of such Source Code Form, in each case
      +    including portions thereof.
      +
      +1.5. "Incompatible With Secondary Licenses"
      +    means
      +
      +    (a) that the initial Contributor has attached the notice described
      +        in Exhibit B to the Covered Software; or
      +
      +    (b) that the Covered Software was made available under the terms of
      +        version 1.1 or earlier of the License, but not also under the
      +        terms of a Secondary License.
      +
      +1.6. "Executable Form"
      +    means any form of the work other than Source Code Form.
      +
      +1.7. "Larger Work"
      +    means a work that combines Covered Software with other material, in 
      +    a separate file or files, that is not Covered Software.
      +
      +1.8. "License"
      +    means this document.
      +
      +1.9. "Licensable"
      +    means having the right to grant, to the maximum extent possible,
      +    whether at the time of the initial grant or subsequently, any and
      +    all of the rights conveyed by this License.
      +
      +1.10. "Modifications"
      +    means any of the following:
      +
      +    (a) any file in Source Code Form that results from an addition to,
      +        deletion from, or modification of the contents of Covered
      +        Software; or
      +
      +    (b) any new file in Source Code Form that contains any Covered
      +        Software.
      +
      +1.11. "Patent Claims" of a Contributor
      +    means any patent claim(s), including without limitation, method,
      +    process, and apparatus claims, in any patent Licensable by such
      +    Contributor that would be infringed, but for the grant of the
      +    License, by the making, using, selling, offering for sale, having
      +    made, import, or transfer of either its Contributions or its
      +    Contributor Version.
      +
      +1.12. "Secondary License"
      +    means either the GNU General Public License, Version 2.0, the GNU
      +    Lesser General Public License, Version 2.1, the GNU Affero General
      +    Public License, Version 3.0, or any later versions of those
      +    licenses.
      +
      +1.13. "Source Code Form"
      +    means the form of the work preferred for making modifications.
      +
      +1.14. "You" (or "Your")
      +    means an individual or a legal entity exercising rights under this
      +    License. For legal entities, "You" includes any entity that
      +    controls, is controlled by, or is under common control with You. For
      +    purposes of this definition, "control" means (a) the power, direct
      +    or indirect, to cause the direction or management of such entity,
      +    whether by contract or otherwise, or (b) ownership of more than
      +    fifty percent (50%) of the outstanding shares or beneficial
      +    ownership of such entity.
      +
      +2. License Grants and Conditions
      +--------------------------------
      +
      +2.1. Grants
      +
      +Each Contributor hereby grants You a world-wide, royalty-free,
      +non-exclusive license:
      +
      +(a) under intellectual property rights (other than patent or trademark)
      +    Licensable by such Contributor to use, reproduce, make available,
      +    modify, display, perform, distribute, and otherwise exploit its
      +    Contributions, either on an unmodified basis, with Modifications, or
      +    as part of a Larger Work; and
      +
      +(b) under Patent Claims of such Contributor to make, use, sell, offer
      +    for sale, have made, import, and otherwise transfer either its
      +    Contributions or its Contributor Version.
      +
      +2.2. Effective Date
      +
      +The licenses granted in Section 2.1 with respect to any Contribution
      +become effective for each Contribution on the date the Contributor first
      +distributes such Contribution.
      +
      +2.3. Limitations on Grant Scope
      +
      +The licenses granted in this Section 2 are the only rights granted under
      +this License. No additional rights or licenses will be implied from the
      +distribution or licensing of Covered Software under this License.
      +Notwithstanding Section 2.1(b) above, no patent license is granted by a
      +Contributor:
      +
      +(a) for any code that a Contributor has removed from Covered Software;
      +    or
      +
      +(b) for infringements caused by: (i) Your and any other third party's
      +    modifications of Covered Software, or (ii) the combination of its
      +    Contributions with other software (except as part of its Contributor
      +    Version); or
      +
      +(c) under Patent Claims infringed by Covered Software in the absence of
      +    its Contributions.
      +
      +This License does not grant any rights in the trademarks, service marks,
      +or logos of any Contributor (except as may be necessary to comply with
      +the notice requirements in Section 3.4).
      +
      +2.4. Subsequent Licenses
      +
      +No Contributor makes additional grants as a result of Your choice to
      +distribute the Covered Software under a subsequent version of this
      +License (see Section 10.2) or under the terms of a Secondary License (if
      +permitted under the terms of Section 3.3).
      +
      +2.5. Representation
      +
      +Each Contributor represents that the Contributor believes its
      +Contributions are its original creation(s) or it has sufficient rights
      +to grant the rights to its Contributions conveyed by this License.
      +
      +2.6. Fair Use
      +
      +This License is not intended to limit any rights You have under
      +applicable copyright doctrines of fair use, fair dealing, or other
      +equivalents.
      +
      +2.7. Conditions
      +
      +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
      +in Section 2.1.
      +
      +3. Responsibilities
      +-------------------
      +
      +3.1. Distribution of Source Form
      +
      +All distribution of Covered Software in Source Code Form, including any
      +Modifications that You create or to which You contribute, must be under
      +the terms of this License. You must inform recipients that the Source
      +Code Form of the Covered Software is governed by the terms of this
      +License, and how they can obtain a copy of this License. You may not
      +attempt to alter or restrict the recipients' rights in the Source Code
      +Form.
      +
      +3.2. Distribution of Executable Form
      +
      +If You distribute Covered Software in Executable Form then:
      +
      +(a) such Covered Software must also be made available in Source Code
      +    Form, as described in Section 3.1, and You must inform recipients of
      +    the Executable Form how they can obtain a copy of such Source Code
      +    Form by reasonable means in a timely manner, at a charge no more
      +    than the cost of distribution to the recipient; and
      +
      +(b) You may distribute such Executable Form under the terms of this
      +    License, or sublicense it under different terms, provided that the
      +    license for the Executable Form does not attempt to limit or alter
      +    the recipients' rights in the Source Code Form under this License.
      +
      +3.3. Distribution of a Larger Work
      +
      +You may create and distribute a Larger Work under terms of Your choice,
      +provided that You also comply with the requirements of this License for
      +the Covered Software. If the Larger Work is a combination of Covered
      +Software with a work governed by one or more Secondary Licenses, and the
      +Covered Software is not Incompatible With Secondary Licenses, this
      +License permits You to additionally distribute such Covered Software
      +under the terms of such Secondary License(s), so that the recipient of
      +the Larger Work may, at their option, further distribute the Covered
      +Software under the terms of either this License or such Secondary
      +License(s).
      +
      +3.4. Notices
      +
      +You may not remove or alter the substance of any license notices
      +(including copyright notices, patent notices, disclaimers of warranty,
      +or limitations of liability) contained within the Source Code Form of
      +the Covered Software, except that You may alter any license notices to
      +the extent required to remedy known factual inaccuracies.
      +
      +3.5. Application of Additional Terms
      +
      +You may choose to offer, and to charge a fee for, warranty, support,
      +indemnity or liability obligations to one or more recipients of Covered
      +Software. However, You may do so only on Your own behalf, and not on
      +behalf of any Contributor. You must make it absolutely clear that any
      +such warranty, support, indemnity, or liability obligation is offered by
      +You alone, and You hereby agree to indemnify every Contributor for any
      +liability incurred by such Contributor as a result of warranty, support,
      +indemnity or liability terms You offer. You may include additional
      +disclaimers of warranty and limitations of liability specific to any
      +jurisdiction.
      +
      +4. Inability to Comply Due to Statute or Regulation
      +---------------------------------------------------
      +
      +If it is impossible for You to comply with any of the terms of this
      +License with respect to some or all of the Covered Software due to
      +statute, judicial order, or regulation then You must: (a) comply with
      +the terms of this License to the maximum extent possible; and (b)
      +describe the limitations and the code they affect. Such description must
      +be placed in a text file included with all distributions of the Covered
      +Software under this License. Except to the extent prohibited by statute
      +or regulation, such description must be sufficiently detailed for a
      +recipient of ordinary skill to be able to understand it.
      +
      +5. Termination
      +--------------
      +
      +5.1. The rights granted under this License will terminate automatically
      +if You fail to comply with any of its terms. However, if You become
      +compliant, then the rights granted under this License from a particular
      +Contributor are reinstated (a) provisionally, unless and until such
      +Contributor explicitly and finally terminates Your grants, and (b) on an
      +ongoing basis, if such Contributor fails to notify You of the
      +non-compliance by some reasonable means prior to 60 days after You have
      +come back into compliance. Moreover, Your grants from a particular
      +Contributor are reinstated on an ongoing basis if such Contributor
      +notifies You of the non-compliance by some reasonable means, this is the
      +first time You have received notice of non-compliance with this License
      +from such Contributor, and You become compliant prior to 30 days after
      +Your receipt of the notice.
      +
      +5.2. If You initiate litigation against any entity by asserting a patent
      +infringement claim (excluding declaratory judgment actions,
      +counter-claims, and cross-claims) alleging that a Contributor Version
      +directly or indirectly infringes any patent, then the rights granted to
      +You by any and all Contributors for the Covered Software under Section
      +2.1 of this License shall terminate.
      +
      +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
      +end user license agreements (excluding distributors and resellers) which
      +have been validly granted by You or Your distributors under this License
      +prior to termination shall survive termination.
      +
      +************************************************************************
      +*                                                                      *
      +*  6. Disclaimer of Warranty                                           *
      +*  -------------------------                                           *
      +*                                                                      *
      +*  Covered Software is provided under this License on an "as is"       *
      +*  basis, without warranty of any kind, either expressed, implied, or  *
      +*  statutory, including, without limitation, warranties that the       *
      +*  Covered Software is free of defects, merchantable, fit for a        *
      +*  particular purpose or non-infringing. The entire risk as to the     *
      +*  quality and performance of the Covered Software is with You.        *
      +*  Should any Covered Software prove defective in any respect, You     *
      +*  (not any Contributor) assume the cost of any necessary servicing,   *
      +*  repair, or correction. This disclaimer of warranty constitutes an   *
      +*  essential part of this License. No use of any Covered Software is   *
      +*  authorized under this License except under this disclaimer.         *
      +*                                                                      *
      +************************************************************************
      +
      +************************************************************************
      +*                                                                      *
      +*  7. Limitation of Liability                                          *
      +*  --------------------------                                          *
      +*                                                                      *
      +*  Under no circumstances and under no legal theory, whether tort      *
      +*  (including negligence), contract, or otherwise, shall any           *
      +*  Contributor, or anyone who distributes Covered Software as          *
      +*  permitted above, be liable to You for any direct, indirect,         *
      +*  special, incidental, or consequential damages of any character      *
      +*  including, without limitation, damages for lost profits, loss of    *
      +*  goodwill, work stoppage, computer failure or malfunction, or any    *
      +*  and all other commercial damages or losses, even if such party      *
      +*  shall have been informed of the possibility of such damages. This   *
      +*  limitation of liability shall not apply to liability for death or   *
      +*  personal injury resulting from such party's negligence to the       *
      +*  extent applicable law prohibits such limitation. Some               *
      +*  jurisdictions do not allow the exclusion or limitation of           *
      +*  incidental or consequential damages, so this exclusion and          *
      +*  limitation may not apply to You.                                    *
      +*                                                                      *
      +************************************************************************
      +
      +8. Litigation
      +-------------
      +
      +Any litigation relating to this License may be brought only in the
      +courts of a jurisdiction where the defendant maintains its principal
      +place of business and such litigation shall be governed by laws of that
      +jurisdiction, without reference to its conflict-of-law provisions.
      +Nothing in this Section shall prevent a party's ability to bring
      +cross-claims or counter-claims.
      +
      +9. Miscellaneous
      +----------------
      +
      +This License represents the complete agreement concerning the subject
      +matter hereof. If any provision of this License is held to be
      +unenforceable, such provision shall be reformed only to the extent
      +necessary to make it enforceable. Any law or regulation which provides
      +that the language of a contract shall be construed against the drafter
      +shall not be used to construe this License against a Contributor.
      +
      +10. Versions of the License
      +---------------------------
      +
      +10.1. New Versions
      +
      +Mozilla Foundation is the license steward. Except as provided in Section
      +10.3, no one other than the license steward has the right to modify or
      +publish new versions of this License. Each version will be given a
      +distinguishing version number.
      +
      +10.2. Effect of New Versions
      +
      +You may distribute the Covered Software under the terms of the version
      +of the License under which You originally received the Covered Software,
      +or under the terms of any subsequent version published by the license
      +steward.
      +
      +10.3. Modified Versions
      +
      +If you create software not governed by this License, and you want to
      +create a new license for such software, you may create and use a
      +modified version of this License if you rename the license and remove
      +any references to the name of the license steward (except to note that
      +such modified license differs from this License).
      +
      +10.4. Distributing Source Code Form that is Incompatible With Secondary
      +Licenses
      +
      +If You choose to distribute Source Code Form that is Incompatible With
      +Secondary Licenses under the terms of this version of the License, the
      +notice described in Exhibit B of this License must be attached.
      +
      +Exhibit A - Source Code Form License Notice
      +-------------------------------------------
      +
      +  This Source Code Form is subject to the terms of the Mozilla Public
      +  License, v. 2.0. If a copy of the MPL was not distributed with this
      +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
      +
      +If it is not possible or desirable to put the notice in a particular
      +file, then You may include the notice in a location (such as a LICENSE
      +file in a relevant directory) where a recipient would be likely to look
      +for such a notice.
      +
      +You may add additional accurate notices of copyright ownership.
      +
      +Exhibit B - "Incompatible With Secondary Licenses" Notice
      +---------------------------------------------------------
      +
      +  This Source Code Form is "Incompatible With Secondary Licenses", as
      +  defined by the Mozilla Public License, v. 2.0.
       
    • @@ -14949,187 +20993,13 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. -
    • - -
    • -

      OpenSSL License

      -

      Used by:

      - -
      /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
      - * All rights reserved.
      - *
      - * This package is an SSL implementation written
      - * by Eric Young (eay@cryptsoft.com).
      - * The implementation was written so as to conform with Netscapes SSL.
      - *
      - * This library is free for commercial and non-commercial use as long as
      - * the following conditions are aheared to.  The following conditions
      - * apply to all code found in this distribution, be it the RC4, RSA,
      - * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
      - * included with this distribution is covered by the same copyright terms
      - * except that the holder is Tim Hudson (tjh@cryptsoft.com).
      - *
      - * Copyright remains Eric Young's, and as such any Copyright notices in
      - * the code are not to be removed.
      - * If this package is used in a product, Eric Young should be given attribution
      - * as the author of the parts of the library used.
      - * This can be in the form of a textual message at program startup or
      - * in documentation (online or textual) provided with the package.
      - *
      - * Redistribution and use in source and binary forms, with or without
      - * modification, are permitted provided that the following conditions
      - * are met:
      - * 1. Redistributions of source code must retain the copyright
      - *    notice, this list of conditions and the following disclaimer.
      - * 2. Redistributions in binary form must reproduce the above copyright
      - *    notice, this list of conditions and the following disclaimer in the
      - *    documentation and/or other materials provided with the distribution.
      - * 3. All advertising materials mentioning features or use of this software
      - *    must display the following acknowledgement:
      - *    "This product includes cryptographic software written by
      - *     Eric Young (eay@cryptsoft.com)"
      - *    The word 'cryptographic' can be left out if the rouines from the library
      - *    being used are not cryptographic related :-).
      - * 4. If you include any Windows specific code (or a derivative thereof) from
      - *    the apps directory (application code) you must include an acknowledgement:
      - *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
      - *
      - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
      - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
      - * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
      - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
      - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
      - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
      - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
      - * SUCH DAMAGE.
      - *
      - * The licence and distribution terms for any publically available version or
      - * derivative of this code cannot be changed.  i.e. this code cannot simply be
      - * copied and put under another distribution licence
      - * [including the GNU Public Licence.]
      - */
      -/* ====================================================================
      - * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
      - *
      - * Redistribution and use in source and binary forms, with or without
      - * modification, are permitted provided that the following conditions
      - * are met:
      - *
      - * 1. Redistributions of source code must retain the above copyright
      - *    notice, this list of conditions and the following disclaimer.
      - *
      - * 2. Redistributions in binary form must reproduce the above copyright
      - *    notice, this list of conditions and the following disclaimer in
      - *    the documentation and/or other materials provided with the
      - *    distribution.
      - *
      - * 3. All advertising materials mentioning features or use of this
      - *    software must display the following acknowledgment:
      - *    "This product includes software developed by the OpenSSL Project
      - *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
      - *
      - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
      - *    endorse or promote products derived from this software without
      - *    prior written permission. For written permission, please contact
      - *    openssl-core@openssl.org.
      - *
      - * 5. Products derived from this software may not be called "OpenSSL"
      - *    nor may "OpenSSL" appear in their names without prior written
      - *    permission of the OpenSSL Project.
      - *
      - * 6. Redistributions of any form whatsoever must retain the following
      - *    acknowledgment:
      - *    "This product includes software developed by the OpenSSL Project
      - *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
      - *
      - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
      - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
      - * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
      - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
      - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
      - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
      - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
      - * OF THE POSSIBILITY OF SUCH DAMAGE.
      - * ====================================================================
      - *
      - * This product includes cryptographic software written by Eric Young
      - * (eay@cryptsoft.com).  This product includes software written by Tim
      - * Hudson (tjh@cryptsoft.com).
      - *
      - */
      -
      -#include <openssl/ssl.h>
      -
      -#if !defined(OPENSSL_WINDOWS) && !defined(OPENSSL_PNACL) && \
      -    !defined(OPENSSL_NO_FILESYSTEM)
      -
      -#include <dirent.h>
      -#include <errno.h>
      -#include <string.h>
      -
      -#include <openssl/err.h>
      -#include <openssl/mem.h>
      -
      -
      -int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
      -                                       const char *path) {
      -  DIR *dir = opendir(path);
      -  if (dir == NULL) {
      -    OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
      -    ERR_add_error_data(3, "opendir('", dir, "')");
      -    return 0;
      -  }
      -
      -  int ret = 0;
      -  for (;;) {
      -    // |readdir| may fail with or without setting |errno|.
      -    errno = 0;
      -    struct dirent *dirent = readdir(dir);
      -    if (dirent == NULL) {
      -      if (errno) {
      -        OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
      -        ERR_add_error_data(3, "readdir('", path, "')");
      -      } else {
      -        ret = 1;
      -      }
      -      break;
      -    }
      -
      -    char buf[1024];
      -    if (strlen(path) + strlen(dirent->d_name) + 2 > sizeof(buf)) {
      -      OPENSSL_PUT_ERROR(SSL, SSL_R_PATH_TOO_LONG);
      -      break;
      -    }
      -
      -    int r = snprintf(buf, sizeof(buf), "%s/%s", path, dirent->d_name);
      -    if (r <= 0 ||
      -        r >= (int)sizeof(buf) ||
      -        !SSL_add_file_cert_subjects_to_stack(stack, buf)) {
      -      break;
      -    }
      -  }
      -
      -  closedir(dir);
      -  return ret;
      -}
      -
      -#endif  // !WINDOWS && !PNACL && !OPENSSL_NO_FILESYSTEM
       
    • Unicode License v3

      Used by:

      UNICODE LICENSE V3
       
      @@ -15176,24 +21046,28 @@ authorization of the copyright holder.
                       

      Unicode License v3

      Used by:

      UNICODE LICENSE V3
       
      @@ -15242,12 +21116,63 @@ SPDX-License-Identifier: Unicode-3.0
       Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
       ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
       
      +
    • +
    • +

      zlib License

      +

      Used by:

      + +
      Copyright (c) 2021 Matias Rodriguez.
      +
      +This software is provided 'as-is', without any express or implied
      +warranty. In no event will the authors be held liable for any damages
      +arising from the use of this software.
      +
      +Permission is granted to anyone to use this software for any purpose,
      +including commercial applications, and to alter it and redistribute it
      +freely, subject to the following restrictions:
      +
      +1. The origin of this software must not be misrepresented; you must not
      +   claim that you wrote the original software. If you use this software
      +   in a product, an acknowledgment in the product documentation would be
      +   appreciated but is not required.
      +2. Altered source versions must be plainly marked as such, and must not be
      +   misrepresented as being the original software.
      +3. This notice may not be removed or altered from any source distribution.
      +
    • +
    • +

      zlib License

      +

      Used by:

      + +
      Copyright (c) 2023 Matias Rodriguez.
      +
      +This software is provided 'as-is', without any express or implied
      +warranty. In no event will the authors be held liable for any damages
      +arising from the use of this software.
      +
      +Permission is granted to anyone to use this software for any purpose,
      +including commercial applications, and to alter it and redistribute it
      +freely, subject to the following restrictions:
      +
      +1. The origin of this software must not be misrepresented; you must not
      +   claim that you wrote the original software. If you use this software
      +   in a product, an acknowledgment in the product documentation would be
      +   appreciated but is not required.
      +2. Altered source versions must be plainly marked as such, and must not be
      +   misrepresented as being the original software.
      +3. This notice may not be removed or altered from any source distribution.
    • zlib License

      Used by:

      Copyright (c) 2024 Orson Peters
       
      diff --git a/ci/build_cli_wheels.py b/ci/build_cli_wheels.py
      new file mode 100644
      index 000000000..9ae9f627b
      --- /dev/null
      +++ b/ci/build_cli_wheels.py
      @@ -0,0 +1,88 @@
      +"""Build lancedb-tools wheels from a complete, checksummed CLI release."""
      +
      +import argparse
      +import re
      +import shutil
      +import subprocess
      +import sys
      +import tarfile
      +import tempfile
      +from pathlib import Path
      +
      +from ci.package_cli import NOTICES, archive_stem, verify_checksums
      +
      +PLATFORMS = {
      +    "aarch64-apple-darwin": "macosx_14_0_arm64",
      +    "aarch64-unknown-linux-gnu": "manylinux_2_28_aarch64",
      +    "x86_64-unknown-linux-gnu": "manylinux_2_28_x86_64",
      +}
      +
      +
      +def build_wheels(tag: str, archives: Path, output: Path):
      +    if not re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-beta\.[0-9]+)?", tag):
      +        raise ValueError(f"Expected a stable or beta CLI release tag, got {tag!r}")
      +    version = tag[1:]
      +    wheel_version = version.replace("-beta.", "b")
      +    verify_checksums(archives, version)
      +    output.mkdir(parents=True, exist_ok=True)
      +
      +    for target, platform in PLATFORMS.items():
      +        stem = archive_stem(version, target)
      +        with tempfile.TemporaryDirectory(dir=output) as tmp:
      +            stage = Path(tmp)
      +            with tarfile.open(archives / f"{stem}.tar.gz", "r:gz") as archive:
      +                archive.extractall(stage, filter="data")
      +            root = stage / "wheel"
      +            package = root / "lancedb_tools"
      +            package.mkdir(parents=True)
      +            (stage / stem / "lancedb").rename(package / "lancedb")
      +            shutil.copyfile(
      +                Path(__file__).parent / "cli_wheel/launcher.py", package / "__init__.py"
      +            )
      +
      +            info = root / f"lancedb_tools-{wheel_version}.dist-info"
      +            licenses = info / "licenses"
      +            licenses.mkdir(parents=True)
      +            for notice in NOTICES:
      +                (stage / stem / notice).rename(licenses / notice)
      +            (info / "METADATA").write_text(
      +                "Metadata-Version: 2.4\n"
      +                "Name: lancedb-tools\n"
      +                f"Version: {wheel_version}\n"
      +                "Summary: Command-line client for LanceDB SQL, profiles, and authentication\n"
      +                "Requires-Python: >=3.8\n"
      +                "License-Expression: Apache-2.0\n"
      +                + "".join(f"License-File: {notice}\n" for notice in NOTICES)
      +                + "Project-URL: Source, https://github.com/lancedb/lancedb\n"
      +                "Description-Content-Type: text/plain\n\n"
      +                "Run LanceDB SQL, manage connection profiles, and authenticate to a deployment.\n"
      +                "Use pipx install lancedb-tools or uvx --from lancedb-tools lancedb --help.\n"
      +                "Supports Apple Silicon on macOS 14+ and Linux ARM64 or x86-64 with glibc 2.28+.\n"
      +                "Linux x86-64 requires AVX2, FMA, and F16C.\n"
      +            )
      +            (info / "WHEEL").write_text(
      +                "Wheel-Version: 1.0\nGenerator: ci.build_cli_wheels\n"
      +                f"Root-Is-Purelib: false\nTag: py3-none-{platform}\n"
      +            )
      +            (info / "entry_points.txt").write_text(
      +                "[console_scripts]\nlancedb = lancedb_tools:main\n"
      +            )
      +            subprocess.run(
      +                [sys.executable, "-m", "wheel", "pack", str(root), "-d", str(stage)],
      +                check=True,
      +            )
      +            (wheel,) = stage.glob("*.whl")
      +            wheel.replace(output / wheel.name)
      +
      +
      +if __name__ == "__main__":
      +    parser = argparse.ArgumentParser(description=__doc__)
      +    parser.add_argument("tag")
      +    parser.add_argument(
      +        "archives",
      +        type=Path,
      +        help="Directory with the three release archives and SHA256SUMS",
      +    )
      +    parser.add_argument("output", type=Path)
      +    args = parser.parse_args()
      +    build_wheels(args.tag, args.archives, args.output)
      diff --git a/ci/build_no_lock.py b/ci/build_no_lock.py
      index 6ec156432..17d9ad333 100644
      --- a/ci/build_no_lock.py
      +++ b/ci/build_no_lock.py
      @@ -54,6 +54,7 @@ def main() -> int:
               ["cargo", "metadata", "--format-version=1", "--no-deps", "--all-features"],
               stdout=subprocess.PIPE,
               text=True,
      +        check=False,
           )
           if metadata.returncode:
               return metadata.returncode
      @@ -68,7 +69,7 @@ def main() -> int:
               "--tests",
               # Bound simultaneous compiler/linker temporary outputs as well as retained files.
               "--jobs",
      -        "1",
      +        "2",
               "--message-format=json,json-diagnostic-rendered-ansi",
           ]
           cleanup_failed = False
      diff --git a/ci/cli_wheel/launcher.py b/ci/cli_wheel/launcher.py
      new file mode 100644
      index 000000000..ae71a936f
      --- /dev/null
      +++ b/ci/cli_wheel/launcher.py
      @@ -0,0 +1,20 @@
      +"""Console entry point for the bundled LanceDB CLI."""
      +
      +import os
      +import platform
      +import sys
      +from pathlib import Path
      +
      +
      +def main():
      +    if sys.platform == "linux" and platform.machine() == "x86_64":
      +        # manylinux tags describe glibc and architecture, not CPU extensions.
      +        with open("/proc/cpuinfo") as cpuinfo:
      +            flags = next(
      +                (line.split() for line in cpuinfo if line.startswith("flags")), []
      +            )
      +        if not {"avx2", "fma", "f16c"}.issubset(flags):
      +            sys.exit("The LanceDB Linux x86-64 binary requires AVX2, FMA, and F16C.")
      +
      +    executable = Path(__file__).with_name("lancedb")
      +    os.execv(executable, [str(executable), *sys.argv[1:]])
      diff --git a/ci/cli_wheel/test_install.sh b/ci/cli_wheel/test_install.sh
      new file mode 100644
      index 000000000..4d8c53bc1
      --- /dev/null
      +++ b/ci/cli_wheel/test_install.sh
      @@ -0,0 +1,24 @@
      +#!/usr/bin/env bash
      +# Exercise resolver platform selection and both tools' installed entry points.
      +set -euo pipefail
      +
      +tag=${1:?pass the CLI release tag}
      +wheels=${2:?pass the absolute wheel directory}
      +version=${tag#v}
      +spec="lancedb-tools==${version/-beta./b}"
      +test_env=$(mktemp -d)
      +trap 'rm -rf "$test_env"' EXIT
      +export XDG_CONFIG_HOME="$test_env/config" UV_CACHE_DIR="$test_env/uv"
      +export XDG_STATE_HOME="$test_env/state" XDG_DATA_HOME="$test_env/data"
      +export PIPX_HOME="$test_env/pipx" PIPX_BIN_DIR="$test_env/bin"
      +export PIPX_SHARED_LIBS="$test_env/shared" PIPX_MAN_DIR="$test_env/man"
      +
      +check_cli() {
      +    "$@" --version | grep -Fx "lancedb $version"
      +    "$@" profile list | grep -w local
      +}
      +
      +check_cli uvx --no-index --find-links "$wheels" --from "$spec" lancedb
      +python -m pip download --no-index --find-links "$wheels" --dest "$test_env/native" "$spec"
      +pipx install --backend pip "$test_env/native/"*.whl
      +check_cli "$PIPX_BIN_DIR/lancedb"
      diff --git a/ci/tests/test_build_no_lock.py b/ci/tests/test_build_no_lock.py
      index 634e8d333..f760d2bfc 100644
      --- a/ci/tests/test_build_no_lock.py
      +++ b/ci/tests/test_build_no_lock.py
      @@ -88,9 +88,11 @@ class BuildNoLockTest(unittest.TestCase):
                   self.assertTrue((target / "fixture_cli").is_file())
                   # Cargo guarantees this binary for test execution, not compile-time reads.
                   subprocess.run([str(target / "fixture_cli")], check=True)
      -            self.assertTrue(list((target / "deps").glob("libartifact_fixture*.rlib")))
      -            self.assertTrue(list((target / "build").glob("*/build-script-build")))
      -            self.assertTrue(list((target / "build").glob("*/out/generated.rs")))
      +            # Cargo 1.100 nests compiler inputs in per-unit build directories and
      +            # names the build-script executable build_script_build.
      +            self.assertTrue(list(target.rglob("libartifact_fixture*.rlib")))
      +            self.assertTrue(list((target / "build").rglob("build[-_]script[-_]build")))
      +            self.assertTrue(list((target / "build").rglob("out/generated.rs")))
       
           def test_link_failure_preserves_cargo_status_and_diagnostic(self):
               with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp:
      diff --git a/ci/tests/test_bump_version.sh b/ci/tests/test_bump_version.sh
      new file mode 100644
      index 000000000..09f60760e
      --- /dev/null
      +++ b/ci/tests/test_bump_version.sh
      @@ -0,0 +1,91 @@
      +#!/usr/bin/env bash
      +# Run from the repository root with bump-my-version and packaging installed.
      +set -euo pipefail
      +
      +work=$(mktemp -d)
      +trap 'rm -rf "$work"' EXIT
      +mkdir -p "$work/repo" "$work/bin"
      +
      +# Release tagging must still include Java's versions when Maven cannot update them.
      +cat > "$work/bin/mvn" <<'MOCK'
      +#!/bin/sh
      +echo "Unable to run Maven versions plugin" >&2
      +exit 1
      +MOCK
      +chmod +x "$work/bin/mvn"
      +export PATH="$work/bin:$PATH"
      +
      +git ls-files -z .bumpversion.toml ci/bump_version.sh ci/semver_sort.py \
      +    nodejs/package.json 'nodejs/npm/*/package.json' nodejs/Cargo.toml \
      +    rust/lancedb/Cargo.toml rust/lancedb/cli/Cargo.toml python/Cargo.toml \
      +    docs/src/java/java.md java/pom.xml java/lancedb-core/pom.xml |
      +    tar --null -T - -cf - | tar -xf - -C "$work/repo"
      +cd "$work/repo"
      +
      +# The breaking-change check needs GitHub access and runs after the release tag is set.
      +printf 'pass\n' > ci/check_breaking_changes.py
      +git init --quiet
      +git config user.name "Release test"
      +git config user.email "release-test@example.com"
      +git add .
      +git commit --quiet --message "Release baseline"
      +git tag v0.0.0
      +
      +current_version=$(python -c 'import tomllib; print(tomllib.load(open(".bumpversion.toml", "rb"))["tool"]["bumpversion"]["current_version"])')
      +git tag "v$current_version"
      +
      +# Verify the current baseline before bumping; stale Java POMs must fail.
      +python - "$current_version" <<'PY'
      +import sys
      +import xml.etree.ElementTree as ET
      +
      +expected = sys.argv[1]
      +ns = {"m": "http://maven.apache.org/POM/4.0.0"}
      +for path, xpath in (
      +    ("java/pom.xml", "m:version"),
      +    ("java/lancedb-core/pom.xml", "m:parent/m:version"),
      +):
      +    actual = ET.parse(path).getroot().findtext(xpath, namespaces=ns)
      +    if actual != expected:
      +        raise SystemExit(f"Java baseline mismatch in {path}: expected {expected}, got {actual}")
      +print(f"Java baseline matches {expected} in both POMs")
      +PY
      +
      +check_java_release() {
      +    local release_type=$1
      +    local expected_version=$2
      +    bash ci/bump_version.sh "$release_type" false > "$work/bump.log" 2>&1 || {
      +        cat "$work/bump.log"
      +        return 1
      +    }
      +    python - "$release_type" "$expected_version" <<'PY'
      +import subprocess
      +import sys
      +import xml.etree.ElementTree as ET
      +
      +release_type, expected_version = sys.argv[1:]
      +case = f"test_java_release_version_matches_tag ({release_type})"
      +tag = subprocess.check_output(["git", "describe", "--tags", "--exact-match", "HEAD"], text=True).strip()
      +assert tag == f"v{expected_version}", f"{case}: expected v{expected_version}, got {tag}"
      +namespace = {"m": "http://maven.apache.org/POM/4.0.0"}
      +for path, version_path in (
      +    ("java/pom.xml", "m:version"),
      +    ("java/lancedb-core/pom.xml", "m:parent/m:version"),
      +):
      +    content = subprocess.check_output(["git", "show", f"{tag}:{path}"])
      +    version = ET.fromstring(content).findtext(version_path, namespaces=namespace)
      +    assert version == expected_version, f"{case}: {path}: expected {expected_version}, got {version}"
      +print(f"{case}: passed")
      +PY
      +}
      +
      +case "$current_version" in
      +    *-beta.*)
      +        preview_version="${current_version%.*}.$((${current_version##*.} + 1))"
      +        ;;
      +    *)
      +        preview_version="${current_version%.*}.$((${current_version##*.} + 1))-beta.0"
      +        ;;
      +esac
      +check_java_release preview "$preview_version"
      +check_java_release stable "${preview_version%-beta.*}"
      diff --git a/ci/tests/test_cli_installer.sh b/ci/tests/test_cli_installer.sh
      new file mode 100644
      index 000000000..5298530a9
      --- /dev/null
      +++ b/ci/tests/test_cli_installer.sh
      @@ -0,0 +1,42 @@
      +#!/bin/sh
      +# Run from repository root. The fake transport serves a deliberately corrupt archive.
      +set -eu
      +work=$(mktemp -d)
      +trap 'rm -rf "$work"' EXIT
      +export HOME="$work/home" LANCEDB_VERSION=v0.42.0-beta.19
      +unset LANCEDB_INSTALL_DIR
      +mkdir -p "$work/bin" "$HOME"
      +export PATH="$work/bin:$PATH"
      +cat > "$work/bin/curl" <<'MOCK'
      +#!/bin/sh
      +while [ "$1" != -o ]; do shift; done
      +case "$3" in
      +    */SHA256SUMS)
      +        for target in x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu aarch64-apple-darwin; do
      +            printf '%064d  lancedb-%s-%s.tar.gz\n' 0 "$LANCEDB_VERSION" "$target"
      +        done > "$2" ;;
      +    *) printf 'corrupt archive' > "$2" ;;
      +esac
      +MOCK
      +chmod +x "$work/bin/curl"
      +reject() {
      +    if sh scripts/install.sh > "$work/log" 2>&1; then
      +        echo "Unexpected install success" >&2
      +        exit 1
      +    fi
      +    grep -F "$1" "$work/log"
      +}
      +
      +printf 'existing admin CLI\n' > "$work/bin/lancedb"
      +chmod +x "$work/bin/lancedb"
      +reject 'on PATH'
      +test ! -e "$HOME/.local/bin/lancedb"
      +export LANCEDB_INSTALL_DIR="$work/separate bin"
      +mkdir -p "$LANCEDB_INSTALL_DIR"
      +ln -s "$work/bin/lancedb" "$LANCEDB_INSTALL_DIR/lancedb"
      +reject 'already exists'
      +test -L "$LANCEDB_INSTALL_DIR/lancedb"
      +rm "$LANCEDB_INSTALL_DIR/lancedb"
      +reject 'Checksum mismatch'
      +test -z "$(ls -A "$LANCEDB_INSTALL_DIR")"
      +test "$(cat "$work/bin/lancedb")" = 'existing admin CLI'
      diff --git a/ci/tests/test_extract_sdk_doc_links.py b/ci/tests/test_extract_sdk_doc_links.py
      index 504d28168..0e4c5fe97 100644
      --- a/ci/tests/test_extract_sdk_doc_links.py
      +++ b/ci/tests/test_extract_sdk_doc_links.py
      @@ -27,7 +27,7 @@ class TestExtractSdkDocLinks(unittest.TestCase):
                   urls,
               )
               self.assertIn(
      -            "https://docs.lancedb.com/enterprise",
      +            "https://docs.lancedb.com/basics/embedded-vs-enterprise",
                   urls,
               )
       
      diff --git a/ci/tests/test_update_homebrew_formula.py b/ci/tests/test_update_homebrew_formula.py
      new file mode 100644
      index 000000000..4996ddadd
      --- /dev/null
      +++ b/ci/tests/test_update_homebrew_formula.py
      @@ -0,0 +1,52 @@
      +import unittest
      +
      +from ci.update_homebrew_formula import update_formula
      +
      +
      +class HomebrewFormulaTest(unittest.TestCase):
      +    targets = [
      +        "aarch64-apple-darwin",
      +        "x86_64-unknown-linux-gnu",
      +        "aarch64-unknown-linux-gnu",
      +    ]
      +    tag = "v0.42.10"
      +
      +    def setUp(self):
      +        self.formula = '  version "0.42.10-beta.26"\n'
      +        self.manifest = ""
      +        for index, target in enumerate(self.targets, start=1):
      +            self.formula += f'    url "#{{archive}}-{target}.tar.gz"\n'
      +            self.formula += f'    sha256 "{"0" * 64}"\n'
      +            entry = f"{str(index) * 64}  lancedb-{self.tag}-{target}.tar.gz\n"
      +            self.manifest = entry + self.manifest
      +        self.formula += '  desc "Command-line client for LanceDB"\n'
      +
      +    def test_updates_each_platform_and_preserves_rest_of_formula(self):
      +        result = update_formula(self.formula, self.tag, self.manifest)
      +        expected = self.formula.replace("0.42.10-beta.26", "0.42.10")
      +        for index in range(1, 4):
      +            expected = expected.replace("0" * 64, str(index) * 64, 1)
      +        self.assertEqual(result, expected)
      +        self.assertEqual(update_formula(result, self.tag, self.manifest), result)
      +
      +    def test_retry_of_older_release_cannot_downgrade_the_tap(self):
      +        formula = self.formula.replace("0.42.10-beta.26", "0.43.0")
      +        self.assertEqual(update_formula(formula, self.tag, self.manifest), formula)
      +
      +    def test_rejects_prereleases_and_incomplete_or_ambiguous_inputs(self):
      +        with self.assertRaisesRegex(ValueError, "stable CLI release tag"):
      +            update_formula(self.formula, "v0.42.10-beta.26", self.manifest)
      +        for manifest in (
      +            self.manifest.split("\n", 1)[1],
      +            self.manifest + self.manifest,
      +            self.manifest.replace("v0.42.10", "v0.42.9"),
      +            self.manifest.replace("1" * 64, "invalid"),
      +        ):
      +            with self.subTest(manifest=manifest), self.assertRaises(ValueError):
      +                update_formula(self.formula, self.tag, manifest)
      +        for formula in (
      +            self.formula.replace("aarch64-apple-darwin", "unexpected-target"),
      +            self.formula + self.formula,
      +        ):
      +            with self.subTest(formula=formula), self.assertRaises(ValueError):
      +                update_formula(formula, self.tag, self.manifest)
      diff --git a/ci/update_homebrew_formula.py b/ci/update_homebrew_formula.py
      new file mode 100644
      index 000000000..554adb22d
      --- /dev/null
      +++ b/ci/update_homebrew_formula.py
      @@ -0,0 +1,65 @@
      +"""Update the tap formula from a stable CLI release's SHA256SUMS."""
      +
      +import argparse
      +from pathlib import Path
      +import re
      +
      +from ci.package_cli import TARGETS, archive_stem
      +
      +
      +def update_formula(formula: str, tag: str, manifest: str) -> str:
      +    stable_version = r"[0-9]+\.[0-9]+\.[0-9]+"
      +    if not re.fullmatch(f"v{stable_version}", tag):
      +        raise ValueError(f"Expected a stable CLI release tag, got {tag!r}")
      +    version = tag[1:]
      +
      +    version_line = rf'^  version "({stable_version})(?:-beta\.[0-9]+)?"$'
      +    current = re.findall(version_line, formula, re.MULTILINE)
      +    if len(current) != 1:
      +        raise ValueError("Expected one CLI version declaration in the tap formula")
      +    if tuple(map(int, current[0].split("."))) > tuple(map(int, version.split("."))):
      +        # A maintainer may be retrying an older release after a newer tap PR merged.
      +        return formula
      +
      +    archives = {}
      +    for line in manifest.splitlines():
      +        entry = re.fullmatch(r"([0-9a-f]{64})  (\S+)", line)
      +        if not entry or entry[2] in archives:
      +            raise ValueError(f"Invalid or duplicate entry in SHA256SUMS: {line!r}")
      +        archives[entry[2]] = entry[1]
      +
      +    filenames = {t: f"{archive_stem(version, t)}.tar.gz" for t in TARGETS}
      +    if archives.keys() != set(filenames.values()):
      +        raise ValueError(f"Expected SHA256SUMS for exactly the CLI archives for {tag}")
      +
      +    updated = re.sub(
      +        version_line, f'  version "{version}"', formula, flags=re.MULTILINE
      +    )
      +    for target, filename in filenames.items():
      +        # Match the URL and its following checksum together; platform order can change.
      +        url = re.escape(f'url "#{{archive}}-{target}.tar.gz"')
      +        pattern = rf'^([ \t]+{url}\n[ \t]+sha256 ")[0-9a-f]{{64}}"$'
      +        updated, count = re.subn(
      +            pattern, rf'\g<1>{archives[filename]}"', updated, flags=re.MULTILINE
      +        )
      +        if count != 1:
      +            raise ValueError(
      +                f"Expected one URL and checksum for {target} in the formula"
      +            )
      +    return updated
      +
      +
      +def main():
      +    parser = argparse.ArgumentParser(description=__doc__)
      +    parser.add_argument("tag")
      +    parser.add_argument("checksums", type=Path)
      +    parser.add_argument("formula", type=Path)
      +    args = parser.parse_args()
      +    original = args.formula.read_text()
      +    updated = update_formula(original, args.tag, args.checksums.read_text())
      +    if updated != original:
      +        args.formula.write_text(updated)
      +
      +
      +if __name__ == "__main__":
      +    main()
      diff --git a/deny.toml b/deny.toml
      index 602cc2820..b10550a54 100644
      --- a/deny.toml
      +++ b/deny.toml
      @@ -131,6 +131,32 @@ ignore = [
           { id = "RUSTSEC-2026-0391", reason = "zstd 0.13 via arrow-ipc 58; affected with_context API is unused" },
           { id = "RUSTSEC-2026-0398", reason = "zstd-safe 7 via arrow-ipc 58; affected seekable API is not enabled" },
           { id = "RUSTSEC-2026-0403", reason = "zstd-safe 7 via arrow-ipc 58; affected streaming decoder API is unused" },
      +
      +    # pin-utils: unmaintained; reviewed 2026-11-05, removed 2026-11-17 after
      +    # the lockfile dropped the aws-smithy pins that carried it.
      +    # https://rustsec.org/advisories/RUSTSEC-2026-0441
      +
      +    # chrono: unmaintained; reviewed 2026-11-17. Informational notice, not a
      +    # vulnerability. Transitive via arrow 59 / datafusion 55 and the lance
      +    # stack throughout the workspace. RustSec lists no patched version and
      +    # recommends jiff/time; clearing it requires the arrow/datafusion/lance
      +    # ecosystem to migrate.
      +    # https://rustsec.org/advisories/RUSTSEC-2026-0543
      +    { id = "RUSTSEC-2026-0543", reason = "chrono unmaintained via arrow/datafusion/lance; no fixed upstream release, awaiting ecosystem migration" },
      +
      +    # chrono-tz: unmaintained; reviewed 2026-11-17. Informational notice, not
      +    # a vulnerability. Transitive via arrow-array → arrow → datafusion/lance.
      +    # No patched version exists; clearing it needs the same ecosystem
      +    # migration off chrono as RUSTSEC-2026-0543.
      +    # https://rustsec.org/advisories/RUSTSEC-2026-0555
      +    { id = "RUSTSEC-2026-0555", reason = "chrono-tz unmaintained via arrow/datafusion/lance; no fixed upstream release" },
      +
      +    # humantime: unmaintained; reviewed 2026-11-17. Informational notice, not
      +    # a vulnerability. Transitive via lance, object_store (through datafusion)
      +    # and xet-runtime. No patched version exists; the advisory follows chrono's
      +    # maintenance status.
      +    # https://rustsec.org/advisories/RUSTSEC-2026-0542
      +    { id = "RUSTSEC-2026-0542", reason = "humantime unmaintained via lance/object_store/xet-runtime; no fixed upstream release" },
       ]
       
       
      diff --git a/dockerfiles/Dockerfile b/dockerfiles/Dockerfile
      index 1c223b9b8..d8cafa690 100644
      --- a/dockerfiles/Dockerfile
      +++ b/dockerfiles/Dockerfile
      @@ -1,27 +1,10 @@
      -# Simple base dockerfile that supports basic dependencies required to run lance with FTS and Hybrid Search
      +# Simple base dockerfile for running LanceDB, including FTS and Hybrid Search
       # Usage: docker build -t lancedb:latest -f Dockerfile .
       FROM python:3.12-slim-bookworm
       
      -# Install build dependencies in a single layer
      -RUN apt-get update && \
      -  apt-get install -y --no-install-recommends \
      -    curl \
      -    build-essential \
      -    protobuf-compiler \
      -    git \
      -    ca-certificates && \
      -  apt-get clean && \
      -  rm -rf /var/lib/apt/lists/*
      -
      -# Install Rust (pinned installer, non-interactive)
      -RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal
      -
      -# Set the environment variable for Rust
      -ENV PATH="/root/.cargo/bin:${PATH}"
      -
      -# Verify installations
      -RUN python --version && \
      -  rustc --version && \
      -  protoc --version
      -
      +# lancedb ships prebuilt manylinux wheels, so no Rust or C toolchain is needed.
       RUN pip install --no-cache-dir lancedb
      +
      +RUN useradd --create-home --uid 1000 lancedb
      +USER lancedb
      +WORKDIR /home/lancedb
      diff --git a/docs/STYLE.md b/docs/STYLE.md
      new file mode 100644
      index 000000000..6e6e1c482
      --- /dev/null
      +++ b/docs/STYLE.md
      @@ -0,0 +1,148 @@
      +# LanceDB documentation style
      +
      +Write for developers who want to understand LanceDB and get something done.
      +Be direct, approachable and technically precise. Give readers enough context
      +to make a decision, then show them how to act on it.
      +
      +This guide covers prose on docs.lancedb.com: the pages in this repository's
      +`docs/web`, including the public Enterprise pages, and the Geneva, dataset and
      +REST pages kept in other sources. The
      +[contributing guide](../CONTRIBUTING.md#documentation) covers previewing,
      +code examples and availability labels.
      +
      +## Start with the reader's goal
      +
      +Open with what the feature does and when to use it. Keep the introduction
      +short. Put prerequisites before the instructions that need them, and explain
      +limitations beside the choice or operation they affect.
      +
      +Show the common path before advanced options. A guide should get readers to a
      +useful result before asking them to compare every configuration. This is a
      +default, not a required outline for every page.
      +
      +## Give each page a purpose
      +
      +A concept page explains a few central ideas and how they relate. A guide helps
      +readers complete a task. A reference describes exact syntax, options and
      +behavior. Link to related material with descriptive link text instead of
      +making every page cover all three roles.
      +
      +Keep each section focused on the page's purpose. Don't add a conclusion or a
      +next-steps section unless it helps the reader decide what to do next.
      +
      +## Teach through examples
      +
      +Use small datasets, meaningful names and examples that build on each other.
      +Include the imports, setup and prerequisites readers need, or clearly link to
      +shared setup. State when successive blocks belong to one program. Show the
      +expected result when it helps readers understand the operation.
      +
      +Where equivalent SDK support exists, show Python, TypeScript and Rust
      +consistently. Use the same task and sample data across languages, with
      +idiomatic code in each. If support differs, explain the difference beside the
      +example; don't invent an equivalent API. Prefer fresh example data and make
      +any destructive behavior explicit.
      +
      +Explain what an example demonstrates or why an option matters. Avoid narrating
      +every line when the code already makes its meaning clear.
      +
      +## Explain choices and consequences
      +
      +Tell readers when to choose an option and what changes when they do. State the
      +relevant tradeoff, such as latency versus recall, rather than listing settings
      +without guidance. Use a table when it makes alternatives easier to compare.
      +
      +Name the product or component whose behavior you describe. Use LanceDB
      +Enterprise when you mean the offering; use deployment when you mean a
      +particular installation or its configuration. Describe concrete capabilities
      +and benefits without unsupported performance claims or superlatives.
      +
      +## Say it directly
      +
      +Address the reader as "you" and prefer active verbs and familiar words.
      +Introduce unfamiliar terms when readers first need them. Prefer "use" to
      +"utilize" and "to" to "in order to". Keep technical terms precise: "GPU
      +utilization", for example, has a specific meaning and does not need replacing.
      +
      +Describe the subject, not the page or the writing. Instead of "This page is the
      +concept; the SQL reference is the specification", explain the concept and
      +link to the reference. Instead of opening with "That matters", state the
      +consequence. Avoid "simply" and "obviously" when they assume a task is easy for
      +the reader. These are writing guidelines, not blanket bans on individual words.
      +
      +## Headings
      +
      +A heading names the task or topic of its section. "Then what" doesn't; "Choose
      +an output" does. Prefer specific headings such as "Data durability" to broad
      +questions such as "What survives?". Use sentence case, preserving product names
      +and identifiers.
      +
      +## Names
      +
      +Write product names exactly: LanceDB, LanceDB Embedded and LanceDB Enterprise.
      +Write other names as their owners do, such as Hugging Face, LangChain,
      +TypeScript and Voyage AI.
      +
      +- **LanceDB Embedded** is the in-process execution model: the SDK runs
      +  database operations inside the application's process and reads Lance tables
      +  directly, from local disk or object storage. Don't write "LanceDB OSS",
      +  "LanceDB Local" or "local mode".
      +- **LanceDB Enterprise** is the commercial product. Use this name in product
      +  descriptions, SDK documentation and architecture explanations: "a LanceDB
      +  SDK connects to LanceDB Enterprise". Describe execution directly: query
      +  execution, indexing, caching and maintenance run on the service, outside
      +  the application. Write "Embedded and Enterprise" when comparing offerings.
      +  Don't introduce "LanceDB Distributed" as another name for the product or
      +  its execution model. Lowercase "distributed" still describes how a feature
      +  works, such as distributed search, caching or training. Use "Enterprise
      +  table" or "Enterprise connection" in prose; keep API identifiers such as
      +  `RemoteTable` unchanged.
      +- **LanceDB Cloud** is only the legacy hosted service. Keep it where text is
      +  specific to that service, such as `db://` URIs with an `api_key` and
      +  `region`; otherwise write LanceDB Enterprise.
      +- **Open source** is a property, not a product: "the open-source LanceDB SDKs",
      +  "Lance is open source". Where free versus paid is the point, write "LanceDB
      +  Embedded (open source)" and "LanceDB Enterprise". Don't use "OSS" as a
      +  product name, as in "OSS vs Enterprise".
      +- Internal component names stay out of public text. Write "query node",
      +  "executor" and LanceDB Enterprise instead; the `InternalNames` Vale rule
      +  lists the names it catches. Geneva is a product name and stays as is.
      +
      +Package, module, class and repository names are code, so put them in code
      +font: `lancedb`, `pyarrow`, `HuggingFaceEmbeddings`.
      +
      +## Punctuation
      +
      +Don't use em dashes in prose, or a double hyphen or spaced en dash in place of
      +one. Use a comma, a colon, parentheses or two sentences. An en dash in a range,
      +such as 1–3, is fine, and so is a table cell that holds only an em dash to mean
      +"none".
      +
      +## Automated checks and review
      +
      +[Vale](https://vale.sh) checks a small subset of these conventions: product
      +names, dashes, repeated words, a few vague phrases and headings, and a few
      +plain-language substitutions. Findings are advisory and appear on changed
      +lines; they never fail the check. Installation or configuration failures can
      +still fail it. See the [bundled rules](../.github/vale/README.md) for usage and tests.
      +
      +Vale cannot verify technical claims, example correctness, SDK coverage or a
      +page's organization. Review those using implementation evidence, tests and
      +feature-owner input. Confirm availability and release status with the owner;
      +do not infer a release promise from an implementation or a passing test.
      +Reader-visible component titles and captions in MDX attributes are also left
      +to review because Vale does not inspect those attributes.
      +
      +Use these guidelines as defaults. Reviewers can make exceptions when they
      +improve clarity or accuracy.
      +
      +## Exceptions
      +
      +When a sentence must break an automated rule, such as a quoted error message,
      +switch off that rule around it and say why in the pull request:
      +
      +```mdx
      +{/* vale LanceDB.Dashes = NO */}
      +The server returns "Table not found — check the name".
      +{/* vale LanceDB.Dashes = YES */}
      +```
      diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml
      index ad6fc4b65..b2bd4738a 100644
      --- a/docs/mkdocs.yml
      +++ b/docs/mkdocs.yml
      @@ -72,11 +72,11 @@ plugins:
                   separate_signature: true
                   filters:
                     - "!^_"
      -          import:
      +          inventories:
                   # for cross references
                   - https://arrow.apache.org/docs/objects.inv
                   - https://pandas.pydata.org/docs/objects.inv
      -            - https://docs.pydantic.dev/latest/objects.inv
      +            - https://pydantic.dev/docs/validation/latest/objects.inv
         - render_swagger:
             allow_arbitrary_locations: true
       #   - redirects:
      diff --git a/docs/requirements.txt b/docs/requirements.txt
      index 89de1cb71..3405e8dce 100644
      --- a/docs/requirements.txt
      +++ b/docs/requirements.txt
      @@ -1,9 +1,9 @@
       mkdocs==1.6.1
       mkdocs-jupyter==0.24.1
      -mkdocs-material==9.6.23
      -mkdocs-autorefs>=0.5,<=1.0
      -mkdocstrings[python]>=0.24,<1.0
      -griffe>=0.40,<1.0
      +mkdocs-material==9.8.2
      +mkdocs-autorefs>=1.4
      +mkdocstrings[python]>=1.0.7,<2
      +pymdown-extensions>=11.0.1
       mkdocs-render-swagger-plugin>=0.1.0
       pydantic>=2.7.4,<3
       mkdocs-redirects>=1.2.0
      diff --git a/docs/src/java/java.md b/docs/src/java/java.md
      index a0844a469..d392faec8 100644
      --- a/docs/src/java/java.md
      +++ b/docs/src/java/java.md
      @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`:
       
           com.lancedb
           lancedb-core
      -    0.42.0-beta.4
      +    0.42.0-beta.37
       
       ```
       
      diff --git a/docs/src/js/classes/Branches.md b/docs/src/js/classes/Branches.md
      index 6680fbfee..4e154e30f 100644
      --- a/docs/src/js/classes/Branches.md
      +++ b/docs/src/js/classes/Branches.md
      @@ -64,6 +64,35 @@ with `status: "failed"` instead of throwing.
       
       ### create()
       
      +#### create(name, options)
      +
      +```ts
      +create(name, options): Promise
      +```
      +
      +Create a branch from a tag and return a handle scoped to it.
      +
      +##### Parameters
      +
      +* **name**: `string`
      +    Name of the new branch.
      +
      +* **options**: [`CreateBranchOptions`](../interfaces/CreateBranchOptions.md)
      +    Named source. `fromTag` keeps the tag's branch and version.
      +
      +##### Returns
      +
      +`Promise`<[`Table`](Table.md)>
      +
      +##### Example
      +
      +```typescript
      +const branches = await table.branches();
      +const branch = await branches.create("exp", { fromTag: "baseline" });
      +```
      +
      +#### create(name, fromRef, fromVersion)
      +
       ```ts
       create(
          name,
      @@ -73,7 +102,7 @@ create(
       
       Create a branch and return a handle scoped to it.
       
      -#### Parameters
      +##### Parameters
       
       * **name**: `string`
           Name of the new branch.
      @@ -84,7 +113,7 @@ Create a branch and return a handle scoped to it.
       * **fromVersion?**: `number`
           A specific version on `fromRef`. Defaults to latest.
       
      -#### Returns
      +##### Returns
       
       `Promise`<[`Table`](Table.md)>
       
      diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md
      index 4876e3a52..06be760ef 100644
      --- a/docs/src/js/classes/Connection.md
      +++ b/docs/src/js/classes/Connection.md
      @@ -196,10 +196,20 @@ it can be queried, indexed and searched, and it appears in `tableNames`.
       
       * **options?**
       
      +* **options.gpuClass?**: `string`
      +
      +* **options.gpuCount?**: `number`
      +
       * **options.limit?**: `number`
       
       * **options.select?**: [`MaterializedViewSelect`](../type-aliases/MaterializedViewSelect.md)
       
      +* **options.totalCpuMillis?**: `number`
      +
      +* **options.totalGpuCount?**: `number`
      +
      +* **options.totalMemoryBytes?**: `number`
      +
       * **options.where?**: `string`
       
       * **options.withNoData?**: `boolean`
      @@ -456,7 +466,7 @@ Rejects a table that exists but is not a materialized view.
       ### dropMaterializedViewAsync()
       
       ```ts
      -abstract dropMaterializedViewAsync(name, namespacePath?): Promise
      +abstract dropMaterializedViewAsync(name, namespacePath?): Promise>
       ```
       
       Start dropping the materialized view named `name` and return its job.
      @@ -473,7 +483,7 @@ Rejects a table that exists but is not a materialized view.
       
       #### Returns
       
      -`Promise`<[`Job`](Job.md)>
      +`Promise`<[`Job`](Job.md)<`void`>>
       
       ***
       
      @@ -532,7 +542,7 @@ Drop an existing table.
       ### dropTableAsync()
       
       ```ts
      -abstract dropTableAsync(name, namespacePath?): Promise
      +abstract dropTableAsync(name, namespacePath?): Promise>
       ```
       
       Start dropping a table and return its cleanup job.
      @@ -548,7 +558,7 @@ on the returned job to know when cleanup has finished.
       
       #### Returns
       
      -`Promise`<[`Job`](Job.md)>
      +`Promise`<[`Job`](Job.md)<`void`>>
       
       ***
       
      @@ -579,7 +589,7 @@ catalog removal; physical cleanup continues in the background.
       ### dropViewAsync()
       
       ```ts
      -abstract dropViewAsync(name, namespacePath?): Promise
      +abstract dropViewAsync(name, namespacePath?): Promise>
       ```
       
       Drop a view and return its SQL query job.
      @@ -594,7 +604,7 @@ catalog removal; physical cleanup continues in the background.
       
       #### Returns
       
      -`Promise`<[`Job`](Job.md)>
      +`Promise`<[`Job`](Job.md)<`void`>>
       
       ***
       
      @@ -729,7 +739,7 @@ state and error behavior; options control page size and the starting token.
       ### openJob()
       
       ```ts
      -abstract openJob(jobId): Promise
      +abstract openJob(jobId): Promise>
       ```
       
       Open a server-side job by id, returning a handle with its record already
      @@ -740,13 +750,17 @@ The returned [Job](Job.md) answers for its own state, specification,
       result, failure and event history, so there is no separate
       connection-level call for any of them.
       
      +#### Type Parameters
      +
      +• **T** = `void`
      +
       #### Parameters
       
       * **jobId**: `string`
       
       #### Returns
       
      -`Promise`<[`Job`](Job.md)>
      +`Promise`<[`Job`](Job.md)<`T`>>
       
       ***
       
      diff --git a/docs/src/js/classes/Index.md b/docs/src/js/classes/Index.md
      index e613882e4..d76acaa3c 100644
      --- a/docs/src/js/classes/Index.md
      +++ b/docs/src/js/classes/Index.md
      @@ -258,3 +258,94 @@ using an underlying bitmap index.
       #### Returns
       
       [`Index`](Index.md)
      +
      +***
      +
      +### plugin()
      +
      +```ts
      +static plugin(indexType, params?): Index
      +```
      +
      +Create a scalar index of a type recognized by a registered database plugin.
      +
      +Use this for index types without a dedicated factory on `Index`.
      +Prefer a dedicated factory when one is available.
      +
      +An unknown plugin name or invalid parameters cause `createIndex` to fail.
      +
      +#### Parameters
      +
      +* **indexType**: `string`
      +    The index type, case-insensitive.
      +    Surrounding whitespace is ignored. Must not be empty.
      +
      +* **params?**: `string` \| `Record`<`string`, `unknown`>
      +    The index parameters, as an object or as a string
      +    holding a JSON object. They are passed as given. Each plugin defines
      +    its parameters and defaults; refer to the plugin's documentation
      +    for guidance.
      +
      +#### Returns
      +
      +[`Index`](Index.md)
      +
      +#### Throws
      +
      +If `indexType` is empty, or `params` is not a JSON object.
      +
      +#### Example
      +
      +```ts
      +await table.createIndex("id", {
      +  config: Index.plugin("bloomfilter", { number_of_items: 4096 }),
      +});
      +```
      +
      +***
      +
      +### rtree()
      +
      +```ts
      +static rtree(options?): Index
      +```
      +
      +Create an RTree index.
      +
      +An RTree index is a scalar index on a GeoArrow geometry column, that is, a
      +column whose Arrow field metadata sets `ARROW:extension:name` to a GeoArrow
      +type such as `geoarrow.point`, `geoarrow.polygon` or `geoarrow.wkb`. It
      +stores the bounding box of each geometry and accelerates spatial filters.
      +
      +The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`,
      +`ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy`
      +between the indexed column and a constant geometry, in either argument
      +order, for example
      +`ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))`, as well as
      +`geom IS NULL`. These filters can be combined with other conditions using
      +`AND`.
      +
      +See the R-tree section of https://docs.lancedb.com/indexing/scalar-index
      +for storing geometry, the other spatial functions, and spatial filters on
      +vector search.
      +
      +Remote tables send the `RTREE` index type to the server, which must
      +support it.
      +
      +#### Parameters
      +
      +* **options?**: `Partial`<[`RTreeOptions`](../interfaces/RTreeOptions.md)>
      +
      +#### Returns
      +
      +[`Index`](Index.md)
      +
      +#### Example
      +
      +```ts
      +await table.createIndex("geom", { config: Index.rtree() });
      +await table
      +  .query()
      +  .where("ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))")
      +  .toArray();
      +```
      diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md
      index 8fd59c964..86c5abc1f 100644
      --- a/docs/src/js/classes/Job.md
      +++ b/docs/src/js/classes/Job.md
      @@ -4,7 +4,7 @@
       
       [@lancedb/lancedb](../globals.md) / Job
       
      -# Class: Job
      +# Class: Job<T>
       
       A handle to an operation that may still be running.
       
      @@ -20,8 +20,26 @@ extra round trip on every call:
       - Registry details are null until one of those runs. Query handles report
         jobType "query" immediately.
       
      +## Type Parameters
      +
      +• **T** = `void`
      +
       ## Accessors
       
      +### attempt
      +
      +```ts
      +get attempt(): null | number
      +```
      +
      +One-based attempt ordinal. Worker replacement does not increment it.
      +
      +#### Returns
      +
      +`null` \| `number`
      +
      +***
      +
       ### creationMs
       
       ```ts
      @@ -36,6 +54,20 @@ When the job was created, in milliseconds since the epoch.
       
       ***
       
      +### executionEpoch
      +
      +```ts
      +get executionEpoch(): null | number
      +```
      +
      +Most recent execution's fencing token, when reported.
      +
      +#### Returns
      +
      +`null` \| `number`
      +
      +***
      +
       ### failure
       
       ```ts
      @@ -69,6 +101,23 @@ durable resume tokens.
       
       ***
       
      +### jobId
      +
      +```ts
      +get jobId(): null | string
      +```
      +
      +Identity of the selected attempt last observed by this handle.
      +For operation handles, `refresh()` or `status()` can select a different
      +attempt while `id` stays unchanged. Save this value after refreshing and
      +use it throughout paged diagnostics. Local IDs cannot be reopened on a server.
      +
      +#### Returns
      +
      +`null` \| `string`
      +
      +***
      +
       ### jobType
       
       ```ts
      @@ -84,6 +133,34 @@ server-reported job type. Null for in-process handles.
       
       ***
       
      +### lifecycleState
      +
      +```ts
      +get lifecycleState(): null | JobState
      +```
      +
      +Detailed state last observed; unknown values never establish success.
      +
      +#### Returns
      +
      +`null` \| [`JobState`](../type-aliases/JobState.md)
      +
      +***
      +
      +### operationId
      +
      +```ts
      +get operationId(): null | string
      +```
      +
      +Root of the explicit retry lineage, when reported.
      +
      +#### Returns
      +
      +`null` \| `string`
      +
      +***
      +
       ### result
       
       ```ts
      @@ -100,6 +177,34 @@ instead.
       
       ***
       
      +### retryOf
      +
      +```ts
      +get retryOf(): null | string
      +```
      +
      +Immediate predecessor attempt, when reported.
      +
      +#### Returns
      +
      +`null` \| `string`
      +
      +***
      +
      +### sourceTableVersion
      +
      +```ts
      +get sourceTableVersion(): null | number
      +```
      +
      +Source snapshot pinned for this attempt, when reported.
      +
      +#### Returns
      +
      +`null` \| `number`
      +
      +***
      +
       ### spec
       
       ```ts
      @@ -142,6 +247,43 @@ Request cancellation. Cancelling a finished operation is a no-op.
       
       ***
       
      +### captureProfile()
      +
      +```ts
      +captureProfile(workerId, options): Promise
      +```
      +
      +Request a profile of a running Enterprise Function worker session.
      +Returns the accepted identity without waiting for recording to finish.
      +Requires System Operate permission and server profiling support. The server
      +pins the worker, Python session and execution epoch. One capture per job
      +can be active. Captures add workload-dependent overhead.
      +
      +GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU sampling requires
      +readable per-thread procfs and is unavailable in dedicated sandboxes.
      +
      +#### Parameters
      +
      +* **workerId**: `string`
      +
      +* **options**: [`FunctionProfileOptions`](../interfaces/FunctionProfileOptions.md) = `{}`
      +
      +#### Returns
      +
      +`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)>
      +
      +#### Example
      +
      +```ts
      +const profile = await job.captureProfile("worker-id", {
      +  kind: "gpu", durationSeconds: 2,
      +});
      +await job.waitForProfile(profile.profileId, { timeoutMs: 60_000 });
      +await job.exportProfile(profile.profileId, "gpu.trace.json");
      +```
      +
      +***
      +
       ### events()
       
       ```ts
      @@ -171,6 +313,89 @@ per fragment. `filter` is a SQL-like expression over the `state`,
       
       ***
       
      +### exportProfile()
      +
      +```ts
      +exportProfile(profileId, path): Promise
      +```
      +
      +Write a completed capture's JSON after successful retrieval. Open CPU
      +exports in speedscope and GPU exports in Perfetto. GPU activity durations
      +can overlap and are not utilization; Python operator attribution and GPU
      +allocation stacks are excluded. Filesystem errors propagate to the caller.
      +
      +#### Parameters
      +
      +* **profileId**: `string`
      +
      +* **path**: `string`
      +
      +#### Returns
      +
      +`Promise`<`void`>
      +
      +***
      +
      +### history()
      +
      +```ts
      +history(options?): AsyncGenerator, any, unknown>
      +```
      +
      +Walk retained history one page at a time using the server's continuation.
      +
      +#### Parameters
      +
      +* **options?**: [`JobEventsOptions`](../interfaces/JobEventsOptions.md)
      +
      +#### Returns
      +
      +`AsyncGenerator`<`Table`<`any`>, `any`, `unknown`>
      +
      +***
      +
      +### profileArtifact()
      +
      +```ts
      +profileArtifact(profileId): Promise>
      +```
      +
      +Retrieve a completed capture's actual JSON: speedscope for CPU,
      +tracemalloc for Python allocations, or Chrome Trace Event JSON for GPU.
      +Truncation flags are preserved. Retention is at most one hour and eight
      +captures per job, until earlier scratch reclamation or archival.
      +Permission, expired-artifact and unsupported-server errors propagate.
      +
      +#### Parameters
      +
      +* **profileId**: `string`
      +
      +#### Returns
      +
      +`Promise`<`Record`<`string`, `unknown`>>
      +
      +***
      +
      +### profileStatus()
      +
      +```ts
      +profileStatus(profileId): Promise
      +```
      +
      +Fetch capture identity and status, including retained lookup after refresh.
      +Failed captures return status "failed" with the server's error reason.
      +This never changes the parent job's cached state.
      +
      +#### Parameters
      +
      +* **profileId**: `string`
      +
      +#### Returns
      +
      +`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)>
      +
      +***
      +
       ### progress()
       
       ```ts
      @@ -204,14 +429,28 @@ its full record, then cache it for the getters above.
       
       ***
       
      +### retry()
      +
      +```ts
      +retry(): Promise>
      +```
      +
      +Select this exact attempt's pinned successor. Requires backend support.
      +
      +#### Returns
      +
      +`Promise`<[`Job`](Job.md)<`T`>>
      +
      +***
      +
       ### status()
       
       ```ts
       status(): Promise
       ```
       
      -The operation's current lifecycle state: "running", "finished", "failed",
      -or "cancelled".
      +The current status, usually "running", "finished", "failed", or "cancelled".
      +A Function refresh waiting for execution workers reports "waiting_for_capacity".
       
       A point snapshot; unlike [Job.wait](Job.md#wait) it does not block or reject on a
       terminal failure state. Also refreshes the getters above.
      @@ -222,6 +461,20 @@ terminal failure state. Also refreshes the getters above.
       
       ***
       
      +### statusTyped()
      +
      +```ts
      +statusTyped(): Promise
      +```
      +
      +Refresh and return the detailed lifecycle state.
      +
      +#### Returns
      +
      +`Promise`<[`JobState`](../type-aliases/JobState.md)>
      +
      +***
      +
       ### toString()
       
       ```ts
      @@ -241,7 +494,7 @@ printing it.
       ### wait()
       
       ```ts
      -wait(progressCallback?): Promise
      +wait(optionsOrProgress?): Promise
       ```
       
       Wait until the operation reaches a terminal state.
      @@ -253,10 +506,44 @@ synchronous observer: its return value is ignored and not awaited. If it
       throws, the error is logged with `console.warn` and waiting continues; a
       callback exception does not reject `wait`.
       
      +Pass an options object to set a client-side timeout. Expiry rejects with an
      +error and stops this wait, including pending status requests and backoff.
      +The operation continues; use the same handle to wait again. Registry jobs
      +can also be reopened with `Connection.openJob`; query IDs cannot.
      +
       #### Parameters
       
      -* **progressCallback?**: [`JobProgressCallback`](../type-aliases/JobProgressCallback.md)
      +* **optionsOrProgress?**: [`JobWaitOptions`](../interfaces/JobWaitOptions.md) \| [`JobProgressCallback`](../type-aliases/JobProgressCallback.md)
       
       #### Returns
       
      -`Promise`<`void`>
      +`Promise`<`T`>
      +
      +#### Example
      +
      +```ts
      +const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log });
      +```
      +
      +***
      +
      +### waitForProfile()
      +
      +```ts
      +waitForProfile(profileId, options): Promise
      +```
      +
      +Wait for a capture with a configurable timeout and polling cadence.
      +Defaults to 60 seconds with two seconds between requests. A timeout stops
      +only this wait; the capture and Function refresh continue. A failed capture
      +rejects with its server-reported reason. Keep its ID to wait again.
      +
      +#### Parameters
      +
      +* **profileId**: `string`
      +
      +* **options**: [`FunctionProfileWaitOptions`](../interfaces/FunctionProfileWaitOptions.md) = `{}`
      +
      +#### Returns
      +
      +`Promise`<[`FunctionProfile`](../interfaces/FunctionProfile.md)>
      diff --git a/docs/src/js/classes/MaterializedView.md b/docs/src/js/classes/MaterializedView.md
      index 3ba4d56b3..7543a2f9d 100644
      --- a/docs/src/js/classes/MaterializedView.md
      +++ b/docs/src/js/classes/MaterializedView.md
      @@ -78,8 +78,18 @@ source-version pinning. Their results leave `mode`, `rowsWritten`, and
       
       * **options.full?**: `boolean`
       
      +* **options.gpuClass?**: `string`
      +
      +* **options.gpuCount?**: `number`
      +
       * **options.sourceVersion?**: `number`
       
      +* **options.totalCpuMillis?**: `number`
      +
      +* **options.totalGpuCount?**: `number`
      +
      +* **options.totalMemoryBytes?**: `number`
      +
       #### Returns
       
       `Promise`<[`RefreshMaterializedViewResult`](../interfaces/RefreshMaterializedViewResult.md)>
      diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md
      index e5ffe71c1..5d8cd1c86 100644
      --- a/docs/src/js/classes/Table.md
      +++ b/docs/src/js/classes/Table.md
      @@ -272,6 +272,38 @@ const after = await table.getRTEStats();
       
       ***
       
      +### cleanupAsync()
      +
      +```ts
      +cleanupAsync(_options?): Promise>
      +```
      +
      +Submit durable remote cleanup through SQL VACUUM and return after acceptance.
      +Requires table Ownership and parent Usage. Retention inherits from the table
      +then deployment when omitted. Local/historical handles are unsupported.
      +Before submission, disable/drain automatic cleanup and prevent other cleanup,
      +tag/branch publication and restore until completion, including direct clients.
      +Coordination is not enforced by the server. Cancellation cannot undo deletion
      +or prove storage I/O stopped. Preview is available without deletion.
      +Wait timeout leaves work running; save the ID and reopen with db.openJob().
      +
      +#### Parameters
      +
      +* **\_options?**: [`CleanupOptions`](../interfaces/CleanupOptions.md)
      +
      +#### Returns
      +
      +`Promise`<[`Job`](Job.md)<[`CleanupResult`](../interfaces/CleanupResult.md)>>
      +
      +#### Example
      +
      +```ts
      +const job = await table.cleanupAsync({ minAgeSeconds: 604800 });
      +const result = await job.wait({ timeoutMs: 600000 });
      +```
      +
      +***
      +
       ### close()
       
       ```ts
      @@ -309,6 +341,40 @@ It is a no-op when no writers are cached.
       
       ***
       
      +### compactAsync()
      +
      +```ts
      +compactAsync(_options?): Promise>
      +```
      +
      +Submit remote compaction and return its durable job after acceptance.
      +
      +Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires
      +a compatible remote server and table Ownership plus parent Usage. Local and
      +historical-version handles are unsupported. Existing optimize() behavior is unchanged.
      +Waiting tracks the rewrite itself and returns actual row/file statistics.
      +Missing result payloads are errors; older workers can omit file counts.
      +Status, progress, events and cancellation reuse the generic HTTP job APIs.
      +Reopen with db.openJob(job.id!). A wait timeout does not cancel work.
      +
      +#### Parameters
      +
      +* **\_options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md)
      +
      +#### Returns
      +
      +`Promise`<[`Job`](Job.md)<[`CompactionResult`](../interfaces/CompactionResult.md)>>
      +
      +#### Example
      +
      +```ts
      +const job = await table.compactAsync({ targetRowsPerFragment: 1000 });
      +const result = await job.wait();
      +console.log(result.rowsSucceeded, result.fragmentsRemoved);
      +```
      +
      +***
      +
       ### compactRTE()
       
       ```ts
      @@ -427,7 +493,7 @@ await table.createIndex("my_float_col");
       ### createIndexAsync()
       
       ```ts
      -abstract createIndexAsync(column, options?): Promise
      +abstract createIndexAsync(column, options?): Promise>
       ```
       
       Create an index, returning a handle to the indexing job.
      @@ -448,7 +514,7 @@ account for the replacement caveat described in [Table.createIndex](Table.md#cre
       
       #### Returns
       
      -`Promise`<[`Job`](Job.md)>
      +`Promise`<[`Job`](Job.md)<`void`>>
       
       ***
       
      @@ -490,6 +556,53 @@ containing the new version number of the table
       
       ***
       
      +### delta()
      +
      +```ts
      +delta(fromVersion, toVersion?): Promise
      +```
      +
      +Compare two persisted versions or same-branch tags on an Embedded table.
      +
      +`fromVersion` is exclusive and `toVersion` is inclusive. Omitting
      +`toVersion` uses the version currently visible through this handle,
      +including a checked-out version. The endpoints are fixed when the delta is
      +created.
      +
      +Row readers require stable row IDs at both endpoints. Create the table with
      +`storageOptions: { new_table_enable_stable_row_ids: "true" }` to enable
      +them. `listTransactions()` works without stable row IDs.
      +
      +Row readers reject ranges containing a Restore, or ranges whose transaction
      +history cannot prove they are restore-free. Recompute the checkpoint with a
      +full rescan and reinitialize it at the range end version.
      +
      +LanceDB Enterprise tables reject this operation.
      +
      +#### Parameters
      +
      +* **fromVersion**: [`DeltaVersion`](../type-aliases/DeltaVersion.md)
      +
      +* **toVersion?**: [`DeltaVersion`](../type-aliases/DeltaVersion.md)
      +
      +#### Returns
      +
      +`Promise`<[`TableDelta`](TableDelta.md)>
      +
      +#### Example
      +
      +```ts
      +const delta = await table.delta("baseline");
      +const reader = delta.insertedRows();
      +console.log((await reader.schema()).fields.map((field) => field.name));
      +for await (const batch of reader) {
      +  console.log(batch.getChild("id")?.toJSON());
      +}
      +console.log(await delta.listTransactions());
      +```
      +
      +***
      +
       ### disableRTE()
       
       ```ts
      @@ -623,6 +736,58 @@ await table.enableRTE({
       
       ***
       
      +### explainCleanup()
      +
      +```ts
      +explainCleanup(_options?): Promise
      +```
      +
      +Preview version deletion without creating a job. Execution re-evaluates current state.
      +
      +#### Parameters
      +
      +* **\_options?**: [`CleanupOptions`](../interfaces/CleanupOptions.md)
      +
      +#### Returns
      +
      +`Promise`<[`CleanupPlan`](../interfaces/CleanupPlan.md)>
      +
      +***
      +
      +### explainPrewarmData()
      +
      +```ts
      +explainPrewarmData(_options?): Promise
      +```
      +
      +Preview prewarm with the same options as [prewarmDataAsync](Table.md#prewarmdataasync), without
      +submitting a warming job. Requires LanceDB Enterprise with structured SQL
      +previews, table Select and database/namespace Usage. Reads metadata and
      +returns the source version, readable plan, and conservative pruning summary.
      +A later submission plans its own snapshot. Historical and Embedded handles
      +are unsupported. Unknown measurements remain null.
      +Custom table implementations can override this method; its default rejects
      +with an unsupported-operation error.
      +
      +#### Parameters
      +
      +* **\_options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md)
      +
      +#### Returns
      +
      +`Promise`<[`PrewarmDataPlan`](../interfaces/PrewarmDataPlan.md)>
      +
      +#### Example
      +
      +```ts
      +const plan = await table.explainPrewarmData({
      +  columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7},
      +});
      +console.log(plan.pruning.selectedFragments);
      +```
      +
      +***
      +
       ### fetchBlobFiles()
       
       ```ts
      @@ -654,6 +819,48 @@ tables; no partial handles are returned.
       
       ***
       
      +### fetchBlobRanges()
      +
      +```ts
      +abstract fetchBlobRanges(
      +   column,
      +   requests,
      +   options?): Promise<(null | Buffer)[]>
      +```
      +
      +Materializes row-specific byte ranges at the table's current checkout.
      +Preserves request order, duplicates, and nulls. Zero length returns an empty
      +buffer for a non-null blob. Invalid ranges or missing rows reject the entire
      +call. See [Table.fetchBlobs](Table.md#fetchblobs) for row-ID validity across versions.
      +
      +Remote tables use the batched endpoint when the server advertises support,
      +splitting at 1024 ranges and 64 MiB, including individual larger ranges.
      +Older servers use descriptor queries and BlobFile range reads. Both protocols
      +use one exact branch and version. Errors from an advertised endpoint propagate
      +without switching protocols. All output bytes occupy memory.
      +
      +#### Parameters
      +
      +* **column**: `string`
      +
      +* **requests**: readonly [`BlobRangeRequest`](../type-aliases/BlobRangeRequest.md)[]
      +
      +* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md)
      +
      +#### Returns
      +
      +`Promise`<(`null` \| `Buffer`)[]>
      +
      +#### Example
      +
      +```ts
      +const bytes = await table.fetchBlobRanges("image", [
      +  { rowId: 10n, offset: 0n, length: 1024n },
      +]);
      +```
      +
      +***
      +
       ### fetchBlobs()
       
       ```ts
      @@ -708,41 +915,122 @@ so this is safe to call repeatedly.
       
       ***
       
      +### functionColumnStatus()
      +
      +```ts
      +abstract functionColumnStatus(column): Promise
      +```
      +
      +Return exact freshness status for one Function-backed output column.
      +
      +#### Parameters
      +
      +* **column**: `string`
      +
      +#### Returns
      +
      +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)>
      +
      +***
      +
      +### functionColumnStatuses()
      +
      +```ts
      +abstract functionColumnStatuses(column?): Promise
      +```
      +
      +Return exact freshness status for Function-backed output columns.
      +
      +All results describe one server table version. Omit `column` for every
      +Function output. Rows already failed remain visible and do not prevent
      +`waitFresh` from completing. A handle pinned to an exact version requests
      +that version; a latest handle retains normal read-freshness behavior.
      +
      +#### Parameters
      +
      +* **column?**: `string`
      +
      +#### Returns
      +
      +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)[]>
      +
      +***
      +
      +### functionErrorRows()
      +
      +```ts
      +functionErrorRows(options?): Promise
      +```
      +
      +Read current failing inputs, one result per error record.
      +Requires a complete LanceDB Enterprise workflow version 1 listing with
      +row identities. Throws if a failed row is no longer addressable in the
      +table's read snapshot. For materialized views, see the source identities
      +on each error record returned by [Table#functionErrors](Table.md#functionerrors).
      +
      +#### Parameters
      +
      +* **options?**: [`FunctionErrorRowsOptions`](../interfaces/FunctionErrorRowsOptions.md)
      +
      +#### Returns
      +
      +`Promise`<[`FunctionFailedRow`](../interfaces/FunctionFailedRow.md)[]>
      +
      +***
      +
       ### functionErrors()
       
       ```ts
       abstract functionErrors(options?): Promise
       ```
       
      -The per-row errors Function refreshes recorded on this table.
      +List the per-row errors recorded by Function refreshes on this table.
       
      -A refresh running under a skip policy records each row it skipped with
      -the input that failed and the error. This lists those records, newest
      -job first, plus a summary for any fragment whose per-row detail was
      -capped. LanceDB Enterprise only; reading errors needs read
      -access to the table, since a message carries the value that failed.
      +On LanceDB Enterprise with workflow version 1 or later, the default
      +lists current failures. Set `history: true` to include retained attempts
      +for repaired rows. Older deployments keep their existing default listing.
      +Reading errors requires table read access because messages can include the
      +input that failed. `errorGroups` describes the returned records.
       
       #### Parameters
       
       * **options?**: [`FunctionErrorsOptions`](../interfaces/FunctionErrorsOptions.md)
      -    Optional filters: `jobId`,
      -    `column`, and `limit` (server default 10000, cap 100000).
       
       #### Returns
       
       `Promise`<[`FunctionErrors`](../interfaces/FunctionErrors.md)>
       
      -The records, the capped fragments,
      -and whether the listing stopped at its limit.
      -
       #### Example
       
       ```ts
      -const { records, truncated } = await table.functionErrors({ column: "embedding" });
      +const errors = await table.functionErrors({ column: "embedding" });
      +console.log(errors.records, errors.errorGroups);
       ```
       
       ***
       
      +### functionProvenance()
      +
      +```ts
      +functionProvenance(_column, _options?): Promise
      +```
      +
      +Read the producing Function version and job for each returned value.
      +Check `truncated` before treating the result as a complete listing.
      +Requires LanceDB Enterprise Function failure workflow version 1 or later.
      +
      +#### Parameters
      +
      +* **\_column**: `string`
      +
      +* **\_options?**: [`FunctionProvenanceOptions`](../interfaces/FunctionProvenanceOptions.md)
      +
      +#### Returns
      +
      +`Promise`<[`FunctionProvenance`](../interfaces/FunctionProvenance.md)>
      +
      +***
      +
       ### getRTESpec()
       
       ```ts
      @@ -788,6 +1076,26 @@ Resolves to `undefined` only when the RTE write path is not enabled.
       
       ***
       
      +### getTableOverrides()
      +
      +```ts
      +getTableOverrides(): Promise>
      +```
      +
      +Read the stored overrides for a remote Enterprise table.
      +
      +Overrides configure background behavior such as automatic compaction,
      +cleanup, and reindex execution. Keys use the server's snake_case names.
      +Returns an empty object when no overrides are set. Local tables are unsupported.
      +Custom table implementations inherit a default rejection unless they override
      +this method.
      +
      +#### Returns
      +
      +`Promise`<`Record`<`string`, `unknown`>>
      +
      +***
      +
       ### indexStats()
       
       ```ts
      @@ -925,6 +1233,67 @@ rows depending on how they match.
       
       ***
       
      +### openBlobFile()
      +
      +```ts
      +openBlobFile(_descriptor, _options?): Promise
      +```
      +
      +Opens a lazy handle from a source-bearing SQL `blob_descriptor` result.
      +
      +The descriptor's source pins the table version, branch, column and row
      +identity, so opening does not change this table's checkout. Null
      +descriptors return `null`. Payload bytes load only when the returned
      +handle is read. Pass BlobReadOptions.signal to cancel the open.
      +
      +#### Parameters
      +
      +* **\_descriptor**: `null` \| [`BlobDescriptor`](../interfaces/BlobDescriptor.md)
      +
      +* **\_options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md)
      +
      +#### Returns
      +
      +`Promise`<`null` \| [`BlobFile`](BlobFile.md)>
      +
      +#### Example
      +
      +```ts
      +const rows = await table
      +  .query()
      +  .select({ video: "blob_descriptor(video)" })
      +  .toArray();
      +const handle = await table.openBlobFile(rows[0].video);
      +if (handle) {
      +  const header = await handle.readRange(0n, 16n);
      +  await handle.close();
      +}
      +```
      +
      +***
      +
      +### openBlobFiles()
      +
      +```ts
      +openBlobFiles(descriptors, options?): AsyncGenerator
      +```
      +
      +Opens source-bearing descriptors in iteration order, preserving nulls.
      +Handles open lazily as the iterable advances. Close each non-null handle
      +after use.
      +
      +#### Parameters
      +
      +* **descriptors**: `Iterable`<`null` \| [`BlobDescriptor`](../interfaces/BlobDescriptor.md)>
      +
      +* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md)
      +
      +#### Returns
      +
      +`AsyncGenerator`<`null` \| [`BlobFile`](BlobFile.md), `any`, `unknown`>
      +
      +***
      +
       ### optimize()
       
       ```ts
      @@ -952,6 +1321,9 @@ supported. Pruning old versions and index optimization are silently
       skipped there instead of being attempted, so this call resolves
       successfully, with zeroed pruning statistics, once the compaction job
       has been submitted; it does not wait for that job to finish.
      +`compactionOptions` can tune the four per-job settings documented in
      +[CompactionOptions](../interfaces/CompactionOptions.md). Older-server errors are propagated without
      +retrying with the settings removed.
       
       #### Parameters
       
      @@ -965,29 +1337,99 @@ has been submitted; it does not wait for that job to finish.
       
       ### prewarmData()
       
      +#### prewarmData(options)
      +
       ```ts
      -abstract prewarmData(columns?): Promise
      +abstract prewarmData(options?): Promise
       ```
       
       Prewarm one or more columns of data in the table.
       
      -#### Parameters
      +This will load the column data into the page cache so that future queries that
      +read those columns avoid the initial cold-start latency.  This call initiates
      +prewarming and returns once the request is accepted; the warming itself may
      +continue in the background. Submission uses SQL PREWARM and needs Flight
      +SQL connectivity. Use [prewarmDataAsync](Table.md#prewarmdataasync) to retain the job handle.
      +
      +Prewarming is generally useful for columns used in filters or projections.
      +Large columns (e.g. high-dimensional vectors or binary data) may not be
      +practical to prewarm.
      +
      +This feature is currently only supported in LanceDB Enterprise.
      +
      +##### Parameters
      +
      +* **options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md)
      +    Columns, a metadata-pruning filter, and per-executor concurrency.
      +    Omitted or empty columns warm every column.
      +
      +##### Returns
      +
      +`Promise`<`void`>
      +
      +##### Example
      +
      +```ts
      +await table.prewarmData({
      +  columns: ["payload"], filter: "quality > 0.7", concurrency: 4,
      +});
      +```
      +
      +#### prewarmData(columns)
      +
      +```ts
      +abstract prewarmData(columns?): Promise
      +```
      +
      +Submit data prewarm using the columns-array form and return after acceptance.
      +
      +##### Parameters
       
       * **columns?**: `string`[]
      -    The columns to prewarm. If undefined, all columns are prewarmed.
      -    This will load the column data into the page cache so that future queries that
      -    read those columns avoid the initial cold-start latency.  This call initiates
      -    prewarming and returns once the request is accepted; the warming itself may
      -    continue in the background.  Calling it on already-prewarmed columns is a
      -    no-op on the server.
      -    Prewarming is generally useful for columns used in filters or projections.
      -    Large columns (e.g. high-dimensional vectors or binary data) may not be
      -    practical to prewarm.
      -    This feature is currently only supported in LanceDB Enterprise.
      +    Columns to warm; omitted or empty means every column.
      +
      +##### Returns
      +
      +`Promise`<`void`>
      +
      +***
      +
      +### prewarmDataAsync()
      +
      +```ts
      +abstract prewarmDataAsync(options?): Promise>
      +```
      +
      +Submit data prewarm through SQL and return its durable warming-job handle.
      +
      +The table handle supplies the branch and namespace. Requires a compatible
      +SQL PREWARM server and Flight SQL connectivity. Standard authorization
      +requires table Select and database/namespace Usage. Status/wait use generic
      +HTTP job APIs; events and cancellation retain their own privileges.
      +No REST fallback or option-dropping retry is performed. Historical-version
      +handles are unsupported; call `checkoutLatest()` first.
      +
      +Submission returns after acceptance. Use `job.wait()` for completion, or
      +save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel
      +the job. After `job.refresh()`, `job.spec.table_version` is the pinned version.
      +
      +#### Parameters
      +
      +* **options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md)
       
       #### Returns
       
      -`Promise`<`void`>
      +`Promise`<[`Job`](Job.md)<[`PrewarmDataResult`](../interfaces/PrewarmDataResult.md)>>
      +
      +#### Example
      +
      +```ts
      +const job = await table.prewarmDataAsync({
      +  columns: ["video"], filter: "quality > $minimum",
      +  parameters: { minimum: 0.7 }, concurrency: 4,
      +});
      +await job.wait();
      +```
       
       ***
       
      @@ -1013,6 +1455,28 @@ Prewarm an index in the table.
       
       ***
       
      +### quarantineFailed()
      +
      +```ts
      +quarantineFailed(_column, _options?): Promise
      +```
      +
      +Quarantine current failures and return the number of affected rows.
      +Set `quarantined: false` to release them for future refreshes.
      +Requires LanceDB Enterprise Function failure workflow version 1 or later.
      +
      +#### Parameters
      +
      +* **\_column**: `string`
      +
      +* **\_options?**: [`FunctionQuarantineOptions`](../interfaces/FunctionQuarantineOptions.md)
      +
      +#### Returns
      +
      +`Promise`<`number`>
      +
      +***
      +
       ### query()
       
       ```ts
      @@ -1086,7 +1550,7 @@ for await (const batch of table.query()) {
       ### refreshColumn()
       
       ```ts
      -abstract refreshColumn(column): Promise
      +abstract refreshColumn(column, options?): Promise
       ```
       
       Fill the rows of a computed column that hold no value yet.
      @@ -1102,6 +1566,10 @@ Enterprise a refresh runs as a server job, through [Table#refreshColumnAsync](Ta
       * **column**: `string`
           The name of the computed column to fill.
       
      +* **options?**: [`RefreshColumnOptions`](../interfaces/RefreshColumnOptions.md)
      +    Refresh options, all LanceDB
      +    Enterprise only; see [Table#refreshColumnAsync](Table.md#refreshcolumnasync).
      +
       #### Returns
       
       `Promise`<[`RefreshColumnResult`](../interfaces/RefreshColumnResult.md)>
      @@ -1114,7 +1582,7 @@ number of rows filled and the new version number of the table.
       ### refreshColumnAsync()
       
       ```ts
      -abstract refreshColumnAsync(column): Promise
      +abstract refreshColumnAsync(column, options?): Promise>
       ```
       
       Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh
      @@ -1134,20 +1602,68 @@ LanceDB Enterprise it is the server's backfill job.
       * **column**: `string`
           The name of the computed column to fill.
       
      +* **options?**: [`RefreshColumnOptions`](../interfaces/RefreshColumnOptions.md)
      +    Refresh options, mirroring the SQL
      +    `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
      +    `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
      +    and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
      +    `maxConcurrency`, `totalCpuMillis`, `totalMemoryBytes`, `supervisorResources`,
      +    `planningWorkers` and `maxExecutorProcessesPerWorker` size registered
      +    Function refreshes. `retryPolicy` overrides user-code retries only when
      +    repeating partial work is safe; set `maxAttempts: 1` to disable retries.
      +    `maxConcurrency` overrides the registered default for this logical
      +    execution only and is a positive integer; it is not an account-wide
      +    quota. `totalCpuMillis`, `totalMemoryBytes`, and `totalGpuCount` override
      +    their corresponding execution-wide resource limits independently. Unset
      +    values inherit column defaults, then Function defaults, then deployment
      +    defaults. A zero GPU limit is valid for CPU-only Functions.
      +    `supervisorResources` and `planningWorkers.resources` are per-pod sizes.
      +    `numWorkers` applies only to expression columns.
      +    `publicationIntervalRows` opts into publishing completed Function split
      +    ranges once their accumulated unpublished rows reach the threshold.
      +    It must be a positive safe integer and requires non-Blob Function outputs.
      +    Omit it for whole-fragment publication. Publications can exceed the
      +    threshold, and remaining rows publish at completion.
      +
       #### Returns
       
      -`Promise`<[`Job`](Job.md)>
      +`Promise`<[`Job`](Job.md)<`void`>>
       
       #### Example
       
       ```ts
      -const job = await table.refreshColumnAsync("doubled");
      +const job = await table.refreshColumnAsync("embedding", {
      +  where: "published_at > '2026-01-01'",
      +  totalCpuMillis: 8000,
      +  totalMemoryBytes: 16 * 1024 ** 3,
      +  maxConcurrency: 4,
      +  publicationIntervalRows: 10000,
      +  errorPolicy: "skip",
      +  maxFailedFraction: 0.01,
      +  rowTimeoutSeconds: 30,
      +});
       await job.wait();
       console.log(await job.status()); // "finished"
       ```
       
       ***
       
      +### resetTableOverrides()
      +
      +```ts
      +resetTableOverrides(): Promise>
      +```
      +
      +Clear a remote Enterprise table's overrides and return an empty object.
      +Local tables and custom table implementations without override support reject
      +this operation.
      +
      +#### Returns
      +
      +`Promise`<`Record`<`string`, `unknown`>>
      +
      +***
      +
       ### restore()
       
       ```ts
      @@ -1171,6 +1687,28 @@ out state and the read_consistency_interval, if any, will apply.
       
       ***
       
      +### retryFailed()
      +
      +```ts
      +retryFailed(_column, _options?): Promise>
      +```
      +
      +Start a job to retry exactly the current failures of one Function column.
      +Filters apply on the server. Quarantined rows are excluded by default.
      +Requires LanceDB Enterprise Function failure workflow version 1 or later.
      +
      +#### Parameters
      +
      +* **\_column**: `string`
      +
      +* **\_options?**: [`RetryFailedOptions`](../interfaces/RetryFailedOptions.md)
      +
      +#### Returns
      +
      +`Promise`<[`Job`](Job.md)<[`RefreshColumnJobResult`](../interfaces/RefreshColumnJobResult.md)>>
      +
      +***
      +
       ### schema()
       
       ```ts
      @@ -1505,6 +2043,66 @@ resolves to the new table version.
       
       ***
       
      +### updateTableOverrides()
      +
      +```ts
      +updateTableOverrides(overrides): Promise>
      +```
      +
      +Recursively merge overrides into a remote Enterprise table's stored overrides.
      +
      +Fetches the current overrides, merges nested objects locally, then sends the
      +complete replacement using REST PUT. Other values replace existing values;
      +unrelated fields from the read snapshot are preserved. This read-modify-write
      +is not atomic: concurrent edits can be overwritten, even to unrelated fields.
      +Coordinate writers when concurrent edits must be preserved. An empty update
      +only reads and returns the current overrides.
      +
      +Unlike this SDK method, CLI `set` and REST PUT replace the overrides object
      +without merging. Use [Table.resetTableOverrides](Table.md#resettableoverrides) to clear all overrides.
      +Local tables and custom table implementations without override support reject
      +this operation.
      +
      +#### Parameters
      +
      +* **overrides**: `Record`<`string`, `unknown`>
      +
      +#### Returns
      +
      +`Promise`<`Record`<`string`, `unknown`>>
      +
      +#### Example
      +
      +```ts
      +await table.updateTableOverrides({
      +  job_types: { compaction: { enabled: false } },
      +});
      +```
      +
      +***
      +
      +### upgradeColumn()
      +
      +```ts
      +upgradeColumn(_column, _options): Promise>
      +```
      +
      +Start an upgrade to an existing immutable Function version and choose
      +which rows to recompute. New and changed inputs use the new version.
      +Requires LanceDB Enterprise Function failure workflow version 1 or later.
      +
      +#### Parameters
      +
      +* **\_column**: `string`
      +
      +* **\_options**: [`UpgradeColumnOptions`](../interfaces/UpgradeColumnOptions.md)
      +
      +#### Returns
      +
      +`Promise`<[`Job`](Job.md)<[`RefreshColumnJobResult`](../interfaces/RefreshColumnJobResult.md)>>
      +
      +***
      +
       ### vectorSearch()
       
       ```ts
      @@ -1565,3 +2163,26 @@ Waits for asynchronous indexing to complete on the table.
       #### Returns
       
       `Promise`<`void`>
      +
      +***
      +
      +### waitFresh()
      +
      +```ts
      +abstract waitFresh(column, timeoutSeconds?): Promise
      +```
      +
      +Poll until no stale or never-computed rows remain.
      +
      +Only HTTP 503 with the exact finalization-pending error code is retried;
      +every other error propagates. Failed rows do not block completion.
      +
      +#### Parameters
      +
      +* **column**: `string`
      +
      +* **timeoutSeconds?**: `number`
      +
      +#### Returns
      +
      +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)>
      diff --git a/docs/src/js/classes/TableDelta.md b/docs/src/js/classes/TableDelta.md
      new file mode 100644
      index 000000000..9318c324b
      --- /dev/null
      +++ b/docs/src/js/classes/TableDelta.md
      @@ -0,0 +1,110 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / TableDelta
      +
      +# Class: TableDelta
      +
      +A handle for reading changes between two pinned table versions.
      +
      +Created by [Table.delta](Table.md#delta). Endpoints are fixed at creation; later writes
      +or tag moves do not change this delta.
      +
      +## Accessors
      +
      +### beginVersion
      +
      +```ts
      +get beginVersion(): bigint
      +```
      +
      +The exclusive start version, as an exact u64 bigint.
      +
      +#### Returns
      +
      +`bigint`
      +
      +***
      +
      +### endVersion
      +
      +```ts
      +get endVersion(): bigint
      +```
      +
      +The inclusive end version, as an exact u64 bigint.
      +
      +#### Returns
      +
      +`bigint`
      +
      +## Methods
      +
      +### deletedRowIds()
      +
      +```ts
      +deletedRowIds(): TableDeltaReader
      +```
      +
      +Stream deleted row IDs. Each batch has one `_rowid: uint64` column.
      +
      +#### Returns
      +
      +[`TableDeltaReader`](../interfaces/TableDeltaReader.md)
      +
      +***
      +
      +### insertedRows()
      +
      +```ts
      +insertedRows(): TableDeltaReader
      +```
      +
      +Stream rows inserted in `(beginVersion, endVersion]`.
      +
      +#### Returns
      +
      +[`TableDeltaReader`](../interfaces/TableDeltaReader.md)
      +
      +***
      +
      +### listTransactions()
      +
      +```ts
      +listTransactions(): Promise
      +```
      +
      +List readable transactions committed in `(beginVersion, endVersion]`.
      +
      +#### Returns
      +
      +`Promise`<[`TableDeltaTransaction`](../interfaces/TableDeltaTransaction.md)[]>
      +
      +***
      +
      +### updatedRows()
      +
      +```ts
      +updatedRows(): TableDeltaReader
      +```
      +
      +Stream rows updated in `(beginVersion, endVersion]`.
      +
      +#### Returns
      +
      +[`TableDeltaReader`](../interfaces/TableDeltaReader.md)
      +
      +***
      +
      +### upsertedRows()
      +
      +```ts
      +upsertedRows(): TableDeltaReader
      +```
      +
      +Stream inserted and updated rows in `(beginVersion, endVersion]`.
      +
      +#### Returns
      +
      +[`TableDeltaReader`](../interfaces/TableDeltaReader.md)
      diff --git a/docs/src/js/classes/Tags.md b/docs/src/js/classes/Tags.md
      index 341673b37..dff91dd70 100644
      --- a/docs/src/js/classes/Tags.md
      +++ b/docs/src/js/classes/Tags.md
      @@ -6,6 +6,8 @@
       
       # Class: Tags
       
      +Tags label table versions with human-readable names.
      +
       ## Constructors
       
       ### new Tags()
      @@ -23,14 +25,19 @@ new Tags(): Tags
       ### create()
       
       ```ts
      -create(tag, version): Promise
      +create(tag, version?): Promise
       ```
       
      +Create a tag for a table version.
      +
      +Omit `version` to tag the version this handle currently shows,
      +including a checked-out version.
      +
       #### Parameters
       
       * **tag**: `string`
       
      -* **version**: `number`
      +* **version?**: `null` \| `number`
       
       #### Returns
       
      diff --git a/docs/src/js/classes/VectorQuery.md b/docs/src/js/classes/VectorQuery.md
      index e4cc0f1cc..2eef209bf 100644
      --- a/docs/src/js/classes/VectorQuery.md
      +++ b/docs/src/js/classes/VectorQuery.md
      @@ -686,6 +686,11 @@ searchEffort(searchEffort): VectorQuery
       
       Set the initial IVF search effort to a finite value in [0, 1].
       
      +Efforts 0.1 and 0.25 target empirical mean partition-routing recall of
      +80% and 90% for L2, cosine and dot through k=100000. The probe budget
      +adapts to the metric and k. Hamming and larger k remain uncalibrated;
      +100000 is not an API limit. Remote queries also require server support.
      +
       The default, null, uses Auto (internally 0.5). Zero starts at the caller
       minimum; one searches all partitions within the caller maximum. Later
       probing may continue when too few candidates are found.
      diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md
      index d6437219e..e98ddccaf 100644
      --- a/docs/src/js/globals.md
      +++ b/docs/src/js/globals.md
      @@ -49,6 +49,7 @@
       - [Session](classes/Session.md)
       - [StaticHeaderProvider](classes/StaticHeaderProvider.md)
       - [Table](classes/Table.md)
      +- [TableDelta](classes/TableDelta.md)
       - [TagContents](classes/TagContents.md)
       - [Tags](classes/Tags.md)
       - [TakeQuery](classes/TakeQuery.md)
      @@ -62,6 +63,8 @@
       - [AddDataOptions](interfaces/AddDataOptions.md)
       - [AddResult](interfaces/AddResult.md)
       - [AlterColumnsResult](interfaces/AlterColumnsResult.md)
      +- [BlobDescriptor](interfaces/BlobDescriptor.md)
      +- [BlobDescriptorSource](interfaces/BlobDescriptorSource.md)
       - [BranchColumnChange](interfaces/BranchColumnChange.md)
       - [BranchColumnSummary](interfaces/BranchColumnSummary.md)
       - [BranchDiff](interfaces/BranchDiff.md)
      @@ -71,12 +74,18 @@
       - [CherryPickError](interfaces/CherryPickError.md)
       - [CherryPickPreview](interfaces/CherryPickPreview.md)
       - [CherryPickResult](interfaces/CherryPickResult.md)
      +- [CleanupOptions](interfaces/CleanupOptions.md)
      +- [CleanupPlan](interfaces/CleanupPlan.md)
      +- [CleanupResult](interfaces/CleanupResult.md)
       - [ClientConfig](interfaces/ClientConfig.md)
       - [ColumnAlteration](interfaces/ColumnAlteration.md)
       - [ColumnOrdering](interfaces/ColumnOrdering.md)
      +- [CompactionOptions](interfaces/CompactionOptions.md)
      +- [CompactionResult](interfaces/CompactionResult.md)
       - [CompactionStats](interfaces/CompactionStats.md)
       - [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md)
       - [ConnectionOptions](interfaces/ConnectionOptions.md)
      +- [CreateBranchOptions](interfaces/CreateBranchOptions.md)
       - [CreateNamespaceOptions](interfaces/CreateNamespaceOptions.md)
       - [CreateNamespaceResponse](interfaces/CreateNamespaceResponse.md)
       - [CreateTableOptions](interfaces/CreateTableOptions.md)
      @@ -94,10 +103,27 @@
       - [FtsToken](interfaces/FtsToken.md)
       - [FullTextQuery](interfaces/FullTextQuery.md)
       - [FullTextSearchOptions](interfaces/FullTextSearchOptions.md)
      +- [FunctionColumnAutoRefreshStatus](interfaces/FunctionColumnAutoRefreshStatus.md)
      +- [FunctionColumnLastRefreshJob](interfaces/FunctionColumnLastRefreshJob.md)
      +- [FunctionColumnStatus](interfaces/FunctionColumnStatus.md)
      +- [FunctionColumnVersionStatus](interfaces/FunctionColumnVersionStatus.md)
       - [FunctionErrorFragment](interfaces/FunctionErrorFragment.md)
      +- [FunctionErrorGroup](interfaces/FunctionErrorGroup.md)
       - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md)
      +- [FunctionErrorRowsOptions](interfaces/FunctionErrorRowsOptions.md)
       - [FunctionErrors](interfaces/FunctionErrors.md)
       - [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md)
      +- [FunctionFailedRow](interfaces/FunctionFailedRow.md)
      +- [FunctionProfile](interfaces/FunctionProfile.md)
      +- [FunctionProfileOptions](interfaces/FunctionProfileOptions.md)
      +- [FunctionProfileWaitOptions](interfaces/FunctionProfileWaitOptions.md)
      +- [FunctionProvenance](interfaces/FunctionProvenance.md)
      +- [FunctionProvenanceOptions](interfaces/FunctionProvenanceOptions.md)
      +- [FunctionQuarantineOptions](interfaces/FunctionQuarantineOptions.md)
      +- [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md)
      +- [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md)
      +- [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md)
      +- [FunctionValueProvenance](interfaces/FunctionValueProvenance.md)
       - [HnswPqOptions](interfaces/HnswPqOptions.md)
       - [HnswSqOptions](interfaces/HnswSqOptions.md)
       - [IndexConfig](interfaces/IndexConfig.md)
      @@ -110,6 +136,7 @@
       - [JobFailureInfo](interfaces/JobFailureInfo.md)
       - [JobInfo](interfaces/JobInfo.md)
       - [JobProgress](interfaces/JobProgress.md)
      +- [JobWaitOptions](interfaces/JobWaitOptions.md)
       - [ListingOptions](interfaces/ListingOptions.md)
       - [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md)
       - [MemtableStats](interfaces/MemtableStats.md)
      @@ -119,15 +146,23 @@
       - [OpenTableOptions](interfaces/OpenTableOptions.md)
       - [OptimizeOptions](interfaces/OptimizeOptions.md)
       - [OptimizeStats](interfaces/OptimizeStats.md)
      +- [PrewarmDataOptions](interfaces/PrewarmDataOptions.md)
      +- [PrewarmDataPlan](interfaces/PrewarmDataPlan.md)
      +- [PrewarmDataResult](interfaces/PrewarmDataResult.md)
      +- [PrewarmPruningSummary](interfaces/PrewarmPruningSummary.md)
       - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md)
       - [RTEStats](interfaces/RTEStats.md)
       - [RTEWriteSpec](interfaces/RTEWriteSpec.md)
      +- [RTreeOptions](interfaces/RTreeOptions.md)
      +- [RefreshColumnJobResult](interfaces/RefreshColumnJobResult.md)
      +- [RefreshColumnOptions](interfaces/RefreshColumnOptions.md)
       - [RefreshColumnResult](interfaces/RefreshColumnResult.md)
       - [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md)
       - [RemovalStats](interfaces/RemovalStats.md)
       - [RenameTableOptions](interfaces/RenameTableOptions.md)
       - [RestNamespaceConfig](interfaces/RestNamespaceConfig.md)
       - [RetryConfig](interfaces/RetryConfig.md)
      +- [RetryFailedOptions](interfaces/RetryFailedOptions.md)
       - [ScannableOptions](interfaces/ScannableOptions.md)
       - [SessionLogout](interfaces/SessionLogout.md)
       - [SessionStatus](interfaces/SessionStatus.md)
      @@ -137,6 +172,8 @@
       - [SplitRandomOptions](interfaces/SplitRandomOptions.md)
       - [SplitSequentialOptions](interfaces/SplitSequentialOptions.md)
       - [SsTableStats](interfaces/SsTableStats.md)
      +- [TableDeltaReader](interfaces/TableDeltaReader.md)
      +- [TableDeltaTransaction](interfaces/TableDeltaTransaction.md)
       - [TableNamesOptions](interfaces/TableNamesOptions.md)
       - [TableShardStats](interfaces/TableShardStats.md)
       - [TableStatistics](interfaces/TableStatistics.md)
      @@ -148,6 +185,7 @@
       - [UpdateFieldMetadataResult](interfaces/UpdateFieldMetadataResult.md)
       - [UpdateOptions](interfaces/UpdateOptions.md)
       - [UpdateResult](interfaces/UpdateResult.md)
      +- [UpgradeColumnOptions](interfaces/UpgradeColumnOptions.md)
       - [Version](interfaces/Version.md)
       - [ViewDescription](interfaces/ViewDescription.md)
       - [WriteExecutionOptions](interfaces/WriteExecutionOptions.md)
      @@ -162,18 +200,26 @@
       - [BlobMode](type-aliases/BlobMode.md)
       - [BlobOptions](type-aliases/BlobOptions.md)
       - [BlobRange](type-aliases/BlobRange.md)
      +- [BlobRangeRequest](type-aliases/BlobRangeRequest.md)
       - [BlobReadOptions](type-aliases/BlobReadOptions.md)
       - [BlobUri](type-aliases/BlobUri.md)
       - [Data](type-aliases/Data.md)
       - [DataLike](type-aliases/DataLike.md)
       - [DataTypeLike](type-aliases/DataTypeLike.md)
      +- [DeltaVersion](type-aliases/DeltaVersion.md)
       - [ExprLike](type-aliases/ExprLike.md)
       - [FieldLike](type-aliases/FieldLike.md)
      +- [FunctionProfileKind](type-aliases/FunctionProfileKind.md)
      +- [FunctionProfileStatus](type-aliases/FunctionProfileStatus.md)
      +- [FunctionRecompute](type-aliases/FunctionRecompute.md)
       - [IntoSql](type-aliases/IntoSql.md)
       - [IntoVector](type-aliases/IntoVector.md)
       - [JobProgressCallback](type-aliases/JobProgressCallback.md)
      +- [JobState](type-aliases/JobState.md)
       - [MaterializedViewSelect](type-aliases/MaterializedViewSelect.md)
       - [MultiVector](type-aliases/MultiVector.md)
      +- [QueryParameterValue](type-aliases/QueryParameterValue.md)
      +- [QueryParameters](type-aliases/QueryParameters.md)
       - [RecordBatchLike](type-aliases/RecordBatchLike.md)
       - [SchemaLike](type-aliases/SchemaLike.md)
       - [TableLike](type-aliases/TableLike.md)
      diff --git a/docs/src/js/interfaces/AddDataOptions.md b/docs/src/js/interfaces/AddDataOptions.md
      index f1f57b98b..567269471 100644
      --- a/docs/src/js/interfaces/AddDataOptions.md
      +++ b/docs/src/js/interfaces/AddDataOptions.md
      @@ -71,3 +71,15 @@ await table.add(data, {
         },
       });
       ```
      +
      +***
      +
      +### retries?
      +
      +```ts
      +optional retries: number;
      +```
      +
      +Override the remote retry budget for this call (0 to 255). Zero disables
      +retries, including multipart parts. Ambiguous commits are never replayed.
      +Ignored by LanceDB Embedded.
      diff --git a/docs/src/js/interfaces/BlobDescriptor.md b/docs/src/js/interfaces/BlobDescriptor.md
      new file mode 100644
      index 000000000..7576b856f
      --- /dev/null
      +++ b/docs/src/js/interfaces/BlobDescriptor.md
      @@ -0,0 +1,59 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / BlobDescriptor
      +
      +# Interface: BlobDescriptor
      +
      +A source-bearing Blob V2 descriptor accepted by [Table.openBlobFile](../classes/Table.md#openblobfile).
      +Query results expose these fields as an Arrow struct. The source pins the
      +table version, branch, column and row identity used to open the handle.
      +
      +## Properties
      +
      +### blob\_id
      +
      +```ts
      +blob_id: number;
      +```
      +
      +***
      +
      +### blob\_uri
      +
      +```ts
      +blob_uri: string;
      +```
      +
      +***
      +
      +### kind
      +
      +```ts
      +kind: number;
      +```
      +
      +***
      +
      +### position
      +
      +```ts
      +position: number | bigint;
      +```
      +
      +***
      +
      +### size
      +
      +```ts
      +size: number | bigint;
      +```
      +
      +***
      +
      +### source
      +
      +```ts
      +source: BlobDescriptorSource;
      +```
      diff --git a/docs/src/js/interfaces/BlobDescriptorSource.md b/docs/src/js/interfaces/BlobDescriptorSource.md
      new file mode 100644
      index 000000000..994adec39
      --- /dev/null
      +++ b/docs/src/js/interfaces/BlobDescriptorSource.md
      @@ -0,0 +1,66 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / BlobDescriptorSource
      +
      +# Interface: BlobDescriptorSource
      +
      +A source-bearing Blob V2 descriptor returned by the SQL `blob_descriptor`
      +function. Field names match the descriptor object/Arrow struct shape.
      +
      +## Properties
      +
      +### branch?
      +
      +```ts
      +optional branch: null | string;
      +```
      +
      +***
      +
      +### column
      +
      +```ts
      +column: string;
      +```
      +
      +***
      +
      +### committed\_at\_micros
      +
      +```ts
      +committed_at_micros: number | bigint;
      +```
      +
      +***
      +
      +### row\_is\_address
      +
      +```ts
      +row_is_address: boolean;
      +```
      +
      +***
      +
      +### row\_reference
      +
      +```ts
      +row_reference: number | bigint;
      +```
      +
      +***
      +
      +### uri
      +
      +```ts
      +uri: string;
      +```
      +
      +***
      +
      +### version
      +
      +```ts
      +version: number | bigint;
      +```
      diff --git a/docs/src/js/interfaces/CherryPickResult.md b/docs/src/js/interfaces/CherryPickResult.md
      index fdec8eedd..a5f416629 100644
      --- a/docs/src/js/interfaces/CherryPickResult.md
      +++ b/docs/src/js/interfaces/CherryPickResult.md
      @@ -38,8 +38,8 @@ preview: CherryPickPreview;
       
       ```ts
       status:
      -  | "ready"
         | "failed"
      +  | "ready"
         | "notImplemented"
         | "cherryPicked"
         | "unknown";
      diff --git a/docs/src/js/interfaces/CleanupOptions.md b/docs/src/js/interfaces/CleanupOptions.md
      new file mode 100644
      index 000000000..853dfad9a
      --- /dev/null
      +++ b/docs/src/js/interfaces/CleanupOptions.md
      @@ -0,0 +1,19 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / CleanupOptions
      +
      +# Interface: CleanupOptions
      +
      +Per-run retention; omission inherits selected table/branch then deployment policy.
      +
      +## Properties
      +
      +### minAgeSeconds?
      +
      +```ts
      +optional minAgeSeconds: number;
      +```
      +
      +Minimum old-version age in seconds. Zero is explicit, not omitted.
      diff --git a/docs/src/js/interfaces/CleanupPlan.md b/docs/src/js/interfaces/CleanupPlan.md
      new file mode 100644
      index 000000000..14fc7600c
      --- /dev/null
      +++ b/docs/src/js/interfaces/CleanupPlan.md
      @@ -0,0 +1,57 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / CleanupPlan
      +
      +# Interface: CleanupPlan
      +
      +Read-only deletion estimates; no job or deletion snapshot is reserved.
      +
      +## Properties
      +
      +### bytesToRemove
      +
      +```ts
      +bytesToRemove: number;
      +```
      +
      +***
      +
      +### cutoffMillis
      +
      +```ts
      +cutoffMillis: number;
      +```
      +
      +***
      +
      +### formatVersion
      +
      +```ts
      +formatVersion: number;
      +```
      +
      +***
      +
      +### minAgeSeconds
      +
      +```ts
      +minAgeSeconds: number;
      +```
      +
      +***
      +
      +### sourceVersion
      +
      +```ts
      +sourceVersion: number;
      +```
      +
      +***
      +
      +### versionsToRemove
      +
      +```ts
      +versionsToRemove: number;
      +```
      diff --git a/docs/src/js/interfaces/CleanupResult.md b/docs/src/js/interfaces/CleanupResult.md
      new file mode 100644
      index 000000000..c3d8c51d7
      --- /dev/null
      +++ b/docs/src/js/interfaces/CleanupResult.md
      @@ -0,0 +1,61 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / CleanupResult
      +
      +# Interface: CleanupResult
      +
      +Version-deletion outcome. Best-effort auxiliary sweeps are excluded.
      +
      +## Properties
      +
      +### bytesRemoved
      +
      +```ts
      +bytesRemoved: null | number;
      +```
      +
      +***
      +
      +### failedDeletes
      +
      +```ts
      +failedDeletes: null | number;
      +```
      +
      +Failed object deletions, if measured. Successful removals are retained.
      +
      +***
      +
      +### formatVersion
      +
      +```ts
      +formatVersion: number;
      +```
      +
      +***
      +
      +### minAgeSeconds
      +
      +```ts
      +minAgeSeconds: number;
      +```
      +
      +***
      +
      +### oldVersions
      +
      +```ts
      +oldVersions: null | number;
      +```
      +
      +***
      +
      +### statisticsComplete
      +
      +```ts
      +statisticsComplete: boolean;
      +```
      +
      +False after uncertain retry/recovery; both counts are then null.
      diff --git a/docs/src/js/interfaces/CompactionOptions.md b/docs/src/js/interfaces/CompactionOptions.md
      new file mode 100644
      index 000000000..135266567
      --- /dev/null
      +++ b/docs/src/js/interfaces/CompactionOptions.md
      @@ -0,0 +1,49 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / CompactionOptions
      +
      +# Interface: CompactionOptions
      +
      +Per-invocation compaction settings. Values must be safe integers.
      +
      +## Properties
      +
      +### batchSize?
      +
      +```ts
      +optional batchSize: number;
      +```
      +
      +Positive scanner batch size in rows.
      +
      +***
      +
      +### ioBufferSize?
      +
      +```ts
      +optional ioBufferSize: number;
      +```
      +
      +Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure.
      +
      +***
      +
      +### maxSourceRows?
      +
      +```ts
      +optional maxSourceRows: number;
      +```
      +
      +Positive live-source-row budget across whole tasks; an oversized first task can produce no work.
      +
      +***
      +
      +### targetRowsPerFragment?
      +
      +```ts
      +optional targetRowsPerFragment: number;
      +```
      +
      +Positive target rows per output fragment; also affects candidate selection.
      diff --git a/docs/src/js/interfaces/CompactionResult.md b/docs/src/js/interfaces/CompactionResult.md
      new file mode 100644
      index 000000000..623dfe453
      --- /dev/null
      +++ b/docs/src/js/interfaces/CompactionResult.md
      @@ -0,0 +1,99 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / CompactionResult
      +
      +# Interface: CompactionResult
      +
      +Actual committed outcome of one remote compaction job.
      +
      +## Properties
      +
      +### completionPercentage
      +
      +```ts
      +completionPercentage: number;
      +```
      +
      +Percentage of planned live rows committed, from 0 to 100.
      +
      +***
      +
      +### filesAdded
      +
      +```ts
      +filesAdded: null | number;
      +```
      +
      +Files added, including deletion files; null if an older worker omitted it.
      +
      +***
      +
      +### filesRemoved
      +
      +```ts
      +filesRemoved: null | number;
      +```
      +
      +Files removed, including deletion files; null if an older worker omitted it.
      +
      +***
      +
      +### fragmentsAdded
      +
      +```ts
      +fragmentsAdded: null | number;
      +```
      +
      +Fragments added by committed rewrites; null if an older worker omitted it.
      +
      +***
      +
      +### fragmentsRemoved
      +
      +```ts
      +fragmentsRemoved: null | number;
      +```
      +
      +Fragments removed by committed rewrites; null if an older worker omitted it.
      +
      +***
      +
      +### moreWork
      +
      +```ts
      +moreWork: boolean;
      +```
      +
      +A bounded run left eligible work for another invocation.
      +
      +***
      +
      +### partialCommit
      +
      +```ts
      +partialCommit: boolean;
      +```
      +
      +Some planned groups were not committed.
      +
      +***
      +
      +### rowsFailed
      +
      +```ts
      +rowsFailed: number;
      +```
      +
      +Planned live rows not committed by this job.
      +
      +***
      +
      +### rowsSucceeded
      +
      +```ts
      +rowsSucceeded: number;
      +```
      +
      +Live source rows in committed rewrite groups.
      diff --git a/docs/src/js/interfaces/CreateBranchOptions.md b/docs/src/js/interfaces/CreateBranchOptions.md
      new file mode 100644
      index 000000000..2cfb3406d
      --- /dev/null
      +++ b/docs/src/js/interfaces/CreateBranchOptions.md
      @@ -0,0 +1,20 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / CreateBranchOptions
      +
      +# Interface: CreateBranchOptions
      +
      +Options for creating a branch from a named source.
      +
      +## Properties
      +
      +### fromTag
      +
      +```ts
      +fromTag: string;
      +```
      +
      +Tag to fork from. The tag keeps the branch and version it points to.
      +Cannot be combined with `fromRef` or `fromVersion`.
      diff --git a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md
      new file mode 100644
      index 000000000..eb95c8004
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md
      @@ -0,0 +1,98 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionColumnAutoRefreshStatus
      +
      +# Interface: FunctionColumnAutoRefreshStatus
      +
      +Automatic-refresh projection for a Function output.
      +
      +## Properties
      +
      +### activeJobId?
      +
      +```ts
      +optional activeJobId: string;
      +```
      +
      +***
      +
      +### blockedReason?
      +
      +```ts
      +optional blockedReason:
      +  | "cancelled"
      +  | "table_has_mem_wal"
      +  | "inputs_not_settled"
      +  | "dependency_in_flight"
      +  | "table_capacity"
      +  | "preparation_backoff"
      +  | "failure_threshold_reached"
      +  | "binding_revision_missing";
      +```
      +
      +***
      +
      +### effectiveCooldownMillis?
      +
      +```ts
      +optional effectiveCooldownMillis: bigint;
      +```
      +
      +***
      +
      +### enabled
      +
      +```ts
      +enabled: boolean;
      +```
      +
      +***
      +
      +### failureStreak
      +
      +```ts
      +failureStreak: number;
      +```
      +
      +***
      +
      +### intervalSeconds?
      +
      +```ts
      +optional intervalSeconds: bigint;
      +```
      +
      +***
      +
      +### nextRunAtMillis
      +
      +```ts
      +nextRunAtMillis: null | bigint;
      +```
      +
      +***
      +
      +### nextRunAtReason?
      +
      +```ts
      +optional nextRunAtReason: string;
      +```
      +
      +***
      +
      +### state
      +
      +```ts
      +state:
      +  | "queued"
      +  | "running"
      +  | "disabled"
      +  | "ready"
      +  | "up_to_date"
      +  | "waiting_interval"
      +  | "waiting_backoff"
      +  | "blocked"
      +  | "unobservable";
      +```
      diff --git a/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md
      new file mode 100644
      index 000000000..a7c1df2aa
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md
      @@ -0,0 +1,51 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionColumnLastRefreshJob
      +
      +# Interface: FunctionColumnLastRefreshJob
      +
      +Latest matching refresh Job projected for a Function output.
      +
      +## Properties
      +
      +### automatic?
      +
      +```ts
      +optional automatic: boolean;
      +```
      +
      +***
      +
      +### completedAtMillis?
      +
      +```ts
      +optional completedAtMillis: bigint;
      +```
      +
      +***
      +
      +### failure?
      +
      +```ts
      +optional failure: JobFailureInfo;
      +```
      +
      +Structured failure details for a failed Job.
      +
      +***
      +
      +### jobId
      +
      +```ts
      +jobId: string;
      +```
      +
      +***
      +
      +### state
      +
      +```ts
      +state: string;
      +```
      diff --git a/docs/src/js/interfaces/FunctionColumnStatus.md b/docs/src/js/interfaces/FunctionColumnStatus.md
      new file mode 100644
      index 000000000..0c299ee2b
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionColumnStatus.md
      @@ -0,0 +1,108 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionColumnStatus
      +
      +# Interface: FunctionColumnStatus
      +
      +Exact four-way status of one Function output at one table version.
      +
      +## Properties
      +
      +### autoRefresh
      +
      +```ts
      +autoRefresh: FunctionColumnAutoRefreshStatus;
      +```
      +
      +***
      +
      +### bindingId
      +
      +```ts
      +bindingId: string;
      +```
      +
      +***
      +
      +### column
      +
      +```ts
      +column: string;
      +```
      +
      +***
      +
      +### failed
      +
      +```ts
      +failed: bigint;
      +```
      +
      +***
      +
      +### fresh
      +
      +```ts
      +fresh: bigint;
      +```
      +
      +***
      +
      +### function
      +
      +```ts
      +function: FunctionColumnVersionStatus;
      +```
      +
      +***
      +
      +### lastFailureJob?
      +
      +```ts
      +optional lastFailureJob: FunctionColumnLastRefreshJob;
      +```
      +
      +Newest failed refresh Job. This remains present when `lastRefreshJob`
      +is a later cancellation.
      +
      +***
      +
      +### lastRefreshJob?
      +
      +```ts
      +optional lastRefreshJob: FunctionColumnLastRefreshJob;
      +```
      +
      +***
      +
      +### neverComputed
      +
      +```ts
      +neverComputed: bigint;
      +```
      +
      +***
      +
      +### rows
      +
      +```ts
      +rows: bigint;
      +```
      +
      +***
      +
      +### stale
      +
      +```ts
      +stale: bigint;
      +```
      +
      +***
      +
      +### tableVersion
      +
      +```ts
      +tableVersion: bigint;
      +```
      diff --git a/docs/src/js/interfaces/FunctionColumnVersionStatus.md b/docs/src/js/interfaces/FunctionColumnVersionStatus.md
      new file mode 100644
      index 000000000..fa02139d2
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionColumnVersionStatus.md
      @@ -0,0 +1,57 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionColumnVersionStatus
      +
      +# Interface: FunctionColumnVersionStatus
      +
      +Exact immutable Function revision attached to a table output.
      +
      +## Properties
      +
      +### location
      +
      +```ts
      +location: string;
      +```
      +
      +***
      +
      +### manifestDigest
      +
      +```ts
      +manifestDigest: string;
      +```
      +
      +***
      +
      +### name
      +
      +```ts
      +name: string;
      +```
      +
      +***
      +
      +### namespacePath
      +
      +```ts
      +namespacePath: string[];
      +```
      +
      +***
      +
      +### objectId
      +
      +```ts
      +objectId: string;
      +```
      +
      +***
      +
      +### version
      +
      +```ts
      +version: string;
      +```
      diff --git a/docs/src/js/interfaces/FunctionErrorGroup.md b/docs/src/js/interfaces/FunctionErrorGroup.md
      new file mode 100644
      index 000000000..cb804b07b
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionErrorGroup.md
      @@ -0,0 +1,41 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionErrorGroup
      +
      +# Interface: FunctionErrorGroup
      +
      +One cause among the returned Function errors.
      +
      +## Properties
      +
      +### column
      +
      +```ts
      +column: string;
      +```
      +
      +***
      +
      +### errorMessage
      +
      +```ts
      +errorMessage: string;
      +```
      +
      +***
      +
      +### errorType
      +
      +```ts
      +errorType: string;
      +```
      +
      +***
      +
      +### rowsFailed
      +
      +```ts
      +rowsFailed: bigint;
      +```
      diff --git a/docs/src/js/interfaces/FunctionErrorRecord.md b/docs/src/js/interfaces/FunctionErrorRecord.md
      index 3a26534a0..a95547b06 100644
      --- a/docs/src/js/interfaces/FunctionErrorRecord.md
      +++ b/docs/src/js/interfaces/FunctionErrorRecord.md
      @@ -10,6 +10,16 @@ One row a Function refresh skipped, as the server recorded it.
       
       ## Properties
       
      +### attempts?
      +
      +```ts
      +optional attempts: number;
      +```
      +
      +Number of failed invocation attempts, when recorded.
      +
      +***
      +
       ### column
       
       ```ts
      @@ -42,6 +52,16 @@ errorType: string;
       
       ***
       
      +### firstSeenAtMillis?
      +
      +```ts
      +optional firstSeenAtMillis: number;
      +```
      +
      +First failure time for this row, when recorded.
      +
      +***
      +
       ### fragmentId
       
       ```ts
      @@ -66,6 +86,16 @@ functionVersion: string;
       
       ***
       
      +### input?
      +
      +```ts
      +optional input: unknown;
      +```
      +
      +Source identities for a materialized-view Function invocation.
      +
      +***
      +
       ### jobId
       
       ```ts
      @@ -74,6 +104,46 @@ jobId: string;
       
       ***
       
      +### lastSeenAtMillis?
      +
      +```ts
      +optional lastSeenAtMillis: number;
      +```
      +
      +Latest failure time for this row, when recorded.
      +
      +***
      +
      +### quarantined?
      +
      +```ts
      +optional quarantined: boolean;
      +```
      +
      +Whether the failure is quarantined. Absent on older listings.
      +
      +***
      +
      +### rowAddress?
      +
      +```ts
      +optional rowAddress: bigint;
      +```
      +
      +Physical row address at the recorded version. A rewrite can change it.
      +
      +***
      +
      +### rowId?
      +
      +```ts
      +optional rowId: bigint;
      +```
      +
      +Stable row identity when recorded. It survives compaction and rewrite.
      +
      +***
      +
       ### rowOffset?
       
       ```ts
      @@ -90,3 +160,13 @@ detail was capped.
       ```ts
       tableVersion: number;
       ```
      +
      +***
      +
      +### traceback?
      +
      +```ts
      +optional traceback: string;
      +```
      +
      +User-code traceback, possibly truncated by the server.
      diff --git a/docs/src/js/interfaces/FunctionErrorRowsOptions.md b/docs/src/js/interfaces/FunctionErrorRowsOptions.md
      new file mode 100644
      index 000000000..da2cdd03c
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionErrorRowsOptions.md
      @@ -0,0 +1,65 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionErrorRowsOptions
      +
      +# Interface: FunctionErrorRowsOptions
      +
      +Filters and projection for current failing inputs.
      +
      +## Extends
      +
      +- `Pick`<[`FunctionErrorsOptions`](FunctionErrorsOptions.md), `"column"` \| `"jobId"` \| `"limit"`>
      +
      +## Properties
      +
      +### column?
      +
      +```ts
      +optional column: string;
      +```
      +
      +Only errors on this column.
      +
      +#### Inherited from
      +
      +`Pick.column`
      +
      +***
      +
      +### columns?
      +
      +```ts
      +optional columns: string[];
      +```
      +
      +Source columns to return. Defaults to all source columns.
      +
      +***
      +
      +### jobId?
      +
      +```ts
      +optional jobId: string;
      +```
      +
      +Only errors recorded by this job.
      +
      +#### Inherited from
      +
      +`Pick.jobId`
      +
      +***
      +
      +### limit?
      +
      +```ts
      +optional limit: number;
      +```
      +
      +At most this many records (server default 10000, cap 100000).
      +
      +#### Inherited from
      +
      +`Pick.limit`
      diff --git a/docs/src/js/interfaces/FunctionErrors.md b/docs/src/js/interfaces/FunctionErrors.md
      index bee0a80d8..2aa19c193 100644
      --- a/docs/src/js/interfaces/FunctionErrors.md
      +++ b/docs/src/js/interfaces/FunctionErrors.md
      @@ -10,6 +10,17 @@ A table's per-row Function errors.
       
       ## Properties
       
      +### errorGroups?
      +
      +```ts
      +optional errorGroups: FunctionErrorGroup[];
      +```
      +
      +Grouped causes over the returned records, if the server supports the workflow.
      +Counts can be incomplete. Check `truncated` and `fragments` before using them as totals.
      +
      +***
      +
       ### fragments
       
       ```ts
      @@ -20,6 +31,16 @@ Fragments whose detail was capped.
       
       ***
       
      +### pageToken?
      +
      +```ts
      +optional pageToken: string;
      +```
      +
      +Continue the same job/filter. Absent for complete pages and older servers.
      +
      +***
      +
       ### records
       
       ```ts
      @@ -37,3 +58,13 @@ truncated: boolean;
       ```
       
       Whether the listing stopped at its limit.
      +
      +***
      +
      +### workflowVersion?
      +
      +```ts
      +optional workflowVersion: number;
      +```
      +
      +Version of the Enterprise row-failure workflow, if advertised by the server.
      diff --git a/docs/src/js/interfaces/FunctionErrorsOptions.md b/docs/src/js/interfaces/FunctionErrorsOptions.md
      index af0e71cfe..1a4f44dd8 100644
      --- a/docs/src/js/interfaces/FunctionErrorsOptions.md
      +++ b/docs/src/js/interfaces/FunctionErrorsOptions.md
      @@ -20,6 +20,16 @@ Only errors on this column.
       
       ***
       
      +### history?
      +
      +```ts
      +optional history: boolean;
      +```
      +
      +Include retained historical attempts, including repaired rows. Requires workflow version 1 or later.
      +
      +***
      +
       ### jobId?
       
       ```ts
      @@ -37,3 +47,13 @@ optional limit: number;
       ```
       
       At most this many records (server default 10000, cap 100000).
      +
      +***
      +
      +### pageToken?
      +
      +```ts
      +optional pageToken: string;
      +```
      +
      +Empty starts retained history, including repaired rows, for an exact jobId; otherwise continue that page.
      diff --git a/docs/src/js/interfaces/FunctionFailedRow.md b/docs/src/js/interfaces/FunctionFailedRow.md
      new file mode 100644
      index 000000000..21a5019c5
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionFailedRow.md
      @@ -0,0 +1,29 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionFailedRow
      +
      +# Interface: FunctionFailedRow
      +
      +A failed Function-column row and its source data at the table's read snapshot.
      +
      +## Properties
      +
      +### error
      +
      +```ts
      +error: FunctionErrorRecord;
      +```
      +
      +The failure for this row and Function column.
      +
      +***
      +
      +### input
      +
      +```ts
      +input: Record;
      +```
      +
      +Values of the requested source columns.
      diff --git a/docs/src/js/interfaces/FunctionProfile.md b/docs/src/js/interfaces/FunctionProfile.md
      new file mode 100644
      index 000000000..f33f33e49
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionProfile.md
      @@ -0,0 +1,126 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionProfile
      +
      +# Interface: FunctionProfile
      +
      +A capture identity and status snapshot. Keep profileId for retained lookup
      +after the Function refresh completes. Timestamp fields are epoch milliseconds.
      +
      +## Properties
      +
      +### artifactId
      +
      +```ts
      +readonly artifactId: null | string;
      +```
      +
      +***
      +
      +### completedAtMillis
      +
      +```ts
      +readonly completedAtMillis: null | number;
      +```
      +
      +***
      +
      +### deadlineAtMillis
      +
      +```ts
      +readonly deadlineAtMillis: number;
      +```
      +
      +***
      +
      +### durationSeconds
      +
      +```ts
      +readonly durationSeconds: number;
      +```
      +
      +***
      +
      +### error
      +
      +```ts
      +readonly error: null | string;
      +```
      +
      +The server's capture failure reason; this is not a refresh job failure.
      +
      +***
      +
      +### executionEpoch
      +
      +```ts
      +readonly executionEpoch: number;
      +```
      +
      +***
      +
      +### expiresAtMillis
      +
      +```ts
      +readonly expiresAtMillis: number;
      +```
      +
      +Upper retention bound; job scratch reclamation can remove artifacts sooner.
      +
      +***
      +
      +### jobId
      +
      +```ts
      +readonly jobId: string;
      +```
      +
      +***
      +
      +### kind
      +
      +```ts
      +readonly kind: FunctionProfileKind;
      +```
      +
      +***
      +
      +### profileId
      +
      +```ts
      +readonly profileId: string;
      +```
      +
      +***
      +
      +### requestedAtMillis
      +
      +```ts
      +readonly requestedAtMillis: number;
      +```
      +
      +***
      +
      +### sessionSlot
      +
      +```ts
      +readonly sessionSlot: number;
      +```
      +
      +***
      +
      +### status
      +
      +```ts
      +readonly status: FunctionProfileStatus;
      +```
      +
      +***
      +
      +### workerId
      +
      +```ts
      +readonly workerId: string;
      +```
      diff --git a/docs/src/js/interfaces/FunctionProfileOptions.md b/docs/src/js/interfaces/FunctionProfileOptions.md
      new file mode 100644
      index 000000000..2115fd027
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionProfileOptions.md
      @@ -0,0 +1,39 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionProfileOptions
      +
      +# Interface: FunctionProfileOptions
      +
      +Options for requesting a Function worker capture.
      +
      +## Properties
      +
      +### durationSeconds?
      +
      +```ts
      +optional durationSeconds: number;
      +```
      +
      +1–30 seconds for CPU/memory, default 10; 1–5 for GPU, default 5.
      +
      +***
      +
      +### kind?
      +
      +```ts
      +optional kind: FunctionProfileKind;
      +```
      +
      +CPU samples, retained Python allocations, or PyTorch CUDA activities.
      +
      +***
      +
      +### sessionSlot?
      +
      +```ts
      +optional sessionSlot: number;
      +```
      +
      +Python execution session within the worker; default zero.
      diff --git a/docs/src/js/interfaces/FunctionProfileWaitOptions.md b/docs/src/js/interfaces/FunctionProfileWaitOptions.md
      new file mode 100644
      index 000000000..1a579a5af
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionProfileWaitOptions.md
      @@ -0,0 +1,29 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionProfileWaitOptions
      +
      +# Interface: FunctionProfileWaitOptions
      +
      +Client-side controls while waiting for a Function worker capture.
      +
      +## Properties
      +
      +### pollIntervalMs?
      +
      +```ts
      +optional pollIntervalMs: number;
      +```
      +
      +Delay between status requests; defaults to 2,000 ms and must be positive.
      +
      +***
      +
      +### timeoutMs?
      +
      +```ts
      +optional timeoutMs: number;
      +```
      +
      +Maximum wait including HTTP requests and sleeps; defaults to 60,000 ms.
      diff --git a/docs/src/js/interfaces/FunctionProvenance.md b/docs/src/js/interfaces/FunctionProvenance.md
      new file mode 100644
      index 000000000..98eb66f34
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionProvenance.md
      @@ -0,0 +1,27 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionProvenance
      +
      +# Interface: FunctionProvenance
      +
      +A bounded producing-version listing for a table snapshot.
      +
      +## Properties
      +
      +### records
      +
      +```ts
      +records: FunctionValueProvenance[];
      +```
      +
      +***
      +
      +### truncated
      +
      +```ts
      +truncated: boolean;
      +```
      +
      +Whether the listing stopped at its limit.
      diff --git a/docs/src/js/interfaces/FunctionProvenanceOptions.md b/docs/src/js/interfaces/FunctionProvenanceOptions.md
      new file mode 100644
      index 000000000..01aacd614
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionProvenanceOptions.md
      @@ -0,0 +1,29 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionProvenanceOptions
      +
      +# Interface: FunctionProvenanceOptions
      +
      +Snapshot and record limit for a producing-version listing.
      +
      +## Properties
      +
      +### limit?
      +
      +```ts
      +optional limit: number;
      +```
      +
      +Maximum records to return (server default 10000, cap 100000).
      +
      +***
      +
      +### version?
      +
      +```ts
      +optional version: number | bigint;
      +```
      +
      +An exact table version. Defaults to the table handle's read version.
      diff --git a/docs/src/js/interfaces/FunctionQuarantineOptions.md b/docs/src/js/interfaces/FunctionQuarantineOptions.md
      new file mode 100644
      index 000000000..e8c5e3679
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionQuarantineOptions.md
      @@ -0,0 +1,49 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionQuarantineOptions
      +
      +# Interface: FunctionQuarantineOptions
      +
      +Select current failures to quarantine or release.
      +
      +## Properties
      +
      +### afterAttempts?
      +
      +```ts
      +optional afterAttempts: number;
      +```
      +
      +Only failures with at least this many attempts. Defaults to 1.
      +
      +***
      +
      +### errorType?
      +
      +```ts
      +optional errorType: string;
      +```
      +
      +Only failures with this exception class.
      +
      +***
      +
      +### jobId?
      +
      +```ts
      +optional jobId: string;
      +```
      +
      +Only failures recorded by this job.
      +
      +***
      +
      +### quarantined?
      +
      +```ts
      +optional quarantined: boolean;
      +```
      +
      +Quarantine by default. Set false to release failures for later refreshes.
      diff --git a/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md b/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md
      new file mode 100644
      index 000000000..48a8a209d
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md
      @@ -0,0 +1,50 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionRefreshPlanningConfig
      +
      +# Interface: FunctionRefreshPlanningConfig
      +
      +Resources and sizing policy for the planning fleet of one registered
      +Function refresh.
      +
      +## Properties
      +
      +### fragmentsPerWorker
      +
      +```ts
      +fragmentsPerWorker: number;
      +```
      +
      +Maximum fragments assigned to one planning worker.
      +
      +***
      +
      +### maxWorkers
      +
      +```ts
      +maxWorkers: number;
      +```
      +
      +Maximum number of planning workers.
      +
      +***
      +
      +### resources
      +
      +```ts
      +resources: FunctionRefreshPodResources;
      +```
      +
      +CPU, memory, and ephemeral-storage limits for one planning worker.
      +
      +***
      +
      +### rowsPerWorker
      +
      +```ts
      +rowsPerWorker: number;
      +```
      +
      +Maximum rows assigned to one planning worker.
      diff --git a/docs/src/js/interfaces/FunctionRefreshPodResources.md b/docs/src/js/interfaces/FunctionRefreshPodResources.md
      new file mode 100644
      index 000000000..99d55512e
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionRefreshPodResources.md
      @@ -0,0 +1,40 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionRefreshPodResources
      +
      +# Interface: FunctionRefreshPodResources
      +
      +CPU, memory, and ephemeral-storage limits for one Function refresh
      +control-plane pod.
      +
      +## Properties
      +
      +### cpuMillis
      +
      +```ts
      +cpuMillis: number;
      +```
      +
      +CPU limit in millicores; 1000 is one CPU.
      +
      +***
      +
      +### ephemeralStorageBytes
      +
      +```ts
      +ephemeralStorageBytes: number;
      +```
      +
      +Ephemeral storage limit in bytes.
      +
      +***
      +
      +### memoryBytes
      +
      +```ts
      +memoryBytes: number;
      +```
      +
      +Memory limit in bytes.
      diff --git a/docs/src/js/interfaces/FunctionRetryPolicy.md b/docs/src/js/interfaces/FunctionRetryPolicy.md
      new file mode 100644
      index 000000000..43d4ed8b2
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionRetryPolicy.md
      @@ -0,0 +1,91 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionRetryPolicy
      +
      +# Interface: FunctionRetryPolicy
      +
      +Overrides retries of failed user-code calls for one refresh. Omitted
      +fields use the Function refresh defaults.
      +
      +## Properties
      +
      +### errorCodes?
      +
      +```ts
      +optional errorCodes: string[];
      +```
      +
      +Structured provider error codes or HTTP status codes.
      +
      +***
      +
      +### exceptionTypes?
      +
      +```ts
      +optional exceptionTypes: string[];
      +```
      +
      +Exception class names, preferably qualified.
      +
      +***
      +
      +### honorRetryAfter?
      +
      +```ts
      +optional honorRetryAfter: boolean;
      +```
      +
      +Honor Retry-After within the configured maximum.
      +
      +***
      +
      +### initialBackoffSeconds?
      +
      +```ts
      +optional initialBackoffSeconds: number;
      +```
      +
      +Initial exponential-backoff ceiling, in seconds.
      +
      +***
      +
      +### maxAttempts?
      +
      +```ts
      +optional maxAttempts: number;
      +```
      +
      +Total calls, including the first; 1 disables retries, maximum 100.
      +
      +***
      +
      +### maxBackoffSeconds?
      +
      +```ts
      +optional maxBackoffSeconds: number;
      +```
      +
      +Maximum backoff, in seconds.
      +
      +***
      +
      +### messagePattern?
      +
      +```ts
      +optional messagePattern: string;
      +```
      +
      +Regular expression matched against the exception class and message.
      +
      +***
      +
      +### transient?
      +
      +```ts
      +optional transient: boolean;
      +```
      +
      +Match connection/timeouts, HTTP 429/503, SlowDown and
      +ServiceUnavailable.
      diff --git a/docs/src/js/interfaces/FunctionValueProvenance.md b/docs/src/js/interfaces/FunctionValueProvenance.md
      new file mode 100644
      index 000000000..56c0974c4
      --- /dev/null
      +++ b/docs/src/js/interfaces/FunctionValueProvenance.md
      @@ -0,0 +1,73 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionValueProvenance
      +
      +# Interface: FunctionValueProvenance
      +
      +The Function and job that produced one stored value.
      +
      +## Properties
      +
      +### column
      +
      +```ts
      +column: string;
      +```
      +
      +***
      +
      +### functionName
      +
      +```ts
      +functionName: string;
      +```
      +
      +***
      +
      +### functionVersion
      +
      +```ts
      +functionVersion: string;
      +```
      +
      +***
      +
      +### jobId
      +
      +```ts
      +jobId: string;
      +```
      +
      +***
      +
      +### publishedVersion
      +
      +```ts
      +publishedVersion: bigint;
      +```
      +
      +***
      +
      +### rowAddress?
      +
      +```ts
      +optional rowAddress: bigint;
      +```
      +
      +***
      +
      +### rowId?
      +
      +```ts
      +optional rowId: bigint;
      +```
      +
      +***
      +
      +### sourceVersion
      +
      +```ts
      +sourceVersion: bigint;
      +```
      diff --git a/docs/src/js/interfaces/JobEventsOptions.md b/docs/src/js/interfaces/JobEventsOptions.md
      index 24831f4f1..c03573ddf 100644
      --- a/docs/src/js/interfaces/JobEventsOptions.md
      +++ b/docs/src/js/interfaces/JobEventsOptions.md
      @@ -27,3 +27,13 @@ optional limit: number;
       ```
       
       Maximum event rows to return, up to the server maximum of 10,000.
      +
      +***
      +
      +### pageToken?
      +
      +```ts
      +optional pageToken: string;
      +```
      +
      +Opaque continuation from the preceding page's schema metadata.
      diff --git a/docs/src/js/interfaces/JobFailureInfo.md b/docs/src/js/interfaces/JobFailureInfo.md
      index 5683ee5f0..cdea222c5 100644
      --- a/docs/src/js/interfaces/JobFailureInfo.md
      +++ b/docs/src/js/interfaces/JobFailureInfo.md
      @@ -31,3 +31,23 @@ optional phase: string;
       ```ts
       optional retryable: boolean;
       ```
      +
      +***
      +
      +### sqlJobId?
      +
      +```ts
      +optional sqlJobId: string;
      +```
      +
      +Isolated SQL job that raised this failure, when supplied by the server.
      +
      +***
      +
      +### traceback?
      +
      +```ts
      +optional traceback: string;
      +```
      +
      +User-code traceback, possibly truncated by the server.
      diff --git a/docs/src/js/interfaces/JobInfo.md b/docs/src/js/interfaces/JobInfo.md
      index 5de1d5e55..510fd7f28 100644
      --- a/docs/src/js/interfaces/JobInfo.md
      +++ b/docs/src/js/interfaces/JobInfo.md
      @@ -10,6 +10,26 @@ A row from `Connection.listJobs`: one server-side job.
       
       ## Properties
       
      +### columns
      +
      +```ts
      +columns: string[];
      +```
      +
      +Affected columns; empty when unavailable or not column-scoped.
      +
      +***
      +
      +### completedAtMillis?
      +
      +```ts
      +optional completedAtMillis: number;
      +```
      +
      +Terminal timestamp in milliseconds since the epoch, when known.
      +
      +***
      +
       ### createdAtMillis
       
       ```ts
      @@ -20,6 +40,46 @@ When the job was created, in milliseconds since the epoch.
       
       ***
       
      +### durationMillis?
      +
      +```ts
      +optional durationMillis: number;
      +```
      +
      +Creation-to-completion wall time, including queueing and pauses.
      +
      +***
      +
      +### failure?
      +
      +```ts
      +optional failure: JobFailureInfo;
      +```
      +
      +Durable failure summary, when available.
      +
      +***
      +
      +### functionName?
      +
      +```ts
      +optional functionName: string;
      +```
      +
      +Pinned Function catalog name, with namespace segments joined by `$`.
      +
      +***
      +
      +### functionVersion?
      +
      +```ts
      +optional functionVersion: string;
      +```
      +
      +Pinned Function version, when known.
      +
      +***
      +
       ### jobId
       
       ```ts
      diff --git a/docs/src/js/interfaces/JobProgress.md b/docs/src/js/interfaces/JobProgress.md
      index dde202794..6c9bc5466 100644
      --- a/docs/src/js/interfaces/JobProgress.md
      +++ b/docs/src/js/interfaces/JobProgress.md
      @@ -17,6 +17,14 @@ different counters. A missing counter is unknown; it is not zero.
       
       ## Properties
       
      +### bytes\_read?
      +
      +```ts
      +optional bytes_read: null | number;
      +```
      +
      +***
      +
       ### estimated\_remaining\_time\_millis?
       
       ```ts
      @@ -37,6 +45,72 @@ Execution identity and sample time used for client-side ETA derivation.
       
       ***
       
      +### executors\_active?
      +
      +```ts
      +optional executors_active: null | number;
      +```
      +
      +***
      +
      +### executors\_completed?
      +
      +```ts
      +optional executors_completed: null | number;
      +```
      +
      +***
      +
      +### executors\_failed?
      +
      +```ts
      +optional executors_failed: null | number;
      +```
      +
      +***
      +
      +### executors\_partial?
      +
      +```ts
      +optional executors_partial: null | number;
      +```
      +
      +***
      +
      +### executors\_targeted?
      +
      +```ts
      +optional executors_targeted: null | number;
      +```
      +
      +***
      +
      +### fragments\_selected?
      +
      +```ts
      +optional fragments_selected: null | number;
      +```
      +
      +***
      +
      +### groups\_completed?
      +
      +```ts
      +optional groups_completed: null | number;
      +```
      +
      +***
      +
      +### groups\_planned?
      +
      +```ts
      +optional groups_planned: null | number;
      +```
      +
      +Maintenance work observations; rewritten rows are not committed rows.
      +
      +***
      +
       ### paused?
       
       ```ts
      @@ -57,6 +131,22 @@ Coarse server-derived phase, including phases from newer servers.
       
       ***
       
      +### ranges\_completed?
      +
      +```ts
      +optional ranges_completed: null | number;
      +```
      +
      +***
      +
      +### ranges\_planned?
      +
      +```ts
      +optional ranges_planned: null | number;
      +```
      +
      +***
      +
       ### rows\_computed?
       
       ```ts
      @@ -92,6 +182,14 @@ optional rows_remaining: null | number;
       
       ***
       
      +### rows\_rewritten?
      +
      +```ts
      +optional rows_rewritten: null | number;
      +```
      +
      +***
      +
       ### rows\_skipped?
       
       ```ts
      diff --git a/docs/src/js/interfaces/JobWaitOptions.md b/docs/src/js/interfaces/JobWaitOptions.md
      new file mode 100644
      index 000000000..38f1795f5
      --- /dev/null
      +++ b/docs/src/js/interfaces/JobWaitOptions.md
      @@ -0,0 +1,31 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / JobWaitOptions
      +
      +# Interface: JobWaitOptions
      +
      +Client-side controls for waiting without cancelling the underlying job.
      +
      +## Properties
      +
      +### onProgress?
      +
      +```ts
      +optional onProgress: JobProgressCallback;
      +```
      +
      +Observe progress using the same poller that waits for completion.
      +
      +***
      +
      +### timeoutMs?
      +
      +```ts
      +optional timeoutMs: number;
      +```
      +
      +Maximum wait in milliseconds, including status requests and polling backoff.
      +Must be a nonnegative safe integer. Omit to wait indefinitely; zero allows
      +only an immediately ready result.
      diff --git a/docs/src/js/interfaces/OptimizeOptions.md b/docs/src/js/interfaces/OptimizeOptions.md
      index 110eb3813..faf1d2724 100644
      --- a/docs/src/js/interfaces/OptimizeOptions.md
      +++ b/docs/src/js/interfaces/OptimizeOptions.md
      @@ -33,6 +33,28 @@ tbl.optimize({cleanupOlderThan: new Date()});
       
       ***
       
      +### compactionOptions?
      +
      +```ts
      +optional compactionOptions: CompactionOptions;
      +```
      +
      +Compaction settings for this invocation. Omitted remote values inherit table
      +tuning, then deployment/built-in defaults.
      +Remote tables require a server supporting these SQL options; settings do
      +not change table policy. This is not a runtime or total-memory limit.
      +
      +#### Example
      +
      +```ts
      +await tbl.optimize({ compactionOptions: {
      +  targetRowsPerFragment: 1000, maxSourceRows: 5000,
      +  ioBufferSize: 64 * 1024 * 1024, batchSize: 128,
      +} });
      +```
      +
      +***
      +
       ### deleteUnverified
       
       ```ts
      diff --git a/docs/src/js/interfaces/PrewarmDataOptions.md b/docs/src/js/interfaces/PrewarmDataOptions.md
      new file mode 100644
      index 000000000..fae916320
      --- /dev/null
      +++ b/docs/src/js/interfaces/PrewarmDataOptions.md
      @@ -0,0 +1,49 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / PrewarmDataOptions
      +
      +# Interface: PrewarmDataOptions
      +
      +Settings for data-cache prewarm submissions and metadata previews.
      +
      +## Properties
      +
      +### columns?
      +
      +```ts
      +optional columns: string[];
      +```
      +
      +Lance field paths to warm; omitted or empty means every column.
      +
      +***
      +
      +### concurrency?
      +
      +```ts
      +optional concurrency: number;
      +```
      +
      +Positive per-executor concurrency, at most 4294967295.
      +
      +***
      +
      +### filter?
      +
      +```ts
      +optional filter: string;
      +```
      +
      +A single SQL predicate for conservative metadata pruning.
      +
      +***
      +
      +### parameters?
      +
      +```ts
      +optional parameters: QueryParameters;
      +```
      +
      +Typed positional or named filter values, sent separately from SQL.
      diff --git a/docs/src/js/interfaces/PrewarmDataPlan.md b/docs/src/js/interfaces/PrewarmDataPlan.md
      new file mode 100644
      index 000000000..c06a2ac0a
      --- /dev/null
      +++ b/docs/src/js/interfaces/PrewarmDataPlan.md
      @@ -0,0 +1,37 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / PrewarmDataPlan
      +
      +# Interface: PrewarmDataPlan
      +
      +Metadata-only snapshot preview; no warming job is submitted.
      +
      +## Properties
      +
      +### plan
      +
      +```ts
      +plan: string;
      +```
      +
      +Readable display text. Use pruning for structured facts.
      +
      +***
      +
      +### pruning
      +
      +```ts
      +pruning: PrewarmPruningSummary;
      +```
      +
      +***
      +
      +### tableVersion
      +
      +```ts
      +tableVersion: number;
      +```
      +
      +Snapshot used for this preview. A later submission plans its own snapshot.
      diff --git a/docs/src/js/interfaces/PrewarmDataResult.md b/docs/src/js/interfaces/PrewarmDataResult.md
      new file mode 100644
      index 000000000..ce43b927c
      --- /dev/null
      +++ b/docs/src/js/interfaces/PrewarmDataResult.md
      @@ -0,0 +1,79 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / PrewarmDataResult
      +
      +# Interface: PrewarmDataResult
      +
      +Reported executor work for a pinned snapshot; unavailable measurements stay null.
      +
      +## Properties
      +
      +### bytesRead
      +
      +```ts
      +bytesRead: null | number;
      +```
      +
      +Reported bytes read, or null when unavailable.
      +
      +***
      +
      +### executorsCompleted
      +
      +```ts
      +executorsCompleted: null | number;
      +```
      +
      +Executors that finished successfully or partially, or null when unavailable.
      +
      +***
      +
      +### executorsPartial
      +
      +```ts
      +executorsPartial: null | number;
      +```
      +
      +Subset of completed executors reporting partial warming, or null when unavailable.
      +
      +***
      +
      +### executorsTargeted
      +
      +```ts
      +executorsTargeted: null | number;
      +```
      +
      +Reported executors targeted, or null when unavailable.
      +
      +***
      +
      +### fragmentsSelected
      +
      +```ts
      +fragmentsSelected: null | number;
      +```
      +
      +Reported fragments selected, or null when unavailable.
      +
      +***
      +
      +### rangesCompleted
      +
      +```ts
      +rangesCompleted: null | number;
      +```
      +
      +Reported ranges completed, or null when unavailable.
      +
      +***
      +
      +### tableVersion
      +
      +```ts
      +tableVersion: number;
      +```
      +
      +The source snapshot captured by submission.
      diff --git a/docs/src/js/interfaces/PrewarmPruningSummary.md b/docs/src/js/interfaces/PrewarmPruningSummary.md
      new file mode 100644
      index 000000000..78d1ba00a
      --- /dev/null
      +++ b/docs/src/js/interfaces/PrewarmPruningSummary.md
      @@ -0,0 +1,61 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / PrewarmPruningSummary
      +
      +# Interface: PrewarmPruningSummary
      +
      +Conservative metadata proof, rather than exact matching rows.
      +
      +## Properties
      +
      +### fallbackReason
      +
      +```ts
      +fallbackReason: null | string;
      +```
      +
      +***
      +
      +### inputFragments
      +
      +```ts
      +inputFragments: number;
      +```
      +
      +***
      +
      +### mode
      +
      +```ts
      +mode: string;
      +```
      +
      +Server-reported proof mode; future servers may add modes.
      +
      +***
      +
      +### prunedFragments
      +
      +```ts
      +prunedFragments: number;
      +```
      +
      +***
      +
      +### selectedFragments
      +
      +```ts
      +selectedFragments: number;
      +```
      +
      +***
      +
      +### selectedRowRanges
      +
      +```ts
      +selectedRowRanges: null | number;
      +```
      +
      +Candidate physical intervals, or null when unknown.
      diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md
      index f18ada7aa..cd36343b8 100644
      --- a/docs/src/js/interfaces/QueryExecutionOptions.md
      +++ b/docs/src/js/interfaces/QueryExecutionOptions.md
      @@ -29,8 +29,10 @@ Selecting a parent struct or directly aliasing a blob or struct also returns
       bytes. Blobs inside lists keep their descriptors. Arbitrary projection
       expressions are not materialized as bytes.
       
      -The rows and the bytes come from the same table version. If the table
      -changes while the query runs, the query runs again, up to three times.
      +The rows and bytes come from the same snapshot. Remote queries require
      +authoritative query version and snapshot identity headers, verified again
      +by the blob response. Older servers can still return `"descriptions"`.
      +Local queries retry up to three times if the table changes while they run.
       
       #### Example
       
      @@ -64,3 +66,6 @@ optional timeoutMs: number;
       ```
       
       Timeout for query execution in milliseconds
      +
      +The timeout also covers reading the results, so consuming them slowly can
      +exceed it.
      diff --git a/docs/src/js/interfaces/RTreeOptions.md b/docs/src/js/interfaces/RTreeOptions.md
      new file mode 100644
      index 000000000..ad0a8d1ce
      --- /dev/null
      +++ b/docs/src/js/interfaces/RTreeOptions.md
      @@ -0,0 +1,21 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / RTreeOptions
      +
      +# Interface: RTreeOptions
      +
      +Options to create an `RTREE` index
      +
      +## Properties
      +
      +### pageSize?
      +
      +```ts
      +optional pageSize: number;
      +```
      +
      +The maximum number of entries in each R-tree page.
      +
      +Must be at least 2. The default is 4096.
      diff --git a/docs/src/js/interfaces/RefreshColumnJobResult.md b/docs/src/js/interfaces/RefreshColumnJobResult.md
      new file mode 100644
      index 000000000..1d5f7fe87
      --- /dev/null
      +++ b/docs/src/js/interfaces/RefreshColumnJobResult.md
      @@ -0,0 +1,79 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / RefreshColumnJobResult
      +
      +# Interface: RefreshColumnJobResult
      +
      +The terminal outcome of a Function retry or upgrade job.
      +
      +## Properties
      +
      +### errorGroups
      +
      +```ts
      +errorGroups: FunctionErrorGroup[];
      +```
      +
      +Grouped causes reported by the completed job.
      +
      +***
      +
      +### errorGroupsTruncated
      +
      +```ts
      +errorGroupsTruncated: boolean;
      +```
      +
      +Whether the reported cause counts omit any failures.
      +
      +***
      +
      +### publishedVersion?
      +
      +```ts
      +optional publishedVersion: bigint;
      +```
      +
      +The table version made visible by the job, if it published one.
      +
      +***
      +
      +### rowsAssigned
      +
      +```ts
      +rowsAssigned: bigint;
      +```
      +
      +Logical rows successfully assigned a value.
      +
      +***
      +
      +### rowsFailed
      +
      +```ts
      +rowsFailed: bigint;
      +```
      +
      +Logical rows whose computation failed.
      +
      +***
      +
      +### rowsRemaining
      +
      +```ts
      +rowsRemaining: bigint;
      +```
      +
      +Logical rows still needing a value, excluding rows counted in `rowsFailed`.
      +
      +***
      +
      +### sourceVersion
      +
      +```ts
      +sourceVersion: bigint;
      +```
      +
      +The exact table version read by the job.
      diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md
      new file mode 100644
      index 000000000..3c22ada7f
      --- /dev/null
      +++ b/docs/src/js/interfaces/RefreshColumnOptions.md
      @@ -0,0 +1,208 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / RefreshColumnOptions
      +
      +# Interface: RefreshColumnOptions
      +
      +Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every
      +option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores
      +`batchSize`, `gpuClass` and `totalGpuCount` and rejects the rest.
      +
      +## Properties
      +
      +### batchSize?
      +
      +```ts
      +optional batchSize: number;
      +```
      +
      +Maximum rows per Function call; must be greater than zero.
      +
      +***
      +
      +### errorPolicy?
      +
      +```ts
      +optional errorPolicy: string;
      +```
      +
      +`"fail"` stops on a row error; `"skip"` records it and continues,
      +subject to the failure limits. The default is server-dependent.
      +
      +***
      +
      +### gpuClass?
      +
      +```ts
      +optional gpuClass: string;
      +```
      +
      +GPU class for Function workers.
      +
      +***
      +
      +### gpuCount?
      +
      +```ts
      +optional gpuCount: number;
      +```
      +
      +Positive GPU count allocated to each Function worker.
      +
      +***
      +
      +### initTimeoutSeconds?
      +
      +```ts
      +optional initTimeoutSeconds: number;
      +```
      +
      +Deadline for Function initialization, in seconds.
      +
      +***
      +
      +### maxConcurrency?
      +
      +```ts
      +optional maxConcurrency: number;
      +```
      +
      +Override the registered Function's maximum concurrent user-code calls
      +for this logical execution.
      +
      +***
      +
      +### maxExecutorProcessesPerWorker?
      +
      +```ts
      +optional maxExecutorProcessesPerWorker: number;
      +```
      +
      +Cap on executor processes per Function worker.
      +
      +***
      +
      +### maxFailedFraction?
      +
      +```ts
      +optional maxFailedFraction: number;
      +```
      +
      +Under a skip policy, fail the job once more than this share of rows
      +(0 to 1) has failed.
      +
      +***
      +
      +### maxFailedRows?
      +
      +```ts
      +optional maxFailedRows: number;
      +```
      +
      +Under a skip policy, fail the job once more than this many rows have
      +failed.
      +
      +***
      +
      +### numWorkers?
      +
      +```ts
      +optional numWorkers: number;
      +```
      +
      +Worker count for an expression column; Function columns reject it.
      +
      +***
      +
      +### planningWorkers?
      +
      +```ts
      +optional planningWorkers: FunctionRefreshPlanningConfig;
      +```
      +
      +Resources and sizing for the refresh planning fleet.
      +
      +***
      +
      +### publicationIntervalRows?
      +
      +```ts
      +optional publicationIntervalRows: number;
      +```
      +
      +Row-count threshold for publishing completed Function split ranges.
      +Must be a positive safe integer. Omit for whole-fragment publication.
      +Actual publications can be larger; remaining rows publish at completion.
      +Requires LanceDB Enterprise with non-Blob Function outputs.
      +
      +***
      +
      +### retryPolicy?
      +
      +```ts
      +optional retryPolicy: FunctionRetryPolicy;
      +```
      +
      +Override retries of failed user-code calls for this refresh.
      +
      +***
      +
      +### rowTimeoutSeconds?
      +
      +```ts
      +optional rowTimeoutSeconds: number;
      +```
      +
      +Deadline for one Function call, in seconds.
      +
      +***
      +
      +### supervisorResources?
      +
      +```ts
      +optional supervisorResources: FunctionRefreshPodResources;
      +```
      +
      +CPU, memory, and ephemeral-storage limits for the refresh supervisor.
      +
      +***
      +
      +### totalCpuMillis?
      +
      +```ts
      +optional totalCpuMillis: number;
      +```
      +
      +Override the total CPU budget in millicores for this refresh.
      +
      +***
      +
      +### totalGpuCount?
      +
      +```ts
      +optional totalGpuCount: number;
      +```
      +
      +Nonnegative total GPU budget for Function workers.
      +
      +***
      +
      +### totalMemoryBytes?
      +
      +```ts
      +optional totalMemoryBytes: number;
      +```
      +
      +Override the total memory budget in bytes for this refresh.
      +
      +***
      +
      +### where?
      +
      +```ts
      +optional where: string;
      +```
      +
      +Only refresh the rows matching this SQL filter.
      diff --git a/docs/src/js/interfaces/RetryFailedOptions.md b/docs/src/js/interfaces/RetryFailedOptions.md
      new file mode 100644
      index 000000000..d13534cb3
      --- /dev/null
      +++ b/docs/src/js/interfaces/RetryFailedOptions.md
      @@ -0,0 +1,312 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / RetryFailedOptions
      +
      +# Interface: RetryFailedOptions
      +
      +Options for retrying exactly the current failures of one Function column.
      +
      +## Extends
      +
      +- `Omit`<[`RefreshColumnOptions`](RefreshColumnOptions.md), `"where"`>
      +
      +## Properties
      +
      +### batchSize?
      +
      +```ts
      +optional batchSize: number;
      +```
      +
      +Maximum rows per Function call; must be greater than zero.
      +
      +#### Inherited from
      +
      +`Omit.batchSize`
      +
      +***
      +
      +### errorPolicy?
      +
      +```ts
      +optional errorPolicy: string;
      +```
      +
      +`"fail"` stops on a row error; `"skip"` records it and continues,
      +subject to the failure limits. The default is server-dependent.
      +
      +#### Inherited from
      +
      +`Omit.errorPolicy`
      +
      +***
      +
      +### errorType?
      +
      +```ts
      +optional errorType: string;
      +```
      +
      +Only retry failures with this exception class.
      +
      +***
      +
      +### functionVersion?
      +
      +```ts
      +optional functionVersion: string;
      +```
      +
      +Upgrade to this immutable Function version while retrying failures.
      +
      +***
      +
      +### gpuClass?
      +
      +```ts
      +optional gpuClass: string;
      +```
      +
      +GPU class for Function workers.
      +
      +#### Inherited from
      +
      +`Omit.gpuClass`
      +
      +***
      +
      +### gpuCount?
      +
      +```ts
      +optional gpuCount: number;
      +```
      +
      +Positive GPU count allocated to each Function worker.
      +
      +#### Inherited from
      +
      +`Omit.gpuCount`
      +
      +***
      +
      +### includeQuarantined?
      +
      +```ts
      +optional includeQuarantined: boolean;
      +```
      +
      +Explicitly release and retry matching quarantined failures.
      +
      +***
      +
      +### initTimeoutSeconds?
      +
      +```ts
      +optional initTimeoutSeconds: number;
      +```
      +
      +Deadline for Function initialization, in seconds.
      +
      +#### Inherited from
      +
      +`Omit.initTimeoutSeconds`
      +
      +***
      +
      +### jobId?
      +
      +```ts
      +optional jobId: string;
      +```
      +
      +Only retry current failures recorded by this job.
      +
      +***
      +
      +### maxConcurrency?
      +
      +```ts
      +optional maxConcurrency: number;
      +```
      +
      +Override the registered Function's maximum concurrent user-code calls
      +for this logical execution.
      +
      +#### Inherited from
      +
      +`Omit.maxConcurrency`
      +
      +***
      +
      +### maxExecutorProcessesPerWorker?
      +
      +```ts
      +optional maxExecutorProcessesPerWorker: number;
      +```
      +
      +Cap on executor processes per Function worker.
      +
      +#### Inherited from
      +
      +`Omit.maxExecutorProcessesPerWorker`
      +
      +***
      +
      +### maxFailedFraction?
      +
      +```ts
      +optional maxFailedFraction: number;
      +```
      +
      +Under a skip policy, fail the job once more than this share of rows
      +(0 to 1) has failed.
      +
      +#### Inherited from
      +
      +`Omit.maxFailedFraction`
      +
      +***
      +
      +### maxFailedRows?
      +
      +```ts
      +optional maxFailedRows: number;
      +```
      +
      +Under a skip policy, fail the job once more than this many rows have
      +failed.
      +
      +#### Inherited from
      +
      +`Omit.maxFailedRows`
      +
      +***
      +
      +### numWorkers?
      +
      +```ts
      +optional numWorkers: number;
      +```
      +
      +Worker count for an expression column; Function columns reject it.
      +
      +#### Inherited from
      +
      +`Omit.numWorkers`
      +
      +***
      +
      +### planningWorkers?
      +
      +```ts
      +optional planningWorkers: FunctionRefreshPlanningConfig;
      +```
      +
      +Resources and sizing for the refresh planning fleet.
      +
      +#### Inherited from
      +
      +`Omit.planningWorkers`
      +
      +***
      +
      +### publicationIntervalRows?
      +
      +```ts
      +optional publicationIntervalRows: number;
      +```
      +
      +Row-count threshold for publishing completed Function split ranges.
      +Must be a positive safe integer. Omit for whole-fragment publication.
      +Actual publications can be larger; remaining rows publish at completion.
      +Requires LanceDB Enterprise with non-Blob Function outputs.
      +
      +#### Inherited from
      +
      +`Omit.publicationIntervalRows`
      +
      +***
      +
      +### retryPolicy?
      +
      +```ts
      +optional retryPolicy: FunctionRetryPolicy;
      +```
      +
      +Override retries of failed user-code calls for this refresh.
      +
      +#### Inherited from
      +
      +`Omit.retryPolicy`
      +
      +***
      +
      +### rowTimeoutSeconds?
      +
      +```ts
      +optional rowTimeoutSeconds: number;
      +```
      +
      +Deadline for one Function call, in seconds.
      +
      +#### Inherited from
      +
      +`Omit.rowTimeoutSeconds`
      +
      +***
      +
      +### supervisorResources?
      +
      +```ts
      +optional supervisorResources: FunctionRefreshPodResources;
      +```
      +
      +CPU, memory, and ephemeral-storage limits for the refresh supervisor.
      +
      +#### Inherited from
      +
      +`Omit.supervisorResources`
      +
      +***
      +
      +### totalCpuMillis?
      +
      +```ts
      +optional totalCpuMillis: number;
      +```
      +
      +Override the total CPU budget in millicores for this refresh.
      +
      +#### Inherited from
      +
      +`Omit.totalCpuMillis`
      +
      +***
      +
      +### totalGpuCount?
      +
      +```ts
      +optional totalGpuCount: number;
      +```
      +
      +Nonnegative total GPU budget for Function workers.
      +
      +#### Inherited from
      +
      +`Omit.totalGpuCount`
      +
      +***
      +
      +### totalMemoryBytes?
      +
      +```ts
      +optional totalMemoryBytes: number;
      +```
      +
      +Override the total memory budget in bytes for this refresh.
      +
      +#### Inherited from
      +
      +`Omit.totalMemoryBytes`
      diff --git a/docs/src/js/interfaces/TableDeltaReader.md b/docs/src/js/interfaces/TableDeltaReader.md
      new file mode 100644
      index 000000000..f05d56a37
      --- /dev/null
      +++ b/docs/src/js/interfaces/TableDeltaReader.md
      @@ -0,0 +1,109 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / TableDeltaReader
      +
      +# Interface: TableDeltaReader
      +
      +A streaming table-delta reader.
      +
      +`schema()` is available before consuming the stream, including when the
      +range is empty. The stream yields Arrow record batches without
      +materializing the full result.
      +
      +A reader owns one native cursor. It is single-use:
      +`[Symbol.asyncIterator]()` returns the same iterator, concurrent pulls are
      +serialized, and `return()` releases the native stream on early drop.
      +
      +## Extends
      +
      +- `AsyncIterable`<`RecordBatch`>.`AsyncIterator`<`RecordBatch`>
      +
      +## Methods
      +
      +### \[asyncIterator\]()
      +
      +```ts
      +asyncIterator: AsyncIterator, any, undefined>
      +```
      +
      +#### Returns
      +
      +`AsyncIterator`<`RecordBatch`<`any`>, `any`, `undefined`>
      +
      +#### Inherited from
      +
      +`AsyncIterable.[asyncIterator]`
      +
      +***
      +
      +### next()
      +
      +```ts
      +next(...args): Promise, any>>
      +```
      +
      +#### Parameters
      +
      +* ...**args**: [] \| [`undefined`]
      +
      +#### Returns
      +
      +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>>
      +
      +#### Inherited from
      +
      +`AsyncIterator.next`
      +
      +***
      +
      +### return()?
      +
      +```ts
      +optional return(value?): Promise, any>>
      +```
      +
      +#### Parameters
      +
      +* **value?**: `any`
      +
      +#### Returns
      +
      +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>>
      +
      +#### Inherited from
      +
      +`AsyncIterator.return`
      +
      +***
      +
      +### schema()
      +
      +```ts
      +schema(): Promise>
      +```
      +
      +#### Returns
      +
      +`Promise`<`Schema`<`any`>>
      +
      +***
      +
      +### throw()?
      +
      +```ts
      +optional throw(e?): Promise, any>>
      +```
      +
      +#### Parameters
      +
      +* **e?**: `any`
      +
      +#### Returns
      +
      +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>>
      +
      +#### Inherited from
      +
      +`AsyncIterator.throw`
      diff --git a/docs/src/js/interfaces/TableDeltaTransaction.md b/docs/src/js/interfaces/TableDeltaTransaction.md
      new file mode 100644
      index 000000000..1c2bda71d
      --- /dev/null
      +++ b/docs/src/js/interfaces/TableDeltaTransaction.md
      @@ -0,0 +1,51 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / TableDeltaTransaction
      +
      +# Interface: TableDeltaTransaction
      +
      +A committed transaction in a table delta range.
      +
      +## Properties
      +
      +### operation
      +
      +```ts
      +operation: string;
      +```
      +
      +***
      +
      +### readVersion
      +
      +```ts
      +readVersion: bigint;
      +```
      +
      +The version the transaction was based on. Exact u64 value.
      +
      +***
      +
      +### tag?
      +
      +```ts
      +optional tag: string;
      +```
      +
      +***
      +
      +### transactionProperties?
      +
      +```ts
      +optional transactionProperties: Record;
      +```
      +
      +***
      +
      +### uuid
      +
      +```ts
      +uuid: string;
      +```
      diff --git a/docs/src/js/interfaces/UpgradeColumnOptions.md b/docs/src/js/interfaces/UpgradeColumnOptions.md
      new file mode 100644
      index 000000000..9f937b116
      --- /dev/null
      +++ b/docs/src/js/interfaces/UpgradeColumnOptions.md
      @@ -0,0 +1,292 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / UpgradeColumnOptions
      +
      +# Interface: UpgradeColumnOptions
      +
      +Options for assigning a new immutable Function version to a column.
      +
      +## Extends
      +
      +- `Omit`<[`RefreshColumnOptions`](RefreshColumnOptions.md), `"where"`>
      +
      +## Properties
      +
      +### batchSize?
      +
      +```ts
      +optional batchSize: number;
      +```
      +
      +Maximum rows per Function call; must be greater than zero.
      +
      +#### Inherited from
      +
      +`Omit.batchSize`
      +
      +***
      +
      +### errorPolicy?
      +
      +```ts
      +optional errorPolicy: string;
      +```
      +
      +`"fail"` stops on a row error; `"skip"` records it and continues,
      +subject to the failure limits. The default is server-dependent.
      +
      +#### Inherited from
      +
      +`Omit.errorPolicy`
      +
      +***
      +
      +### gpuClass?
      +
      +```ts
      +optional gpuClass: string;
      +```
      +
      +GPU class for Function workers.
      +
      +#### Inherited from
      +
      +`Omit.gpuClass`
      +
      +***
      +
      +### gpuCount?
      +
      +```ts
      +optional gpuCount: number;
      +```
      +
      +Positive GPU count allocated to each Function worker.
      +
      +#### Inherited from
      +
      +`Omit.gpuCount`
      +
      +***
      +
      +### initTimeoutSeconds?
      +
      +```ts
      +optional initTimeoutSeconds: number;
      +```
      +
      +Deadline for Function initialization, in seconds.
      +
      +#### Inherited from
      +
      +`Omit.initTimeoutSeconds`
      +
      +***
      +
      +### maxConcurrency?
      +
      +```ts
      +optional maxConcurrency: number;
      +```
      +
      +Override the registered Function's maximum concurrent user-code calls
      +for this logical execution.
      +
      +#### Inherited from
      +
      +`Omit.maxConcurrency`
      +
      +***
      +
      +### maxExecutorProcessesPerWorker?
      +
      +```ts
      +optional maxExecutorProcessesPerWorker: number;
      +```
      +
      +Cap on executor processes per Function worker.
      +
      +#### Inherited from
      +
      +`Omit.maxExecutorProcessesPerWorker`
      +
      +***
      +
      +### maxFailedFraction?
      +
      +```ts
      +optional maxFailedFraction: number;
      +```
      +
      +Under a skip policy, fail the job once more than this share of rows
      +(0 to 1) has failed.
      +
      +#### Inherited from
      +
      +`Omit.maxFailedFraction`
      +
      +***
      +
      +### maxFailedRows?
      +
      +```ts
      +optional maxFailedRows: number;
      +```
      +
      +Under a skip policy, fail the job once more than this many rows have
      +failed.
      +
      +#### Inherited from
      +
      +`Omit.maxFailedRows`
      +
      +***
      +
      +### numWorkers?
      +
      +```ts
      +optional numWorkers: number;
      +```
      +
      +Worker count for an expression column; Function columns reject it.
      +
      +#### Inherited from
      +
      +`Omit.numWorkers`
      +
      +***
      +
      +### planningWorkers?
      +
      +```ts
      +optional planningWorkers: FunctionRefreshPlanningConfig;
      +```
      +
      +Resources and sizing for the refresh planning fleet.
      +
      +#### Inherited from
      +
      +`Omit.planningWorkers`
      +
      +***
      +
      +### publicationIntervalRows?
      +
      +```ts
      +optional publicationIntervalRows: number;
      +```
      +
      +Row-count threshold for publishing completed Function split ranges.
      +Must be a positive safe integer. Omit for whole-fragment publication.
      +Actual publications can be larger; remaining rows publish at completion.
      +Requires LanceDB Enterprise with non-Blob Function outputs.
      +
      +#### Inherited from
      +
      +`Omit.publicationIntervalRows`
      +
      +***
      +
      +### recompute?
      +
      +```ts
      +optional recompute: FunctionRecompute;
      +```
      +
      +Defaults to `"all"`. Quarantined failures are excluded.
      +
      +***
      +
      +### retryPolicy?
      +
      +```ts
      +optional retryPolicy: FunctionRetryPolicy;
      +```
      +
      +Override retries of failed user-code calls for this refresh.
      +
      +#### Inherited from
      +
      +`Omit.retryPolicy`
      +
      +***
      +
      +### rowTimeoutSeconds?
      +
      +```ts
      +optional rowTimeoutSeconds: number;
      +```
      +
      +Deadline for one Function call, in seconds.
      +
      +#### Inherited from
      +
      +`Omit.rowTimeoutSeconds`
      +
      +***
      +
      +### supervisorResources?
      +
      +```ts
      +optional supervisorResources: FunctionRefreshPodResources;
      +```
      +
      +CPU, memory, and ephemeral-storage limits for the refresh supervisor.
      +
      +#### Inherited from
      +
      +`Omit.supervisorResources`
      +
      +***
      +
      +### totalCpuMillis?
      +
      +```ts
      +optional totalCpuMillis: number;
      +```
      +
      +Override the total CPU budget in millicores for this refresh.
      +
      +#### Inherited from
      +
      +`Omit.totalCpuMillis`
      +
      +***
      +
      +### totalGpuCount?
      +
      +```ts
      +optional totalGpuCount: number;
      +```
      +
      +Nonnegative total GPU budget for Function workers.
      +
      +#### Inherited from
      +
      +`Omit.totalGpuCount`
      +
      +***
      +
      +### totalMemoryBytes?
      +
      +```ts
      +optional totalMemoryBytes: number;
      +```
      +
      +Override the total memory budget in bytes for this refresh.
      +
      +#### Inherited from
      +
      +`Omit.totalMemoryBytes`
      +
      +***
      +
      +### version
      +
      +```ts
      +version: string;
      +```
      +
      +An existing immutable version of the bound Function.
      diff --git a/docs/src/js/interfaces/WriteExecutionOptions.md b/docs/src/js/interfaces/WriteExecutionOptions.md
      index 0ca796b6b..9c9be4489 100644
      --- a/docs/src/js/interfaces/WriteExecutionOptions.md
      +++ b/docs/src/js/interfaces/WriteExecutionOptions.md
      @@ -8,6 +8,26 @@
       
       ## Properties
       
      +### retries?
      +
      +```ts
      +optional retries: number;
      +```
      +
      +Override the remote retry budget for this execution only (an integer from
      +0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after
      +precommit conflicts (409) or rate limits (429). This does not change
      +connection-wide/read budgets or local transaction conflict retries.
      +
      +By default, remote calls use the connection's `clientConfig.retryConfig`
      +([RetryConfig](RetryConfig.md)). Its `statuses` (also set through
      +`LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget;
      +it never permits replay of ambiguous merge outcomes. In particular, 502,
      +ordinary 503, and 504 are never replayed, even if configured. Reconcile table
      +contents before manually repeating a merge whose commit outcome is unknown.
      +
      +***
      +
       ### timeoutMs?
       
       ```ts
      @@ -24,3 +44,6 @@ the second attempt will be cancelled after 10 seconds, hitting the
       first attempt will not be cancelled.
       
       When this is set, the timeout is enforced on all attempts, including the first.
      +For remote tables this is sent as a server execution timeout. It does not
      +extend HTTP read or proxy idle timeouts, or prove that a failed request did
      +not commit.
      diff --git a/docs/src/js/type-aliases/BlobRangeRequest.md b/docs/src/js/type-aliases/BlobRangeRequest.md
      new file mode 100644
      index 000000000..daa231260
      --- /dev/null
      +++ b/docs/src/js/type-aliases/BlobRangeRequest.md
      @@ -0,0 +1,39 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / BlobRangeRequest
      +
      +# Type Alias: BlobRangeRequest
      +
      +```ts
      +type BlobRangeRequest: object;
      +```
      +
      +One row-specific range for [Table.fetchBlobRanges](../classes/Table.md#fetchblobranges).
      +
      +## Type declaration
      +
      +### length
      +
      +```ts
      +length: bigint;
      +```
      +
      +Number of bytes to read, as a uint64. Zero returns an empty non-null value.
      +
      +### offset
      +
      +```ts
      +offset: bigint;
      +```
      +
      +Byte offset from the beginning of the logical blob, as a uint64.
      +
      +### rowId
      +
      +```ts
      +rowId: bigint | number;
      +```
      +
      +A row ID from a query with row IDs enabled.
      diff --git a/docs/src/js/type-aliases/DeltaVersion.md b/docs/src/js/type-aliases/DeltaVersion.md
      new file mode 100644
      index 000000000..263b5614c
      --- /dev/null
      +++ b/docs/src/js/type-aliases/DeltaVersion.md
      @@ -0,0 +1,17 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / DeltaVersion
      +
      +# Type Alias: DeltaVersion
      +
      +```ts
      +type DeltaVersion: number | bigint | string;
      +```
      +
      +One endpoint of a table delta: a positive version number/bigint or a tag on
      +the table handle's current branch.
      +
      +Use a `bigint` when the version may exceed `Number.MAX_SAFE_INTEGER`.
      +Strings are always tags.
      diff --git a/docs/src/js/type-aliases/FunctionProfileKind.md b/docs/src/js/type-aliases/FunctionProfileKind.md
      new file mode 100644
      index 000000000..e7fe3bf59
      --- /dev/null
      +++ b/docs/src/js/type-aliases/FunctionProfileKind.md
      @@ -0,0 +1,13 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionProfileKind
      +
      +# Type Alias: FunctionProfileKind
      +
      +```ts
      +type FunctionProfileKind: "cpu" | "gpu" | "memory";
      +```
      +
      +Evidence collected from one Function worker's Python execution session.
      diff --git a/docs/src/js/type-aliases/FunctionProfileStatus.md b/docs/src/js/type-aliases/FunctionProfileStatus.md
      new file mode 100644
      index 000000000..5a1304aa5
      --- /dev/null
      +++ b/docs/src/js/type-aliases/FunctionProfileStatus.md
      @@ -0,0 +1,13 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionProfileStatus
      +
      +# Type Alias: FunctionProfileStatus
      +
      +```ts
      +type FunctionProfileStatus: "pending" | "capturing" | "complete" | "failed";
      +```
      +
      +A capture's lifecycle, independent of its parent refresh job.
      diff --git a/docs/src/js/type-aliases/FunctionRecompute.md b/docs/src/js/type-aliases/FunctionRecompute.md
      new file mode 100644
      index 000000000..1957ad801
      --- /dev/null
      +++ b/docs/src/js/type-aliases/FunctionRecompute.md
      @@ -0,0 +1,15 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / FunctionRecompute
      +
      +# Type Alias: FunctionRecompute
      +
      +```ts
      +type FunctionRecompute: "failed" | "all" | "none";
      +```
      +
      +Which existing values to recompute during a Function version upgrade.
      +`"failed"` selects current failures. `"all"` refreshes every eligible live
      +row. `"none"` preserves existing values and only changes the binding.
      diff --git a/docs/src/js/type-aliases/JobState.md b/docs/src/js/type-aliases/JobState.md
      new file mode 100644
      index 000000000..dfc70b5f3
      --- /dev/null
      +++ b/docs/src/js/type-aliases/JobState.md
      @@ -0,0 +1,21 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / JobState
      +
      +# Type Alias: JobState
      +
      +```ts
      +type JobState:
      +  | "created"
      +  | "queued"
      +  | "in_progress"
      +  | "succeeded"
      +  | "failed"
      +  | "canceled"
      +  | "timed_out"
      +  | string & object;
      +```
      +
      +Detailed lifecycle state. Unrecognized future values remain strings.
      diff --git a/docs/src/js/type-aliases/QueryParameterValue.md b/docs/src/js/type-aliases/QueryParameterValue.md
      new file mode 100644
      index 000000000..a8f275052
      --- /dev/null
      +++ b/docs/src/js/type-aliases/QueryParameterValue.md
      @@ -0,0 +1,20 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / QueryParameterValue
      +
      +# Type Alias: QueryParameterValue
      +
      +```ts
      +type QueryParameterValue:
      +  | string
      +  | number
      +  | bigint
      +  | boolean
      +  | Date
      +  | Uint8Array
      +  | null;
      +```
      +
      +Scalar SQL values. Use a one-row Arrow table for explicit Arrow types.
      diff --git a/docs/src/js/type-aliases/QueryParameters.md b/docs/src/js/type-aliases/QueryParameters.md
      new file mode 100644
      index 000000000..dfce3ed30
      --- /dev/null
      +++ b/docs/src/js/type-aliases/QueryParameters.md
      @@ -0,0 +1,16 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / QueryParameters
      +
      +# Type Alias: QueryParameters
      +
      +```ts
      +type QueryParameters: readonly QueryParameterValue[] | Readonly> | TableLike | RecordBatchLike;
      +```
      +
      +Values for `$1`/`$name` placeholders, sent separately from SQL text.
      +Arrays bind by position; objects bind by name. Arrow columns bind both ways.
      +Safe integers and bigint use Int64; fractional numbers use Float64.
      +Arrow input preserves explicit types.
      diff --git a/docs/src/python/python.md b/docs/src/python/python.md
      index efb57605b..39e599184 100644
      --- a/docs/src/python/python.md
      +++ b/docs/src/python/python.md
      @@ -37,11 +37,43 @@ embedding_functions`. Prefer keyword arguments for optional parameters.
       
       ::: lancedb.db.DBConnection
       
      +Embedded connections support `location=` on `open_table` to open a table from an
      +explicit dataset URI instead of the derived `/.lance` path:
      +
      +```python
      +db = lancedb.connect("./data")
      +table = db.open_table("events", location="./datasets/events.lance")
      +```
      +
      +Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection)
      +to include the responding server's release, Git revision, build date and Function
      +runtime information in a bug report. It returns a JSON-compatible dictionary and
      +does not submit a query or job. Configured images are distinct from the version
      +of an already running job. During a rolling upgrade, successive requests can
      +reach different query-node builds. Embedded connections and older servers without
      +the endpoint raise `NotImplementedError`.
      +
      +::: lancedb.server_info.ServerBuildInfo
      +
      +::: lancedb.server_info.ServerInfo
      +
       Resource listings return iterators. Use `list(db.list_tables())` to collect all
       table names. `db.list_tables().tables` is a list of the first page; `limit`
       controls its page size and `page_token` resumes at a saved token. The same
       patterns apply to `list_namespaces()`. Other resource listings use `page_limit`.
       
      +For existence checks, use `db.table_exists(["events"])` or `"events" in db`.
      +These look up the table directly and work even when the database has more than
      +100 tables. For a table in a namespace, include the namespace segments:
      +
      +```python
      +exists = db.table_exists(["analytics", "events"])
      +```
      +
      +When migrating from `name in db.table_names()`, use `name in db` or
      +`db.table_exists([name])`. Checking `name in db.list_tables().tables` only
      +searches the first page and can miss an existing table.
      +
       Resource listings (`list_storage_integrations`, `list_secrets`, `list_views`, `list_jobs`, `list_functions`, and
       `list_materialized_views`) return lazy iterators. Use `list(db.list_views())` to
       collect synchronous results, or `[name async for name in db.list_views()]` with
      @@ -274,7 +306,8 @@ call or return a polling continuation that the SDK follows automatically.
       This behavior is the same with and without parameters. Open the reader directly;
       a directly streamed query needs its reader to make progress. Dropping an unread
       handle or its reader stops direct streaming. Deferred execution continues until
      -explicitly cancelled.
      +explicitly cancelled by default; use `cancel_on_drop=True` to attempt cancellation
      +when its unread handle or reader is dropped.
       
       For example:
       
      @@ -328,6 +361,26 @@ reader = db.execute_query(
       # await query.cancel()
       ```
       
      +Set `timeout` to bound submission and result consumption together, including
      +any time before opening a reader. Set `read_timeout` to limit each server read.
      +Both accept `datetime.timedelta` and apply to one execution. An expired timeout
      +or failed result read stops reading and attempts to cancel Flight execution.
      +Cancellation on drop requires the submitting runtime to remain alive. Durable
      +server-side jobs require explicit `db.cancel_job(query.job_id)`.
      +
      +```python
      +from datetime import timedelta
      +
      +query = db.execute_query_async(
      +    "SELECT * FROM events",
      +    timeout=timedelta(seconds=30),
      +    read_timeout=timedelta(seconds=5),
      +    cancel_on_drop=True,
      +)
      +# To stop this execution explicitly:
      +query.cancel()
      +```
      +
       ## Namespaces (Synchronous)
       
       A namespace-backed connection resolves tables through a
      @@ -352,9 +405,27 @@ accept the LanceDB Embedded options: cleanup and compaction warn that they are n
       `optimize` submits a durable compaction job and returns once that submission is
       accepted, not once compaction itself finishes. Pruning and index optimization
       are not yet supported remotely, so it silently skips them and returns with
      -zeroed pruning statistics rather than attempting and failing. A non-default
      -`compaction_options` raises `NotImplementedError` before anything is
      -submitted, since there is no way yet to forward those settings to the server.
      +zeroed pruning statistics. Remote `compaction_options` support per-job
      +`target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and `batch_size`
      +on compatible servers. Other non-default settings raise `NotImplementedError`
      +before submission; older-server errors are returned without dropping options.
      +The source-row budget selects whole tasks and can produce no work if the first
      +task exceeds it. An I/O buffer size of zero disables byte-based I/O backpressure.
      +Use a positive size to limit I/O read-ahead; this is not a total-memory limit.
      +Each field resolves as invocation option → table tuning → deployment/built-in
      +default. These options apply only to the submitted job and leave table policy
      +unchanged. Table `enabled` controls automatic scheduling; explicit manual runs
      +remain allowed.
      +
      +```python
      +table.optimize(compaction_options={
      +    "target_rows_per_fragment": 100_000,
      +    "max_source_rows": 1_000_000,
      +    "io_buffer_size": 64 * 1024 * 1024,
      +    "batch_size": 1024,
      +})
      +```
      +
       Removed Tantivy options produce the same explanatory errors on both backends.
       
       The old LanceDB Enterprise keyword names `predicate` for `delete`, `index_name` for
      @@ -378,28 +449,98 @@ code that used the former LanceDB Enterprise-only argument order.
       
       ::: lancedb.table.Branches
       
      +::: lancedb.table.TableDelta
      +
       ::: lancedb.RTEWriteSpec
       
       ## Functions and Jobs
       
      -A decorated `udf` definition is also a local callable. Call a decorated function
      +Use `progress=True` when waiting for Function registration in a notebook or
      +terminal. A callback receives structured snapshots instead:
      +
      +```python
      +fn = db.create_function(my_function, progress=True)
      +registration = db.create_function_async(other_function)
      +fn = registration.wait(progress=lambda snapshot: print(snapshot))
      +print(fn.image.describe())
      +```
      +
      +Registration uses the existing SQL query handle. The current handle reports
      +lifecycle state and `client_elapsed_time_millis` since the handle was created;
      +detailed build phases and build logs are unavailable. Keep the same handle after
      +a wait timeout to resume waiting. Failures retain the server error and request
      +identifiers. `fn.image` has a concise representation; `describe()` exposes Python
      +and CUDA requirements without inspecting Pydantic internals. Platforms, base image
      +and size are `None` until the service reports them. The full image descriptor and
      +canonical JSON remain available.
      +Jobs retain an attempt identity through `job_id()`, and explicit server retries
      +report `operation_id()`, `attempt()`, and `retry_of()` when the server supports
      +them.
      +`lifecycle_state()` and `status_typed()` expose detailed `JobState` values while
      +the existing string `status()` remains available. Unknown future states retain
      +their value and never imply success. `source_table_version()` identifies the
      +attempt's pinned input snapshot when reported.
      +
      +```python
      +from datetime import timedelta
      +from lancedb import JobState
      +
      +job = db.open_job(job_id)
      +state = job.status_typed()
      +if state is JobState.SUCCEEDED:
      +    print(job.operation_id(), job.attempt(), job.source_table_version())
      +job.wait(timeout=timedelta(seconds=5))
      +for page in job.history(limit=1000):
      +    print(page)
      +```
      +
      +A wait timeout leaves execution running and the handle reusable. Cancellation
      +can be refused when publication has already acquired its commit claim; inspect
      +the job again to learn that attempt's outcome. LanceDB Embedded handles have a
      +stable identity for their lifetime and share typed lifecycle and wait semantics;
      +their IDs cannot be reopened after a process restart. Event history, durable
      +retries, and per-row Function errors require a backend that records them.
      +
      +Explicit retries name the exact failed attempt and preserve its resolved
      +Function version and source snapshot. Repeating `job.retry()` selects the same
      +successor; call `retry()` on that successor to request another attempt. Safely
      +retryable states and publication outcomes are validated by the backend.
      +
      +```python
      +retry = failed_job.retry()
      +retry.refresh()
      +attempt_job_id = retry.job_id()
      +token = ""
      +while token is not None:
      +    errors = table.function_errors(job_id=attempt_job_id, limit=1000, page_token=token)
      +    print(errors.records, errors.fragments)
      +    token = errors.page_token
      +```
      +
      +An empty error page can still carry a continuation. Keep the table, branch,
      +job, and column filters unchanged while paging. Diagnose a terminal attempt for
      +its complete retained row errors; an executing attempt is a partial observation.
      +
      +A `@function` definition is also a local callable. Call a decorated function
       directly with row inputs, or call a decorated class with its initialization fields
       and then call the returned instance; call `close()` if the class defines it. This
       path uses the current Python environment and does not create a registered
       `FunctionVersion`, build the declared remote runtime, resolve Secrets, or execute
       the remote Arrow adapter. A registered `FunctionVersion` call instead binds
      -`col(...)` inputs and returns a remote `FunctionApplication`.
      +`col(...)` inputs and returns a remote `FunctionApplication`. Passing an `Expr`
      +such as `col("value")` to a definition raises `TypeError` before the callable
      +runs; bind it on the registered `FunctionVersion` instead.
       
       ```python
      -from lancedb import udf
      +from lancedb import function
       
       
      -@udf
      +@function
       def normalize(text: str) -> str:
           return text.strip().lower()
       
       
      -@udf
      +@function
       class Scale:
           def __init__(self, factor: float):
               self.factor = factor
      @@ -417,6 +558,98 @@ assert scaler(3.0) == 6.0
       scaler.close()
       ```
       
      +### Function packaging restrictions
      +
      +The decorator snapshots the Function's source and referenced globals into a new
      +module. It supports three statically recognizable diagnostic operations:
      +`sys.stderr`, `sys.version_info`, and `importlib.metadata.version`. Direct
      +imports, `from` imports, and aliases are treated the same way, whether the
      +import appears inside a function or class body or at module level.
      +
      +Other imports of `sys`, `builtins`, `importlib`, `inspect`, `gc`, `ctypes`, and
      +`types`, including submodules such as `ctypes.util` and `importlib.resources`,
      +remain blocked. This applies to imports inside function or class bodies and
      +references to module-level aliases. Even ordinary uses such as `sys.version`
      +and `ctypes.util.find_library` are blocked: these modules can reach names
      +outside the reconstructed Function namespace. References to `globals`, `locals`,
      +`vars`, `eval`, `exec`, `compile`, and `__import__` are rejected as dynamic
      +namespace access. These restrictions also apply to the deprecated `@udf` alias.
      +
      +For example, a diagnostic Function can report its Python version and NumPy
      +version without a helper module:
      +
      +```python
      +import importlib.metadata
      +import sys
      +
      +from lancedb import function
      +
      +
      +@function(pip=["numpy"])
      +def report(value: int) -> str:
      +    print("diagnostic", file=sys.stderr)
      +    return f"numpy {importlib.metadata.version('numpy')} on {sys.version_info}"
      +```
      +
      +For other restricted uses, move the code into an importable helper module and
      +ship it with `code=`, or install its package with `pip=` or `conda=`. Imported
      +helpers keep their own namespace; the packager does not scan their bodies.
      +Helpers defined in `__main__` are copied by source and have the same
      +restrictions as the Function.
      +
      +For example, put this helper in `native_diagnostics/__init__.py`:
      +
      +```python
      +import ctypes.util
      +
      +
      +def find_library(name: str) -> str:
      +    return ctypes.util.find_library(name) or ""
      +```
      +
      +Then import the helper and include its source in the Function's artifact:
      +
      +```python
      +import native_diagnostics
      +from lancedb import function
      +
      +
      +@function(code=[native_diagnostics])
      +def probe_library(name: str) -> str:
      +    return native_diagnostics.find_library(name)
      +```
      +
      +Captured globals are copied into the Function's source. They can be `None`,
      +booleans, integers, strings, bytes, and finite floats; tuples, lists, dicts,
      +sets, and frozensets of supported values; PyArrow data types, fields, and
      +schemas; and NumPy arrays and scalars of bool, integer, `float16`, `float32`,
      +and `float64` dtypes. The copy is taken when the decorator runs and rebuilt in
      +each worker process, so later changes on either side are not shared. NumPy
      +values need `numpy` in the remote environment; declare it with `pip=` or
      +`conda=`. Each value is limited to 1 MiB of source and 32 levels of nesting;
      +load larger data inside the Function, for example from a table or a package
      +resource shipped with `code=`. Construct other objects inside the Function or
      +helper module instead. Values used only in the decorator's `input_schema` or
      +`output_schema` are not captured globals and can be defined outside the
      +Function.
      +
      +```python
      +import pyarrow as pa
      +from lancedb import function
      +
      +LABELS = {"pick": 0, "place": 1}
      +RESULT = pa.struct([pa.field("label", pa.string()), pa.field("id", pa.int32())])
      +
      +
      +@function(
      +    input_schema=pa.schema([pa.field("action", pa.string(), nullable=False)]),
      +    output_schema=pa.field("result", RESULT, nullable=False),
      +)
      +def label(action: pa.Array) -> pa.Array:
      +    rows = [{"label": name, "id": LABELS[name]} for name in action.to_pylist()]
      +    return pa.array(rows, type=RESULT)
      +```
      +
       Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or
       with `bytes` to materialize its contents before the Function runs. Reader
       inputs infer the Blob V2 type without an explicit input schema. Readers are
      @@ -443,6 +676,8 @@ with BlobReader(read_range, len(payload)) as reader:
       
       ::: lancedb.BlobReader
       
      +::: lancedb.functions.BlobWriter
      +
       ::: lancedb.functions.FunctionArtifact
       
       ::: lancedb.functions.FunctionParameter
      @@ -455,9 +690,13 @@ with BlobReader(read_range, len(payload)) as reader:
       
       ::: lancedb.functions.PythonEnvironmentSpec
       
      -::: lancedb.functions.udf
      +::: lancedb.functions.RequestedPythonEnvironment
       
      -::: lancedb.functions.UdfDefinition
      +::: lancedb.functions.PythonEnvironmentBuild
      +
      +::: lancedb.functions.function
      +
      +::: lancedb.functions.FunctionDefinition
       
       ::: lancedb.secrets.EnvVarSecret
       
      @@ -465,6 +704,8 @@ with BlobReader(read_range, len(payload)) as reader:
       
       ::: lancedb.functions.FunctionRegistrationRequest
       
      +::: lancedb.functions.FunctionRetryPolicy
      +
       ::: lancedb.functions.FunctionArtifactRequest
       
       ::: lancedb.functions.FunctionArtifactContent
      @@ -475,10 +716,20 @@ with BlobReader(read_range, len(payload)) as reader:
       
       ::: lancedb.functions.FunctionVersion
       
      +::: lancedb.functions.FunctionEnvironment
      +
      +::: lancedb.functions.ResolvedEnvironment
      +
      +::: lancedb.functions.ResolvedPackage
      +
      +::: lancedb.functions.ResolvedEnvironmentProvenance
      +
       ::: lancedb.functions.HuggingFaceModel
       
       ::: lancedb.functions.PythonRuntimeSpec
       
      +::: lancedb.functions.RequestedPythonRuntime
      +
       ::: lancedb.GpuClass
       
       ::: lancedb.functions.FunctionVersionRef
      @@ -489,6 +740,8 @@ with BlobReader(read_range, len(payload)) as reader:
       
       ::: lancedb.functions.InputBinding
       
      +::: lancedb.functions.LiteralInputBinding
      +
       ::: lancedb.functions.OutputMapping
       
       ::: lancedb.functions.AssignmentMapping
      @@ -497,14 +750,32 @@ with BlobReader(read_range, len(payload)) as reader:
       
       ::: lancedb.functions.RefreshColumnResult
       
      -::: lancedb.FunctionErrors
      +::: lancedb.functions.FunctionErrorGroup
      +
      +::: lancedb.functions.FunctionProvenance
      +
      +::: lancedb.functions.FunctionValueProvenance
      +
      +::: lancedb.functions.AsyncFunctionErrors
      +
      +::: lancedb.functions.FunctionErrors
       
       ::: lancedb.FunctionErrorRecord
       
       ::: lancedb.FunctionErrorFragment
       
      +::: lancedb.FunctionColumnStatus
      +
      +::: lancedb.FunctionColumnVersionStatus
      +
      +::: lancedb.FunctionColumnLastRefreshJob
      +
      +::: lancedb.FunctionColumnAutoRefreshStatus
      +
       ::: lancedb.job.Job
       
      +::: lancedb.job.JobState
      +
       ::: lancedb.job.AsyncJob
       
       ::: lancedb.job.JobInfo
      @@ -513,6 +784,12 @@ with BlobReader(read_range, len(payload)) as reader:
       
       ::: lancedb.job.JobFailureInfo
       
      +::: lancedb.profiling.FunctionProfile
      +
      +::: lancedb.profiling.FunctionProfileKind
      +
      +::: lancedb.profiling.FunctionProfileStatus
      +
       ::: lancedb.sql.Query
       
       ::: lancedb.sql.AsyncQuery
      @@ -530,6 +807,20 @@ remain available, as do LanceDB Enterprise operations. The same feature
       requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary
       eager `add_columns` transforms remain available.
       
      +Pass a complete defining SQL query with `query=` to use grouping, Functions
      +in `FROM`, or `UNNEST`:
      +
      +```python
      +view = db.create_materialized_view(
      +    "events_by_kind",
      +    query="SELECT kind, count(*) AS n FROM events GROUP BY kind",
      +)
      +```
      +
      +`query` is mutually exclusive with `source`, `select`, `where`, and `limit`.
      +It is also accepted by asynchronous connections and `create_materialized_view_async`.
      +The backend SQL parser determines which query shapes are supported.
      +
       In LanceDB Enterprise, creation accepts `auto_refresh_enabled` and
       `auto_refresh_interval_seconds`:
       
      @@ -598,6 +889,8 @@ of raw SQL strings with [where][lancedb.query.LanceQueryBuilder.where] and
       
       ::: lancedb.query.Query
       
      +::: lancedb.query.ColumnOrdering
      +
       ::: lancedb.query.LanceQueryBuilder
       
       ::: lancedb.query.LanceVectorQueryBuilder
      @@ -708,6 +1001,27 @@ with `search().with_row_id(True).to_arrow()` and pass the result to the fetch AP
       One missing or deleted row ID rejects the entire blob-read batch; the APIs do
       not return partial results.
       
      +Row positions are not row IDs. To read by position, call
      +`take_offsets(offsets, with_row_id=True)` first and pass the resulting `_rowid`
      +values; `fetch_blobs` remains row-ID based. A query result table that carries
      +snapshot metadata keeps the snapshot that produced it on LanceDB Enterprise, so
      +the fetched bytes or files stay pinned if the table changes. Metadata-free
      +inputs, including legacy query responses and plain row-ID lists, are read from
      +the table handle's current snapshot; keep the source unchanged between selection
      +and fetching. Partial snapshot metadata fails explicitly. For `fetch_blob_files`,
      +a snapshot-bound read also fails explicitly when the serving node cannot echo
      +the immutable identity. The basic remote Blob API floor (server 0.5.0) does not
      +by itself provide that echo capability.
      +
      +Local and remote `BlobFile` handles prefetch 512 KiB for sequential reads by
      +default. Pass `buffer_size=0` to `fetch_blob_files`, `open_blob_file`, or
      +`open_blob_files` for sparse reads, or choose another window size in bytes.
      +Call `file.set_buffer_size(size)` to change it without moving the cursor;
      +changing the size discards unused prefetched bytes. Explicit `read_range` and
      +`read_ranges` calls always read exactly the requested intervals and leave the
      +cursor unchanged. Remote prefetch consumes the HTTP response completely before
      +returning, so idle handles do not hold request concurrency slots or connections.
      +
       To construct inline Blob V2 arrays for ingestion in record batches, use
       [blob_array][lancedb.schema.blob_array]. It accepts bytes and `None`, preserving
       the distinction between an empty blob (`b""`) and a null blob:
      @@ -732,9 +1046,42 @@ PyArrow's `RecordBatch.from_pylist(..., schema=...)` cannot convert raw bytes
       into the blob extension type; use `blob_array` and `RecordBatch.from_arrays`
       when constructing batches explicitly.
       
      -For external blob references, construct the descriptor struct described by
      -[blob][lancedb.schema.blob], then wrap it with `pa.ExtensionArray.from_storage`.
      -Inline `data` and external `uri` representations are mutually exclusive.
      +For external blob references, use [blob_uri_array][lancedb.blob_uri_array]. It builds the
      +same extension type from URI strings and optional `(position, size)` byte
      +ranges without requiring pylance. Inline `data` and external `uri` representations
      +are mutually exclusive.
      +
      +Register the object prefix with [BasePath][lancedb.BasePath] on
      +`create_table(..., initial_bases=[...])` to store a matched absolute blob URI
      +relative to a base and to scope credentials with `base_.
      ```sql SQL icon="database" REFRESH COLUMN doubled ON my_table -REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' +REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' ``` -A refresh gives values to rows that lack them, recomputes rows whose inputs -changed, and **leaves other filled rows alone**. That makes it idempotent, cheap -to repeat as data arrives, and safe to re-run after a failure, though a re-run -can recompute values the failed run had already written. +Without `WHERE`, a refresh fills unassigned rows and recomputes values whose +inputs changed, leaving other current values alone. A retry after a failure +can still repeat work that was not committed. -`WHERE` scopes the refresh, which is how you fill a slice and check it before -committing to the whole table. +With `WHERE`, a refresh **recomputes every matching live row**, including rows +that already have current values. Repeating a predicate can repeat the Function +calls and their cost. To select only null outputs within a slice: + + +```sql SQL icon="database" +REFRESH COLUMN embedding ON documents + WHERE created_at > date '2026-01-01' AND embedding IS NULL +``` + + +This skips non-null outputs even if their inputs changed. It also selects +outputs that were successfully computed as `NULL`. Use an unfiltered refresh +to let LanceDB track which outputs need updating. ## Options {#options} | Option | Meaning | | --- | --- | -| `num_workers` | how many workers to use | -| `cpu_millis` | aggregate CPU ceiling across the refresh's workers, not a per-worker size | -| `memory_bytes` | aggregate memory ceiling across the refresh's workers | -| `gpu_count` | aggregate GPU budget across the refresh's workers. Function columns only | -| `gpu_class` | GPU class name for the refresh's workers. Function columns only | -| `batch_size` | rows passed to each Function call. Function columns only | +| `num_workers` | fixed worker count for SQL-expression columns; rejected for registered Function columns | +| `total_cpu_millis` | aggregate CPU ceiling across the refresh's Function workers, in thousandths of a CPU | +| `total_memory_bytes` | aggregate memory ceiling across the refresh's Function workers, in bytes | +| `total_gpu_count` | aggregate GPU budget across the refresh's workers. Function columns only | +| `gpu_class` | GPU class name for the refresh's workers; `any` accepts any eligible pool. Function columns only | +| `gpu_count` | positive number of GPUs allocated together to each worker. Function columns only | +| `batch_size` | maximum rows passed to one Function call; actual calls can be smaller. Function columns only | | `max_executor_processes_per_worker` | cap on executor processes per worker. Function columns only | | `row_timeout_seconds` | deadline for one Function call. Function columns only | -| `error_policy` | `'skip'` continues past failing rows instead of failing the job. Function columns only | +| `error_policy` | `'skip'` (default, with a 5% failed-row ceiling) retains a failing row's existing output, leaves unassigned outputs unassigned and records row errors, subject to failure limits; `'fail'` stops on a row error. Function columns only | | `max_failed_fraction` | fail the job once more than this share of rows has failed. Function columns only | | `max_failed_rows` | fail the job once more than this many rows has failed. Function columns only | ```sql SQL icon="database" REFRESH COLUMN embedding ON documents - WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2) + WITH (total_cpu_millis = 8000, total_memory_bytes = 17179869184, total_gpu_count = 2) ``` -`num_workers` sets a count; the budget options size the refresh's workers in -aggregate, not each one individually. They are alternatives rather than a -pair. +The example allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the +Function workers together. It does not reserve those resources per worker or +guarantee a worker count. Set each resource independently; omitted values inherit +column `total_*` settings, then Function defaults, then deployment defaults. +A CPU-only GPU budget uses `total_gpu_count = 0`. + +Set `error_policy` on the refresh, not on the Function definition. With `skip`, +inspect failures with `SHOW ERRORS` or `table.function_errors()` and retry the +affected rows after fixing the cause. Initialization, infrastructure, and +publication failures can still fail the job. `num_workers` is refused for a column filled by a registered diff --git a/docs/web/sql/dml/refresh-materialized-view.mdx b/docs/web/sql/dml/refresh-materialized-view.mdx index ecb4e84d1..ef662e01d 100644 --- a/docs/web/sql/dml/refresh-materialized-view.mdx +++ b/docs/web/sql/dml/refresh-materialized-view.mdx @@ -14,7 +14,8 @@ A LanceDB extension with no DataFusion equivalent. ```sql SQL icon="database" REFRESH MATERIALIZED VIEW - [WITH (full = )] + [WITH (full = , total_cpu_millis = , total_memory_bytes = , + total_gpu_count = , gpu_class = '')] ``` @@ -36,6 +37,39 @@ regardless of what a local SDK's `refresh()` method accepts -- do not assume the two option sets match. +## Resource budgets {#resources} + +Set budgets for one refresh execution: + +```sql +REFRESH MATERIALIZED VIEW curated_training_set WITH ( + total_cpu_millis = 8000, + total_memory_bytes = 17179869184, + total_gpu_count = 2, + gpu_class = 'h100' +); +``` + +`total_cpu_millis` is CPU capacity in millicores (1000 = one core), not CPU time. +`total_memory_bytes` caps memory in bytes. `total_gpu_count` caps concurrent GPUs for the +refresh. These are aggregate caps across its SQL execution and Function +processes; they are not multiplied by the number of Functions in the query. + +Each resource may be overridden independently. CPU and memory must be positive; +`total_gpu_count = 0` is allowed for CPU-only views. A GPU budget alone is also accepted. +A cap does not reserve all of its GPUs or increase refresh parallelism. Current +MV refreshes use at most one GPU, shared by their GPU Function calls. + +`gpu_class` selects an operator-configured class for this execution, leaving the +Function registration and saved MV placement unchanged. Use `SHOW GPU CLASSES` +to discover configured classes. Omitted budgets and class preserve defaults. +Options can be combined with `full = true`. + +This requires an Enterprise server and an isolated execution backend that can +enforce resource budgets. Unsupported backends reject constrained refreshes. +Older servers reject the new options. Saved defaults and automatic refresh +configuration are unchanged. + ## Watching a refresh {#watching} A refresh submits work that outlives the call. Track it with diff --git a/docs/web/sql/dql/blob-descriptor.mdx b/docs/web/sql/dql/blob-descriptor.mdx index 5021f2d20..49b4fe391 100644 --- a/docs/web/sql/dql/blob-descriptor.mdx +++ b/docs/web/sql/dql/blob-descriptor.mdx @@ -15,10 +15,10 @@ SELECT id, blob_descriptor(video) AS descriptor FROM videos ``` -A [BlobV2](/management/table#managed-blobs) column's bytes are not fetched by -a plain `SELECT`: that already returns `large_binary`, the same as any other -binary column. `blob_descriptor` instead returns a small struct describing -where the payload lives, without reading it. Pass one row's descriptor to +A plain `SELECT` of a [BlobV2](/management/table#managed-blobs) column returns +its payload as `large_binary`. `blob_descriptor` instead returns a small +struct describing where the payload lives, without reading the payload. +Pass one row's descriptor to the SDK's blob file reader to open that payload directly: @@ -27,6 +27,33 @@ rows = db.execute_query("SELECT id, blob_descriptor(video) AS descriptor FROM vi with table.open_blob_file(rows[0]["descriptor"]) as reader: payload = reader.read() ``` + +```typescript TypeScript icon="typescript" +const rows = await table + .query() + .select({ descriptor: "blob_descriptor(video)" }) + .toArray(); +const reader = await table.openBlobFile(rows[0].descriptor); +if (reader) { + const payload = await reader.read(); + await reader.close(); +} +``` + +```rust Rust icon="rust" +use lancedb::{blob::BlobDescriptor, Table}; + +async fn read_descriptor( + table: &Table, + descriptor: &BlobDescriptor, +) -> lancedb::Result<()> { + let reader = table.open_blob_file(descriptor).await?; + let payload = reader.read().await?; + println!("{} bytes", payload.len()); + reader.close().await?; + Ok(()) +} +``` A descriptor is pinned to the table version it was read at: it keeps diff --git a/docs/web/sql/dql/dedupe.mdx b/docs/web/sql/dql/dedupe.mdx index dbb6717b4..452638ea3 100644 --- a/docs/web/sql/dql/dedupe.mdx +++ b/docs/web/sql/dql/dedupe.mdx @@ -55,6 +55,15 @@ current deployments. a subset of partitions and `id_column` are pair-query-only options, accepted by [`duplicate_pairs`](/sql/dql/duplicate-pairs#input) but refused here. +## Index and snapshot requirements {#requirements} + +Use one compatible, current vector index covering the source snapshot. +Full scans reject unindexed fragments. Comparisons stay within physical IVF +partitions and index segments; this does not enumerate cross-partition or +cross-segment duplicates. Quantized-index distances use encoded vector +representations. See [recall and scale limits](/curation/dedupe#limits) before +treating the result as globally exact deduplication. + ## Output {#output} One row per duplicate group, **in the table's own schema** -- every column of diff --git a/docs/web/sql/dql/duplicate-pairs.mdx b/docs/web/sql/dql/duplicate-pairs.mdx index daa078955..dc93d5180 100644 --- a/docs/web/sql/dql/duplicate-pairs.mdx +++ b/docs/web/sql/dql/duplicate-pairs.mdx @@ -60,6 +60,12 @@ only [`dedupe`](/sql/dql/dedupe#input) accepts it. ## Output {#output} +See [`dedupe` index prerequisites](/sql/dql/dedupe#requirements) and the +[recall limits](/curation/dedupe#limits). Pairs are found within each physical +partition and index segment, not across them. A full scan requires complete +index coverage; sampling is a diagnostic view of the selected indexed +partitions and does not prove coverage or recall for the rest of the table. + One row per close pair found, in a fixed schema independent of the source table: diff --git a/docs/web/sql/dql/fts.mdx b/docs/web/sql/dql/fts.mdx index 7b52f5e17..667d92cd6 100644 --- a/docs/web/sql/dql/fts.mdx +++ b/docs/web/sql/dql/fts.mdx @@ -30,14 +30,16 @@ INSERT INTO my_docs VALUES (3, 'The puppy catches a ball with great enthusiasm', 'sports', 'Alice'), (5, 'Puppy training requires patience and dedication', 'training', 'Alice'); -CREATE INDEX ON my_docs USING fts (text); +CREATE INDEX ON my_docs USING fts (text) WITH (with_position = true); ``` Phrase queries need position information, which costs extra index size. -Add `WITH (with_position = true)` to `CREATE INDEX`. Without it, -[phrase queries](#phrase) find nothing. See +The setup above enables it with `WITH (with_position = true)`. An existing +index without positions must be rebuilt before running a phrase query; the +server rejects the query and asks you to recreate the index with positions. +It does not silently return no matches. See [FTS parameters](/indexing/fts-index#fts-parameters). @@ -86,6 +88,44 @@ LIMIT 5 it behaves like any other column, but exists only in a relation that came from `fts()`. See [Data types](/sql/data-types#pseudo-columns). +## Match any term or every term {#term-operators} + +The default match operator is OR. `"happy puppy"` matches either analyzed +term. SQL JSON uses `"Or"` and `"And"`, with this casing; Python uses the +`FullTextOperator.OR` and `FullTextOperator.AND` enum members: + +```python +from lancedb.query import FullTextOperator, MatchQuery + +query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND) +json_query = query.to_json() +``` + +```sql +SELECT id, text, _score +FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}') +ORDER BY _score DESC +``` + +Both terms must occur, but they need not be adjacent. Do not embed `AND` or +`OR` in `terms` to select an operator. + +## Count matches {#count} + +Count the `fts()` relation before applying a top-k limit: + +```sql +SELECT COUNT(*) AS matching_rows +FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}') +``` + +This is an Enterprise SQL workaround when the SDK's FTS query builder does +not expose a match-count operation. `table.count_rows()` without an FTS +relation counts table rows, and taking the length of a limited search counts +only that result page. For list-element indexes, multiple matching elements +can produce multiple rows; use `COUNT(DISTINCT id)` when you need unique +application records. + ## Fuzzy {#fuzzy} Tolerates typos, up to a character-edit budget: @@ -109,6 +149,12 @@ PhraseQuery("puppy park", "text", slop=2) # up to 2 words between them ``` +```sql +SELECT id, text, _score +FROM fts('my_docs', '{"phrase":{"column":"text","terms":"happy puppy","slop":0}}') +ORDER BY _score DESC +``` + ## Boolean {#boolean} Combine queries with `&` (AND) or `|` (OR): @@ -120,6 +166,17 @@ MatchQuery("puppy", "text") | MatchQuery("kitten", "text") ``` +For SQL, serialize the composed query rather than writing occurrence enums +by hand: + +```python +query = MatchQuery("puppy", "text") & MatchQuery("happy", "text") +json_query = query.to_json() +``` + +Use that string as the second `fts()` argument. `.to_json()` supplies the +serialized Boolean field names for the SDK version you use. + ## Boost {#boost} Weight a query up or down relative to another: diff --git a/docs/web/sql/dql/functions.mdx b/docs/web/sql/dql/functions.mdx index 945abbe03..0ea53a508 100644 --- a/docs/web/sql/dql/functions.mdx +++ b/docs/web/sql/dql/functions.mdx @@ -15,7 +15,7 @@ plus what Lance adds. | | | | --- | --- | -| [Scalar functions](/sql/dql/scalar-functions) | per row: math, string, regex, date/time, array, struct, JSON | +| [Scalar functions](/sql/dql/scalar-functions) | per row: math, string, regex, date/time, array, struct{/* Draft until JSON columns reach early access: restore ", JSON" */} | | [Aggregate functions](/sql/dql/aggregation#functions) | per group: `count`, `sum`, statistical, approximate | | [Window functions](/sql/dql/window#functions) | per window: ranking, offset, running aggregates | | [Table functions](#table-functions) | produce a relation rather than a value | @@ -45,13 +45,17 @@ see [Data types](/sql/data-types#pseudo-columns). ## What Lance accelerates {#accelerated} -Two function families use an index rather than scanning, which is the difference +`contains_tokens` uses an index rather than scanning, which is the difference between a fast predicate and a slow one: | | Index used | | --- | --- | | [`contains_tokens`](/sql/dql/contains-tokens) | full-text index | + +{/* +Draft until JSON columns reach early access; restore "Two function families" above. | [`json_get`, typed variants, `json_extract`](/sql/dql/json-functions) | JSON scalar index | +*/} Confirm with [`EXPLAIN`](/sql/dql/explain): an accelerated predicate shows an index node rather than a `LanceScan` followed by a filter. diff --git a/docs/web/sql/dql/sampling.mdx b/docs/web/sql/dql/sampling.mdx index b6b24f8eb..c84caccc1 100644 --- a/docs/web/sql/dql/sampling.mdx +++ b/docs/web/sql/dql/sampling.mdx @@ -22,6 +22,9 @@ SELECT * FROM documents TABLESAMPLE (500 ROWS) -- 500 rows A bare number is a **percentage**. Add `ROWS` for a count instead. +To sample rows independently from every partition of an IVF vector index, +use [`TABLESAMPLE IVF`](/curation/semantic-sampling). + ## Rows or fragments {#methods} The standard calls these two methods of one clause. They are different diff --git a/docs/web/sql/dql/scalar-functions.mdx b/docs/web/sql/dql/scalar-functions.mdx index b0910c01a..9bd2057b0 100644 --- a/docs/web/sql/dql/scalar-functions.mdx +++ b/docs/web/sql/dql/scalar-functions.mdx @@ -3,7 +3,7 @@ title: "Scalar functions" sidebarTitle: "Scalar Functions" description: "The per-row function set: math, string, regex, date/time, array, struct, and what Lance adds." icon: calculator -keywords: ["scalar functions", "string functions", "math functions", "regex", "array functions", "json"] +keywords: ["scalar functions", "string functions", "math functions", "regex", "array functions"] availability: embedded: unavailable enterprise: available @@ -133,7 +133,14 @@ reference page: | [`contains_tokens`](/sql/dql/contains-tokens) | index-accelerated keyword predicate, usable in `WHERE` | | [`ivf_partition`](/sql/dql/ivf-partition) | assign each row to its trained IVF index partition | | [`blob_descriptor`](/sql/dql/blob-descriptor) | a BlobV2 column's payload location, without reading it | + +{/* +Draft until JSON columns reach early access. | [JSON accessors](/sql/dql/json-functions) | `json_get` and its typed variants, `json_extract`, and more | +*/} + +{/* +Draft: geospatial queries and indexes are unsupported in LanceDB Enterprise. ### Geospatial {#geo} @@ -143,6 +150,7 @@ Lance defines `st_*` functions on GeoArrow, but they sit behind a build feature feature rather than an unknown-function error, and the spatial index is gated the same way. +*/} ## Additional scalar functions {#escape-hatch} diff --git a/docs/web/sql/pagination.mdx b/docs/web/sql/pagination.mdx new file mode 100644 index 000000000..d14a364fc --- /dev/null +++ b/docs/web/sql/pagination.mdx @@ -0,0 +1,69 @@ +--- +title: "Catalog listing pagination" +description: "Use one continuation-token syntax for SQL catalog listings." +icon: list-ol +--- + +Catalog `SHOW` statements share one pagination suffix: + +```sql +SHOW [IN ] [LIMIT [FROM '']]; +``` + +This applies to tables, views, materialized views, functions and function +history, secrets, storage integrations, namespaces/schemas, and databases. + +```sql +SHOW TABLES LIMIT 100; +SHOW TABLES IN team$ml LIMIT 100; +SHOW TABLES IN team$ml LIMIT 100 FROM ''; +SHOW TABLES IN analytics.team$ml LIMIT 100; +SHOW DATABASES LIMIT 100 FROM ''; +``` + +## Namespace scope + +`IN` is optional. Without it, listings include root and every authorized +namespace in the current database, regardless of the session's default namespace. +With `IN`, objects are listed only in that exact namespace. The scope accepts a +schema directly: `IN team$ml` means the absolute namespace path `["team", "ml"]` +in the current database. Use `IN public` for root, or `IN other_db.team$ml` to +select a different database. Quote schema identifiers containing punctuation or +mixed case, for example `IN "Team$ML"`. + +`SHOW SCHEMAS` and `SHOW NAMESPACES` use the same rules: without `IN` they +include all namespace paths and the public root; with `IN` they list the +selected parent's immediate children. `SHOW DATABASES` remains global and +does not accept `IN`. + +SDK APIs that take a namespace send an explicit `IN` clause and continue to +list that one namespace. + +## Continuation metadata + +The Arrow result schema carries `lancedb.next_page_token` when more results +remain. Pass that opaque value unchanged in `FROM` on the next request. +The token identifies the object type, database, namespace scope, and complete +position, including namespace path and any numeric revision. It cannot be +reused with another object type or scope. + +The token is metadata, not an additional result column or a synthetic row. +Namespace-scoped object listings contain `namespace_path` and `name`; +databases contain only `name`. Function history retains revision metadata. +SDK listing APIs expose this server-issued value as the page's `page_token`. + +Continue until no token is returned. A short or empty page may still have a +token. Pages observe the live catalog; continuation does not create a snapshot. + +## Page size and ordering + +The default page limit is 1,000, with a maximum of 10,000. `LIMIT 0` returns +no rows. Object catalogs order identifiers by namespace path components and +unqualified name; database names are ordered by name. Table page boundaries +follow native catalog order, which may differ from logical name order for +directory-backed tables; table names are sorted within each returned page. Function history uses +numeric revision order within each name. The token preserves that complete +position, including when names repeat in different namespaces. + +The old name-comparison `WHERE` and Function `WITH` pagination forms are no +longer supported. Use the same `LIMIT ... FROM ...` suffix for every listing. diff --git a/docs/web/tables/branching.mdx b/docs/web/tables/branching.mdx index baf46b265..9edd7c669 100644 --- a/docs/web/tables/branching.mdx +++ b/docs/web/tables/branching.mdx @@ -127,8 +127,12 @@ small `quotes` table with three rows on `main`. ### Create a branch {#create-a-branch} Forking from `main` returns a table handle scoped to the new branch. `main` is -the reserved default source, so `create` needs only a name; to fork from -somewhere else, pass a branch name, a specific version, or both. +the reserved default source, so `create` needs only a name. To fork from another +branch, pass `from_ref`, optionally with `from_version`. In Python, use +keyword-only `from_tag` to fork from a tag; it cannot be combined with +`from_ref` or `from_version`. In Rust, pass `Ref::Tag` to `create_branch`. A +tag carries its own branch and version, so the tag source forks from that exact +snapshot. diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx index f058cc836..09e933894 100644 --- a/docs/web/tables/realtime-engine.mdx +++ b/docs/web/tables/realtime-engine.mdx @@ -1,21 +1,21 @@ --- -title: "Real Time engine (RTE)" -sidebarTitle: "Real Time Engine (RTE)" +title: "Realtime Engine (RTE)" +sidebarTitle: "Realtime Engine (RTE)" description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] +keywords: ["rte", "realtime engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] availability: embedded: available enterprise: available --- -## What is the real time engine? {#what-is-rte} +## What is the Realtime Engine? {#what-is-rte} Every write to a LanceDB table is normally a commit to the underlying Lance dataset. That is ideal for bulk loads, but a stream of small upserts becomes a stream of small commits, and each write is only visible once its commit lands. -The real time engine (RTE) puts an LSM-style write tier in front of the table. +The Realtime Engine (RTE) puts an LSM-style write tier in front of the table. It turns many small writes into a few large commits, and makes each write **searchable within milliseconds** of being acknowledged. It is enabled per table, and nothing about how you query that table changes. @@ -25,7 +25,7 @@ table, and nothing about how you query that table changes. RTE is built on **MemWAL**, a log-structured-merge (LSM) format that Lance itself defines -- the structure Enterprise serves is part of the open Lance format, not a layer bolted on beside it. A table with RTE enabled is divided -into one or more **shards** (see [Real Time writes](/ingestion/realtime-write#primary-key) +into one or more **shards** (see [RTE writes](/ingestion/realtime-write#primary-key) for enabling and sizing them), and each shard holds: - A **memtable**: the active, in-memory table for that shard's newest rows, @@ -49,8 +49,8 @@ later folds SSTables into the base table, catching its indexes up as it goes. This section describes LanceDB Enterprise's serving layer. LanceDB Embedded runs the same MemWAL mechanics directly against the local dataset, in one process -- there is no separate node to route to or scale; see -[Real Time writes](/ingestion/realtime-write#getting-started) and -[Real Time reads](/search/realtime-read#embedded) for what that looks like. +[RTE writes](/ingestion/realtime-write#getting-started) and +[RTE reads](/search/realtime-read#embedded) for what that looks like. RTE's Enterprise serving layer is a dedicated component, separate from the [query nodes and plan executors](/enterprise/distributed-search) @@ -81,13 +81,13 @@ pods are never both appending to the same shard's WAL at once. Every query runs against the base table and the fresh tier -- every shard's memtable and not-yet-compacted SSTables -- in parallel. Fresh rows supersede base rows with the same primary key, and the two are merged into one result. -See [Real Time reads](/search/realtime-read) for what this means for query +See [RTE reads](/search/realtime-read) for what this means for query results. ## Next steps {#next-steps} -- [Real Time writes](/ingestion/realtime-write) — enable RTE and write to a table -- [Real Time reads](/search/realtime-read) — query an RTE table -- [Distributed Real Time Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales writes -- [Distributed Real Time Read](/enterprise/distributed-real-time-read) — how Enterprise combines reads across machines +- [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table +- [RTE reads](/search/realtime-read) — query an RTE table +- [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales writes +- [Distributed RTE Read](/enterprise/distributed-real-time-read) — how Enterprise combines reads across machines - [RTE Compaction](/enterprise/realtime-engine-compaction) — how Enterprise folds shards into the base table diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx index 2d5104322..23000d88c 100644 --- a/docs/web/tools/cli.mdx +++ b/docs/web/tools/cli.mdx @@ -1,7 +1,7 @@ --- title: "LanceDB CLI" sidebarTitle: "CLI" -description: "Connect to LanceDB, run SQL, and manage connection profiles with the lancedb command-line client." +description: "Install the LanceDB CLI, connect to a deployment, run SQL, and manage connection profiles." icon: terminal keywords: ["cli", "command line", "sql", "profiles", "authentication"] --- @@ -10,11 +10,48 @@ Use the `lancedb` command-line client to open an interactive SQL shell, run a statement, or execute a SQL file. SQL requires a running deployment with an [Arrow Flight SQL endpoint](/basics/sql#sql-is-remote). +This public client exposes `auth`, `profile`, and `sql`. Commands such as +`lancedb admin ...` and `lancedb job ...` require the Enterprise administrative +CLI from your deployment administrator; the public client archive and source +installation below do not include them. Use `lancedb sql --command` for SQL +statements supported by your deployment. + ## Install +On Apple Silicon macOS or Linux (x86-64 or ARM64), install the CLI with +Homebrew or the hosted shell installer. + +### Homebrew + +```sh +brew install lancedb/tap/lancedb +lancedb --version +``` + +To upgrade an existing Homebrew installation, run `brew upgrade lancedb/tap/lancedb`. + +### Shell installer + +The installer downloads the latest stable CLI for your platform, verifies the archive's +SHA-256 checksum, and installs the executable in `$HOME/.local/bin`. + +```sh +curl -fsSL https://downloads.lancedb.com/cli/install.sh | sh +"$HOME/.local/bin/lancedb" --version +``` + +Add `$HOME/.local/bin` to your `PATH` to run `lancedb` by name. To install a +specific release, pass the tag to `sh`, for example +`curl -fsSL https://downloads.lancedb.com/cli/install.sh | LANCEDB_VERSION=v0.42.0 sh`. +If you already use the Enterprise CLI, set `LANCEDB_INSTALL_DIR` to a separate +absolute directory and invoke the public CLI by its full path. To upgrade, move +the existing executable first. + +### Manual download + Download a CLI archive and `SHA256SUMS` from the [LanceDB releases page](https://github.com/lancedb/lancedb/releases). The CLI -shares the SDK release version, including beta versions. +shares the SDK release version. | Platform | Target | Requirements | | --- | --- | --- | @@ -25,7 +62,7 @@ shares the SDK release version, including beta versions. Set the version and target to match your chosen release and platform: ```sh -CLI_VERSION=X.Y.Z # Replace with the release version, for example X.Y.Z-beta.N +CLI_VERSION=0.42.0 # Replace with the release version you want CLI_TARGET=aarch64-apple-darwin CLI_STEM="lancedb-v${CLI_VERSION}-${CLI_TARGET}" CLI_RELEASE_URL="https://github.com/lancedb/lancedb/releases/download/v${CLI_VERSION}" diff --git a/docs/web/training/checkpointing.mdx b/docs/web/training/checkpointing.mdx index 119601d98..99124549a 100644 --- a/docs/web/training/checkpointing.mdx +++ b/docs/web/training/checkpointing.mdx @@ -54,6 +54,8 @@ Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. +With `num_workers > 0` and `multiprocessing_context` omitted or `None`, `StreamingDataLoader` uses `forkserver` where the platform provides it and falls back to `spawn`. Callback functions and worker state must be picklable under that start method. Multi-worker scripts should keep their entry point behind the standard `if __name__ == "__main__":` guard so spawned workers can import the module safely. + ```py Python icon=Python from lancedb.streaming import StreamingDataset, StreamingDataLoader diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index 1e4989cf9..1db37189c 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -54,7 +54,7 @@ ds = StreamingDataset( ## Shuffling Rows {#shuffling-rows} -In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles at one of two granularities, selected by the `shuffle_clump_size` parameter. +In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles rows individually by default; `shuffle_clump_size` and `block_size` each trade some randomness for more contiguous reads. `StreamingDataset` shuffle seeds combine `shuffle_seed` with `epoch`; each epoch produces a different permutation while runs @@ -109,6 +109,34 @@ for sample in eval_ds: ``` +### Block Shuffle {#block-shuffle} + +Setting `block_size` enables a two-phase shuffled read. First, contiguous blocks of `block_size` rows are shuffled and read with range scans. Then each split shuffles rows across a rolling window of `window_blocks` blocks (default `8`). Unlike a clump, a block does not stay together: a row can move up to `max_shuffle_distance` positions (default `window_blocks * block_size`) from its place in the block order. Every split serves the same number of rows, so a split can start or end partway through a block, and fewer than `num_splits` rows are left out per epoch. + +`block_size=512` is a good starting point. Use [DataLoader workers](#dataloader-workers), because throughput comes from reading many splits in parallel; `num_splits` must be divisible by `world_size * num_workers`. Keep in mind: + +- The table needs at least `num_splits * block_size` live rows (after `filter`), so that each split gets at least one full block. The example below needs at least 32,768. +- `block_size` cannot be combined with `shuffle_clump_size` or `split_strategy`; passing both raises `ValueError`. +- On LanceDB Embedded, reading on-disk tables requires the optional `pylance` package (`pip install "lancedb[pylance]"`). + + +```py Python icon=Python +# Block shuffle: shuffle contiguous blocks, then rows within a bounded window. +for epoch in range(num_epochs): + ds = StreamingDataset( + table, + shuffle_seed=42, + epoch=epoch, + num_splits=64, + block_size=512, # rows per contiguous block read + window_blocks=8, # blocks per split whose rows are mixed together + ) + loader = StreamingDataLoader(ds, batch_size=32, num_workers=16) + for batch in loader: + train_step(batch) +``` + + ## Fetching {#fetching} Traditional datasets have often been designed to yield a single sample at a time upon iteration. However, in modern use cases, accessing data on object storage one row at a time introduces too much per-call overhead. Thus, `StreamingDataset` fetches data in read batches, whose size is controlled by the `read_batch_size` parameter (defaults = `64`). @@ -217,12 +245,23 @@ dataloader = torch.utils.data.DataLoader( ``` -By default, `StreamingDataset` serializes enough table state to reopen the -table in each worker. Remote LanceDB Enterprise tables (`db://...`) work the -same way: workers reopen the table from the pickled connection state. -Replace the URI, API key, region and endpoint below with your deployment -details. In application code, load credentials from environment variables -or a secrets manager: +By default, `StreamingDataset` and `Permutation` pickle the native table's +reopen state, including its connection, table identity, open options and +explicit storage overrides. A standard-mode handle reopens at the latest +version; `checkout(version)` and branch-scoped handles keep their pinned +version and branch. `memory://` tables are exported as an Arrow snapshot, so +workers see the data as of pickling; an in-memory connection by itself is not +picklable. + +Connections opened with a `Session` cannot be pickled. For a Session-backed +table, pass a picklable `connection_factory` to +`Permutation.with_connection_factory` or `StreamingDataset(connection_factory=...)` +so each worker creates its own connection and Session. + +Remote LanceDB Enterprise tables (`db://...`) work the same way: workers +reopen the table from the pickled connection state. Replace the URI, API key, +region and endpoint below with your deployment details. In application code, +load credentials from environment variables or a secrets manager: ```py Python icon=Python diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx index ebfcce0c6..6f38d226c 100644 --- a/docs/web/training/permutation.mdx +++ b/docs/web/training/permutation.mdx @@ -29,6 +29,45 @@ In specific use cases, you may need the flexibility to shuffle, split, and selec functionality `StreamingDataset` is built on. A `Permutation` defines a customizable row ordering, and supports map-style access through `__getitem__()` and batched access through `__getitems__()`. +## Persisting a permutation {#persisting} + +By default a permutation table is stored in memory. Call `persist` before `execute` to write it to an embedded +LanceDB connection backed by local files or object storage. The plan becomes an ordinary table, so another process +with access to the same storage can open it and use `Permutation.from_tables` to read the same split. + +Only the plan destination must be embedded. The base table can be Embedded or Enterprise; an Enterprise base is +pinned through the plan's recorded base branch and version. + + +```py Python icon=Python +from lancedb.permutation import Permutation, permutation_builder + +db = lancedb.connect("file://some/db/path") +table = db.open_table("some_table") +plan = ( + permutation_builder(table) + .split_random(ratios=[0.8, 0.2], seed=42, split_names=["train", "validation"]) + .persist(db, "splits_v1") + .execute() +) +train = Permutation.from_tables(table, db.open_table("splits_v1"), split="train") +print(train.base_version, train.base_branch) +``` + + +The table returned by `execute` keeps the destination connection and namespace context, so it can be pickled and +reopened directly in a worker process. + +`mode="create"` is the default and fails when the destination table already exists. Pass `mode="overwrite"` to +replace it explicitly. Overwriting writes a new table version; readers that already opened the previous version keep +reading that snapshot. Use `namespace_path` to create the plan in a namespace. Persisting the plan itself to a +LanceDB Enterprise connection is not supported yet, because reproducible Enterprise plan ordering requires +deterministic remote row ordering. + +The plan records the base table version and branch in its schema metadata. `Permutation.base_version` and +`Permutation.base_branch` read those values without querying the base table; both are `None` for older plans that did +not record them. + ## Version Pinning {#version-pinning} A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads @@ -50,32 +89,72 @@ LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it conv column-major `torch.Tensor` with shape `(columns, rows)`. `Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function -can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a -significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you -want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor -conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation` -with one of the transform formats described below. +can batch into a dict of tensors. However, converting every value to a Python object has a significant performance +penalty. To convert the Arrow data in different ways, call `with_format()` with one of the formats below. Here `B` is +the batch size, `C` is the number of columns, and `*S` is the shape of one sample. -To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map -the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`, -`pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and -`torch` formats will all require at least one full copy of the data and are the slowest options. +| Format | Output of `iter(batch_size=B)` | DataLoader collate | +|---|---|---| +| `"arrow"` | `pyarrow.RecordBatch` | Not accepted directly | +| `"torch_dict"` | `dict[str, Tensor]`, one `(B, *S)` tensor per column | Identity function | +| `"torch"` | `list[dict[str, Tensor]]`, one `(*S)` tensor per column per row | Default collate produces `dict[str, Tensor]` with `(B, *S)` | +| `"torch_col"` | One `(C, B, *S)` tensor | Identity function | +| `"torch_row"` | `list[Tensor]`, one `(C, *S)` tensor per row | Default collate produces `(B, C, *S)` | +| `"numpy"` | One NumPy ndarray | Not accepted directly | + +`torch_dict` is usually the best choice for training because it keeps column names, handles columns with different +sample shapes, and shares Arrow storage where the layout allows. `torch_col` and `torch_row` require every column to +have the same sample shape. `torch_row` combines numeric dtypes with `torch.promote_types`, and `torch_col` promotes +supported mixed numeric dtypes through `torch.stack`. If they see mixed scalar and vector columns, they name the +mismatched fields and shapes and point you to `torch_dict`. + +`torch_dict`, `torch`, and `torch_col` reject null values. `torch_row` preserves the previous NaN behavior for +nullable scalar integer and floating columns, but rejects nulls in nested fixed-size-list and tensor columns. Use the +`"python"` or `"arrow"` format for other nullable columns, or drop/fill the nulls first. `lance.bfloat16` values are +supported when the leaf field is `fixed_size_binary[2]` with the `ARROW:extension:name` metadata set to +`lance.bfloat16`; these become `torch.bfloat16` tensors. An unmarked binary column is rejected rather than guessed to +be bfloat16. + +The `numpy` format returns one ndarray built with `batch.to_pandas().to_numpy()`. The pandas conversion may copy data +and may promote mixed numeric columns to a common numeric dtype, for example int64 and float32 to float64. Nested, +list, or incompatible columns produce an object ndarray rather than a numeric array. + +### Using torch_dict with a torch data loader {#using-torch-dict-with-a-torch-data-loader} + +`torch_dict` produces a dictionary of per-column tensors for each batch. Pass an identity function as `collate_fn` so +PyTorch returns that dictionary unchanged. Scalar columns have shape `(B,)`, a `FixedSizeList` column has +shape `(B, D)`, and nested fixed-size lists contribute one dimension per level. Fixed-shape tensor columns use their +logical shape, with the Arrow axis permutation applied as a view. + + +```python Python icon="python" +import torch +from lancedb.permutation import Permutation + +permutation = Permutation.identity(table).with_format("torch_dict") +dataloader = torch.utils.data.DataLoader( + permutation, + batch_size=1024, + shuffle=True, + collate_fn=lambda batch: batch, +) + +for batch in dataloader: + print(batch["id"].shape) # (1024,) + print(batch["vector"].shape) # (1024, 128) +``` + + +When `num_workers > 0`, replace the lambda with a picklable top-level function that returns its argument. ### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader} -The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the -entire Arrow batch to a _column-major_ `torch.Tensor`. In other words, given C columns and R rows, the resulting -Tensor will have shape `(C, R)`. However, this format generates an error if you are using a -`torch.utils.data.DataLoader` with the default collation function: +The `torch_col` format converts the entire Arrow batch to one tensor with shape `(C, B, *S)`. For a table of scalar +columns this is the familiar `(columns, rows)` tensor. For a single column it is an `unsqueeze(0)` view of the +per-column tensor, so no data is copied; stacking multiple columns does copy. -```text -TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor -``` - -This error occurs because the default collation function does not currently expect a single two-dimensional tensor. -It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format -requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function -in addition to specifying the `torch_col` format. +PyTorch's default collate does not accept a single multi-dimensional tensor. Pass an identity function as `collate_fn` +to receive the tensor directly from the data loader. ```python Python icon="python" @@ -86,7 +165,48 @@ dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x) ``` -This will now output a single two-dimensional tensor for each batch. +## Transforming rows with map {#transforming-rows-with-map} + +To change rows in Python as they are read, call `map()` with a function that takes a row as a dict and returns a dict. +Calls can be chained, and the functions run in order. Pass `batched=True` to receive the whole batch as a dict of +column lists instead; the function must then return one value per input row for every column. + + +```python Python icon="python" +import lancedb +import pyarrow as pa +from lancedb.permutation import Permutation + +db = lancedb.connect("memory://") +reviews = db.create_table( + "reviews", + pa.table({"text": ["Great", "Awful", "Fine"], "stars": [5, 1, 3]}), +) + + +def lowercase(row): + return {"text": row["text"].lower(), "stars": row["stars"]} + + +def add_label(batch): + return {**batch, "label": [int(stars >= 3) for stars in batch["stars"]]} + + +permutation = Permutation.identity(reviews).map(lowercase).map(add_label, batched=True) + +print(permutation.take_offsets([0, 1])) +# [{'text': 'great', 'stars': 5, 'label': 1}, {'text': 'awful', 'stars': 1, 'label': 0}] +``` + + +The dict a function returns replaces the row. A column the function does not return is dropped, so return every +column you want to keep. A mapped `Permutation` always produces a list of dicts, like the default format, whether or +not `batched` is set, so PyTorch's default collate function can batch it. `select_columns()` and `schema` still +describe the columns read from the table, which are the input of the first function. + +`map()` cannot be combined with `with_format()` or `with_transform()`. Calling one after the other, in either order, +raises a `ValueError`. To build tensors from mapped rows, convert them in the DataLoader's `collate_fn`. When +`num_workers > 0`, pass picklable top-level functions to `map()`, not lambdas. ## Selecting columns {#selecting-columns} diff --git a/docs/web/training/training-cache.mdx b/docs/web/training/training-cache.mdx index 14769d2f0..3f7e36877 100644 --- a/docs/web/training/training-cache.mdx +++ b/docs/web/training/training-cache.mdx @@ -24,7 +24,7 @@ consequence of connecting to Enterprise at all. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR DL["PyTorch DataLoader
      / StreamingDataset"] --> T["Enterprise-connected table"] @@ -34,7 +34,7 @@ flowchart LR C -->|miss| O[("Object storage")] O --> Fill["Fills the cache,
      served"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class Fast accent ``` @@ -46,7 +46,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR DL["PyTorch DataLoader
      / StreamingDataset"] --> T["Enterprise-connected table"] diff --git a/docs/web/tutorials/index.mdx b/docs/web/tutorials/index.mdx index 6ada57c9a..b9aea29a2 100644 --- a/docs/web/tutorials/index.mdx +++ b/docs/web/tutorials/index.mdx @@ -21,7 +21,7 @@ are runnable in Colab; the rest are written up here. Retrieval-augmented generation and agent applications. - Deriving columns, materialized views, experimenting on branches. + Deriving columns and materialized views.{/* Draft until branching reaches early access: restore "Deriving columns, materialized views, experimenting on branches." */} Curating data and training models directly on a table. diff --git a/java/README.md b/java/README.md index fd163b9f1..85e7e85ba 100644 --- a/java/README.md +++ b/java/README.md @@ -1,5 +1,39 @@ # LanceDB Java Enterprise Client +## Installation + +Stable releases of `com.lancedb:lancedb-core` are published to Maven Central. + +Beta releases are published to `https://maven.fury.io/lancedb/` instead. They +depend on Lance beta releases, which are published to `https://maven.lance.org`. +To use a beta, add both repositories alongside Maven Central: + +```xml + + + lancedb + https://maven.fury.io/lancedb/ + + + lance + https://maven.lance.org + + +``` + +For Gradle: + +```kotlin +repositories { + mavenCentral() + maven { url = uri("https://maven.fury.io/lancedb/") } + maven { url = uri("https://maven.lance.org") } +} +``` + +Use an explicit version, including the full `-beta.N` suffix. Beta versions are +Maven releases, not `SNAPSHOT` versions. + ## Configuration and Initialization ### LanceDB Cloud (legacy) diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 6006329f9..250dcbda8 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.4 + 0.42.0-beta.37 ../pom.xml @@ -17,6 +17,10 @@ Utilities to work with LanceDB Cloud and Enterprise via Lance REST Namespace jar + + 2.25.5 + + org.lance @@ -33,12 +37,12 @@ arrow-memory-netty - + org.apache.httpcomponents.client5 httpclient5 - 5.2.1 + 5.6.5 @@ -93,21 +97,21 @@ org.apache.logging.log4j log4j-slf4j2-impl - 2.25.3 + ${log4j.version} test org.apache.logging.log4j log4j-core - 2.25.3 + ${log4j.version} test org.apache.logging.log4j log4j-api - 2.25.3 + ${log4j.version} test diff --git a/java/pom.xml b/java/pom.xml index 95568874b..a0a2a6ee3 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.4 + 0.42.0-beta.37 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,8 +28,8 @@ UTF-8 15.0.0 - 15.0.0-beta.8 - 2.18.11 + 16.0.0-beta.4 + 2.18.12 false 2.30.0 1.7 @@ -318,6 +318,15 @@ + + deploy-to-fury + + + fury + https://maven.fury.io/lancedb/ + + + deploy-to-ossrh diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 33a71fff3..2c44d4471 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.4" +version = "0.42.0-beta.37" publish = false license.workspace = true description.workspace = true @@ -30,6 +30,7 @@ napi = { version = "3.15.0", default-features = false, features = [ "serde-json", ] } chrono.workspace = true +serde.workspace = true serde_json.workspace = true napi-derive = "3.6.13" # Prevent dynamic linking of lzma, which comes from datafusion @@ -45,7 +46,7 @@ aws-lc-rs = "=1.18.1" napi-build = "2.3.1" [features] -default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel"] +default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] experimental-functions = ["lancedb/experimental-functions"] diff --git a/nodejs/RUST_THIRD_PARTY_LICENSES.html b/nodejs/RUST_THIRD_PARTY_LICENSES.html index 461fb2715..d9ca180c5 100644 --- a/nodejs/RUST_THIRD_PARTY_LICENSES.html +++ b/nodejs/RUST_THIRD_PARTY_LICENSES.html @@ -44,19 +44,19 @@

      Overview of licenses:

      All license text:

      @@ -65,230 +65,20 @@

      BSD Zero Clause License

      Used by:

      -
      Copyright (C) 2020 by museun <museun@outlook.com>
      +                
      Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
       
      -Permission to use, copy, modify, and/or distribute this software for any purpose
      -with or without fee is hereby granted.
      +Permission to use, copy, modify, and/or distribute this software for
      +any purpose with or without fee is hereby granted.
       
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
      -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
      -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
      -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
      -THIS SOFTWARE.
      -
      - -
    • -

      Apache License 2.0

      -

      Used by:

      - -
      -                                 Apache License
      -                           Version 2.0, January 2004
      -                        http://www.apache.org/licenses/
      -
      -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      -
      -   1. Definitions.
      -
      -      "License" shall mean the terms and conditions for use, reproduction,
      -      and distribution as defined by Sections 1 through 9 of this document.
      -
      -      "Licensor" shall mean the copyright owner or entity authorized by
      -      the copyright owner that is granting the License.
      -
      -      "Legal Entity" shall mean the union of the acting entity and all
      -      other entities that control, are controlled by, or are under common
      -      control with that entity. For the purposes of this definition,
      -      "control" means (i) the power, direct or indirect, to cause the
      -      direction or management of such entity, whether by contract or
      -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      -      outstanding shares, or (iii) beneficial ownership of such entity.
      -
      -      "You" (or "Your") shall mean an individual or Legal Entity
      -      exercising permissions granted by this License.
      -
      -      "Source" form shall mean the preferred form for making modifications,
      -      including but not limited to software source code, documentation
      -      source, and configuration files.
      -
      -      "Object" form shall mean any form resulting from mechanical
      -      transformation or translation of a Source form, including but
      -      not limited to compiled object code, generated documentation,
      -      and conversions to other media types.
      -
      -      "Work" shall mean the work of authorship, whether in Source or
      -      Object form, made available under the License, as indicated by a
      -      copyright notice that is included in or attached to the work
      -      (an example is provided in the Appendix below).
      -
      -      "Derivative Works" shall mean any work, whether in Source or Object
      -      form, that is based on (or derived from) the Work and for which the
      -      editorial revisions, annotations, elaborations, or other modifications
      -      represent, as a whole, an original work of authorship. For the purposes
      -      of this License, Derivative Works shall not include works that remain
      -      separable from, or merely link (or bind by name) to the interfaces of,
      -      the Work and Derivative Works thereof.
      -
      -      "Contribution" shall mean any work of authorship, including
      -      the original version of the Work and any modifications or additions
      -      to that Work or Derivative Works thereof, that is intentionally
      -      submitted to Licensor for inclusion in the Work by the copyright owner
      -      or by an individual or Legal Entity authorized to submit on behalf of
      -      the copyright owner. For the purposes of this definition, "submitted"
      -      means any form of electronic, verbal, or written communication sent
      -      to the Licensor or its representatives, including but not limited to
      -      communication on electronic mailing lists, source code control systems,
      -      and issue tracking systems that are managed by, or on behalf of, the
      -      Licensor for the purpose of discussing and improving the Work, but
      -      excluding communication that is conspicuously marked or otherwise
      -      designated in writing by the copyright owner as "Not a Contribution."
      -
      -      "Contributor" shall mean Licensor and any individual or Legal Entity
      -      on behalf of whom a Contribution has been received by Licensor and
      -      subsequently incorporated within the Work.
      -
      -   2. Grant of Copyright License. Subject to the terms and conditions of
      -      this License, each Contributor hereby grants to You a perpetual,
      -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      -      copyright license to reproduce, prepare Derivative Works of,
      -      publicly display, publicly perform, sublicense, and distribute the
      -      Work and such Derivative Works in Source or Object form.
      -
      -   3. Grant of Patent License. Subject to the terms and conditions of
      -      this License, each Contributor hereby grants to You a perpetual,
      -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      -      (except as stated in this section) patent license to make, have made,
      -      use, offer to sell, sell, import, and otherwise transfer the Work,
      -      where such license applies only to those patent claims licensable
      -      by such Contributor that are necessarily infringed by their
      -      Contribution(s) alone or by combination of their Contribution(s)
      -      with the Work to which such Contribution(s) was submitted. If You
      -      institute patent litigation against any entity (including a
      -      cross-claim or counterclaim in a lawsuit) alleging that the Work
      -      or a Contribution incorporated within the Work constitutes direct
      -      or contributory patent infringement, then any patent licenses
      -      granted to You under this License for that Work shall terminate
      -      as of the date such litigation is filed.
      -
      -   4. Redistribution. You may reproduce and distribute copies of the
      -      Work or Derivative Works thereof in any medium, with or without
      -      modifications, and in Source or Object form, provided that You
      -      meet the following conditions:
      -
      -      (a) You must give any other recipients of the Work or
      -          Derivative Works a copy of this License; and
      -
      -      (b) You must cause any modified files to carry prominent notices
      -          stating that You changed the files; and
      -
      -      (c) You must retain, in the Source form of any Derivative Works
      -          that You distribute, all copyright, patent, trademark, and
      -          attribution notices from the Source form of the Work,
      -          excluding those notices that do not pertain to any part of
      -          the Derivative Works; and
      -
      -      (d) If the Work includes a "NOTICE" text file as part of its
      -          distribution, then any Derivative Works that You distribute must
      -          include a readable copy of the attribution notices contained
      -          within such NOTICE file, excluding those notices that do not
      -          pertain to any part of the Derivative Works, in at least one
      -          of the following places: within a NOTICE text file distributed
      -          as part of the Derivative Works; within the Source form or
      -          documentation, if provided along with the Derivative Works; or,
      -          within a display generated by the Derivative Works, if and
      -          wherever such third-party notices normally appear. The contents
      -          of the NOTICE file are for informational purposes only and
      -          do not modify the License. You may add Your own attribution
      -          notices within Derivative Works that You distribute, alongside
      -          or as an addendum to the NOTICE text from the Work, provided
      -          that such additional attribution notices cannot be construed
      -          as modifying the License.
      -
      -      You may add Your own copyright statement to Your modifications and
      -      may provide additional or different license terms and conditions
      -      for use, reproduction, or distribution of Your modifications, or
      -      for any such Derivative Works as a whole, provided Your use,
      -      reproduction, and distribution of the Work otherwise complies with
      -      the conditions stated in this License.
      -
      -   5. Submission of Contributions. Unless You explicitly state otherwise,
      -      any Contribution intentionally submitted for inclusion in the Work
      -      by You to the Licensor shall be under the terms and conditions of
      -      this License, without any additional terms or conditions.
      -      Notwithstanding the above, nothing herein shall supersede or modify
      -      the terms of any separate license agreement you may have executed
      -      with Licensor regarding such Contributions.
      -
      -   6. Trademarks. This License does not grant permission to use the trade
      -      names, trademarks, service marks, or product names of the Licensor,
      -      except as required for reasonable and customary use in describing the
      -      origin of the Work and reproducing the content of the NOTICE file.
      -
      -   7. Disclaimer of Warranty. Unless required by applicable law or
      -      agreed to in writing, Licensor provides the Work (and each
      -      Contributor provides its Contributions) on an "AS IS" BASIS,
      -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      -      implied, including, without limitation, any warranties or conditions
      -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      -      PARTICULAR PURPOSE. You are solely responsible for determining the
      -      appropriateness of using or redistributing the Work and assume any
      -      risks associated with Your exercise of permissions under this License.
      -
      -   8. Limitation of Liability. In no event and under no legal theory,
      -      whether in tort (including negligence), contract, or otherwise,
      -      unless required by applicable law (such as deliberate and grossly
      -      negligent acts) or agreed to in writing, shall any Contributor be
      -      liable to You for damages, including any direct, indirect, special,
      -      incidental, or consequential damages of any character arising as a
      -      result of this License or out of the use or inability to use the
      -      Work (including but not limited to damages for loss of goodwill,
      -      work stoppage, computer failure or malfunction, or any and all
      -      other commercial damages or losses), even if such Contributor
      -      has been advised of the possibility of such damages.
      -
      -   9. Accepting Warranty or Additional Liability. While redistributing
      -      the Work or Derivative Works thereof, You may choose to offer,
      -      and charge a fee for, acceptance of support, warranty, indemnity,
      -      or other liability obligations and/or rights consistent with this
      -      License. However, in accepting such obligations, You may act only
      -      on Your own behalf and on Your sole responsibility, not on behalf
      -      of any other Contributor, and only if You agree to indemnify,
      -      defend, and hold each Contributor harmless for any liability
      -      incurred by, or claims asserted against, such Contributor by reason
      -      of your accepting any such warranty or additional liability.
      -
      -   END OF TERMS AND CONDITIONS
      -
      -   APPENDIX: How to apply the Apache License to your work.
      -
      -      To apply the Apache License to your work, attach the following
      -      boilerplate notice, with the fields enclosed by brackets "[]"
      -      replaced with your own identifying information. (Don't include
      -      the brackets!)  The text should be enclosed in the appropriate
      -      comment syntax for the file format. We also recommend that a
      -      file or class name and description of purpose be included on the
      -      same "printed page" as the copyright notice for easier
      -      identification within third-party archives.
      -
      -   Copyright 2023 Jacob Pratt
      -
      -   Licensed under the Apache License, Version 2.0 (the "License");
      -   you may not use this file except in compliance with the License.
      -   You may obtain a copy of the License at
      -
      -       http://www.apache.org/licenses/LICENSE-2.0
      -
      -   Unless required by applicable law or agreed to in writing, software
      -   distributed under the License is distributed on an "AS IS" BASIS,
      -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      -   See the License for the specific language governing permissions and
      -   limitations under the License.
      +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
      +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
      +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
      +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
    • @@ -505,7 +295,7 @@ THIS SOFTWARE.

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -715,23 +505,224 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

      +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + @@ -943,7 +934,8 @@ THIS SOFTWARE.

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -1155,34 +1147,549 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

      +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +--- LLVM Exceptions to the Apache 2.0 License ----
      +
      +As an exception, if, as a result of your compiling your source code, portions
      +of this Software are embedded into an Object form of such source code, you
      +may redistribute such embedded portions in such Object form without complying
      +with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
      +
      +In addition, if you combine or link compiled forms of this Software with
      +software that is licensed under the GPLv2 ("Combined Software") and if a
      +court of competent jurisdiction determines that the patent provision (Section
      +3), the indemnity provision (Section 9) or other Section of the License
      +conflicts with the conditions of the GPLv2, you may retroactively and
      +prospectively choose to deem waived or otherwise exclude such Section(s) of
      +the License, but only in their entirety and only with respect to the Combined
      +Software.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +Licenses for support code
      +-------------------------
      +
      +Parts of the TLS test suite are under the Go license. This code is not included
      +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
      +distributing code linked against BoringSSL does not trigger this license:
      +
      +Copyright (c) 2009 The Go Authors. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +   * Redistributions of source code must retain the above copyright
      +notice, this list of conditions and the following disclaimer.
      +   * Redistributions in binary form must reproduce the above
      +copyright notice, this list of conditions and the following disclaimer
      +in the documentation and/or other materials provided with the
      +distribution.
      +   * Neither the name of Google Inc. nor the names of its
      +contributors may be used to endorse or promote products derived from
      +this software without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
      +BoringSSL uses the Chromium test infrastructure to run a continuous build,
      +trybots etc. The scripts which manage this, and the script for generating build
      +metadata, are under the Chromium license. Distributing code linked against
      +BoringSSL does not trigger this license.
      +
      +Copyright 2015 The Chromium Authors. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +   * Redistributions of source code must retain the above copyright
      +notice, this list of conditions and the following disclaimer.
      +   * Redistributions in binary form must reproduce the above
      +copyright notice, this list of conditions and the following disclaimer
      +in the documentation and/or other materials provided with the
      +distribution.
      +   * Neither the name of Google Inc. nor the names of its
      +contributors may be used to endorse or promote products derived from
      +this software without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                        Apache License
      @@ -1396,6 +1903,237 @@ This project includes code from Apache Aurora.
       Copyright: 2016 The Apache Software Foundation.
       Home page: https://aurora.apache.org/
       License: http://www.apache.org/licenses/LICENSE-2.0
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +--------------------------------------------------------------------------------
      +
      +arrow-array/src/delta.rs: MIT
      +
      +This file is derived from the chronoutil crate. The full MIT license
      +text is in arrow-array/LICENSE-MIT.
       
    • @@ -1403,9 +2141,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

      Used by:

                                        Apache License
      @@ -1615,7 +2351,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -1815,7 +2551,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Used by:

                                        Apache License
      @@ -2025,41 +2760,30 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2268,7 +2992,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2477,7 +3201,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2667,7 +3392,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
             same "printed page" as the copyright notice for easier
             identification within third-party archives.
       
      -   Copyright 2020 - 2025 Tatsuya Kawano
      +   Copyright 2019 TiKV Project Authors.
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 - 2026 Tatsuya Kawano
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 Sébastien Crozet
       
          Licensed under the Apache License, Version 2.0 (the "License");
          you may not use this file except in compliance with the License.
      @@ -2687,7 +3830,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2895,8 +4037,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3315,7 +4457,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3524,9 +4666,20 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3735,7 +4888,455 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +------------------------------------------------------------------------------------
      +This product bundles third-party components under other open source licenses.
      +This section summarizes those components and their licenses. See the referenced
      +license files for text of these licenses.
      +
      +
      +Creative Commons Zero v1.0 Universal
      +------------------------------------
      +
      +bindings/dotnet/.gitignore
      +
      +The above file is derived from VisualStudio.gitignore in
      +https://github.com/github/gitignore. Its license text is in
      +bindings/dotnet/LICENSE-CC0-1.0.txt.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +   
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                       Apache License
                                  Version 2.0, January 2004
      @@ -3944,6 +5545,218 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "{}"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright Individual contributors
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                       Apache License
      @@ -4153,22 +5966,28 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -4378,12 +6197,221 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 Sébastien Crozet
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                      Apache License
                                  Version 2.0, January 2004
      @@ -4593,7 +6621,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                     Apache License
                                  Version 2.0, January 2004
      @@ -5011,15 +7039,15 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5229,7 +7257,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5437,7 +7465,8 @@ limitations under the License.

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5646,8 +7675,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5856,7 +7884,6 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
      @@ -6066,7 +8093,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6256,7 +8283,7 @@ APPENDIX: How to apply the Apache License to your work.
          same "printed page" as the copyright notice for easier
          identification within third-party archives.
       
      -Copyright 2018 The pin-utils authors
      +Copyright 2018 Brian Myers
       
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
      @@ -6275,8 +8302,8 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6683,6 +8710,215 @@ You may obtain a copy of the License at
       
          http://www.apache.org/licenses/LICENSE-2.0
       
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright 2019 quininer kel
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      @@ -6695,7 +8931,9 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6905,7 +9143,7 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7323,7 +9561,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7532,7 +9770,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7743,7 +9981,216 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright 2024 Liam Gray <gmail@liamg.me>
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                    Apache License
                               Version 2.0, January 2004
      @@ -7953,7 +10400,8 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -8161,156 +10609,171 @@ limitations under the License.

      Apache License 2.0

      Used by:

        +
      • addr2line 0.25.1
      • ahash 0.8.12
      • -
      • arc-swap 1.7.1
      • -
      • arrayvec 0.7.6
      • +
      • arc-swap 1.9.3
      • +
      • arrayvec 0.7.8
      • async-channel 2.5.0
      • -
      • async-compression 0.4.19
      • -
      • async-lock 3.4.1
      • +
      • async-compression 0.4.42
      • +
      • async-lock 3.4.2
      • atomic-waker 1.1.2
      • autocfg 1.5.0
      • -
      • base64 0.21.7
      • +
      • backtrace 0.3.76
      • base64 0.22.1
      • -
      • bitflags 2.9.4
      • -
      • bumpalo 3.19.0
      • +
      • base64 0.23.1
      • +
      • bitflags 1.3.2
      • +
      • bitflags 2.11.1
      • +
      • bstr 1.12.1
      • +
      • bumpalo 3.20.2
      • bytes-utils 0.1.4
      • -
      • cc 1.2.40
      • -
      • cexpr 0.6.0
      • -
      • cfg-if 1.0.3
      • -
      • cmake 0.1.54
      • +
      • cast 0.3.0
      • +
      • cc 1.2.62
      • +
      • cfg-if 0.1.10
      • +
      • cfg-if 1.0.4
      • +
      • cmake 0.1.58
      • +
      • compression-codecs 0.4.38
      • +
      • compression-core 0.4.32
      • concurrent-queue 2.5.0
      • const-random-macro 0.1.16
      • const-random 0.1.18
      • core-foundation-sys 0.8.7
      • core-foundation 0.10.1
      • core-foundation 0.9.4
      • +
      • cpp_demangle 0.4.5
      • +
      • criterion-plot 0.8.2
      • +
      • criterion 0.8.2
      • crossbeam-channel 0.5.15
      • crossbeam-deque 0.8.6
      • -
      • crossbeam-epoch 0.9.18
      • +
      • crossbeam-epoch 0.9.20
      • crossbeam-queue 0.3.12
      • +
      • crossbeam-skiplist 0.1.3
      • crossbeam-utils 0.8.21
      • +
      • debugid 0.8.0
      • displaydoc 0.2.5
      • either 1.15.0
      • +
      • encoding_rs_io 0.1.7
      • equivalent 1.0.2
      • errno 0.3.14
      • event-listener-strategy 0.5.4
      • -
      • event-listener 5.4.1
      • -
      • fastrand 2.3.0
      • -
      • find-msvc-tools 0.1.3
      • +
      • event-listener 5.4.2
      • +
      • fastrand 2.4.1
      • +
      • find-msvc-tools 0.1.9
      • +
      • findshlibs 0.10.2
      • fixedbitset 0.5.7
      • +
      • flate2 1.1.9
      • fnv 1.0.7
      • form_urlencoded 1.2.2
      • -
      • fs4 0.8.4
      • +
      • foyer-intrusive-collections 0.10.0-dev
      • +
      • fs4 0.13.1
      • futures-timer 3.0.3
      • -
      • geohash 0.13.1
      • +
      • geohash 0.13.2
      • +
      • gimli 0.32.3
      • glob 0.3.3
      • -
      • group 0.12.1
      • +
      • group 0.14.0
      • hash32 0.3.1
      • hashbrown 0.14.5
      • hashbrown 0.15.5
      • -
      • hashbrown 0.16.0
      • +
      • hashbrown 0.16.1
      • +
      • hashbrown 0.17.1
      • heapless 0.8.0
      • heck 0.5.0
      • hermit-abi 0.5.2
      • httparse 1.10.1
      • -
      • hyper-rustls 0.24.2
      • -
      • hyper-rustls 0.27.7
      • +
      • hyper-rustls 0.27.9
      • +
      • hyper-timeout 0.5.2
      • idna 1.1.0
      • -
      • idna_adapter 1.2.1
      • -
      • indexmap 2.12.0
      • -
      • itertools 0.11.0
      • -
      • itertools 0.12.1
      • +
      • idna_adapter 1.2.2
      • +
      • indexmap 2.14.0
      • itertools 0.13.0
      • itertools 0.14.0
      • +
      • itertools 0.15.0
      • jobserver 0.1.34
      • -
      • js-sys 0.3.81
      • +
      • js-sys 0.3.107
      • lazy_static 1.5.0
      • -
      • lazycell 1.3.0
      • -
      • linux-raw-sys 0.11.0
      • -
      • linux-raw-sys 0.4.15
      • +
      • linux-raw-sys 0.12.1
      • lock_api 0.4.14
      • -
      • log 0.4.28
      • +
      • log 0.4.34
      • lzma-sys 0.1.20
      • matrixmultiply 0.3.10
      • mime 0.3.17
      • -
      • multimap 0.10.1
      • ndarray 0.16.1
      • -
      • num-bigint-dig 0.8.4
      • +
      • num-bigint-dig 0.8.6
      • num-bigint 0.4.6
      • +
      • num-bigint 0.5.1
      • num-complex 0.4.6
      • num-integer 0.1.46
      • num-iter 0.1.45
      • +
      • num-rational 0.4.2
      • num-traits 0.2.19
      • num_cpus 1.17.0
      • -
      • once_cell 1.21.3
      • -
      • openssl-probe 0.1.6
      • +
      • oauth2 5.0.0
      • +
      • object 0.37.3
      • +
      • once_cell 1.21.4
      • +
      • openssl-probe 0.2.1
      • parking 2.2.1
      • parking_lot 0.12.5
      • parking_lot_core 0.9.12
      • percent-encoding 2.3.2
      • petgraph 0.8.3
      • -
      • pkg-config 0.3.32
      • -
      • prost-build 0.14.3
      • -
      • prost-derive 0.14.3
      • +
      • pkg-config 0.3.33
      • +
      • prost-derive 0.14.4
      • prost-types 0.14.3
      • -
      • prost 0.14.3
      • +
      • prost 0.14.4
      • +
      • rand_xoshiro 0.6.0
      • rawpointer 0.2.1
      • rayon-core 1.13.0
      • -
      • rayon 1.11.0
      • -
      • regex-automata 0.4.13
      • -
      • regex-lite 0.1.7
      • -
      • regex-syntax 0.8.6
      • -
      • regex 1.12.2
      • +
      • rayon 1.12.0
      • +
      • regex-automata 0.4.16
      • +
      • regex-lite 0.1.9
      • +
      • regex-syntax 0.8.11
      • +
      • regex 1.13.1
      • ring 0.17.14
      • +
      • roaring 0.11.5
      • robust 1.2.0
      • -
      • rustc-hash 1.1.0
      • +
      • rustc-demangle 0.1.27
      • rustc_version 0.4.1
      • -
      • rustix 0.38.44
      • -
      • rustix 1.1.2
      • -
      • rustls-native-certs 0.6.3
      • -
      • rustls-native-certs 0.8.1
      • -
      • rustls-pemfile 1.0.4
      • -
      • rustls-pemfile 2.2.0
      • -
      • rustls 0.21.12
      • -
      • rustls 0.23.31
      • +
      • rustix 1.1.4
      • +
      • rustls-native-certs 0.8.3
      • +
      • rustls 0.23.46
      • scoped-tls 1.0.1
      • scopeguard 1.2.0
      • -
      • sct 0.7.1
      • -
      • security-framework-sys 2.15.0
      • -
      • security-framework 2.11.1
      • -
      • security-framework 3.5.1
      • -
      • serde_with 3.15.0
      • -
      • serde_with_macros 3.15.0
      • -
      • shellexpand 3.1.1
      • -
      • signal-hook-registry 1.4.6
      • -
      • smallvec 1.15.1
      • -
      • socket2 0.5.10
      • -
      • socket2 0.6.0
      • -
      • sqlparser 0.59.0
      • -
      • sqlparser_derive 0.3.0
      • -
      • stable_deref_trait 1.2.0
      • -
      • syn 1.0.109
      • +
      • security-framework-sys 2.17.0
      • +
      • security-framework 3.7.0
      • +
      • serde_with 3.24.0
      • +
      • serde_with_macros 3.24.0
      • +
      • shellexpand 3.1.2
      • +
      • signal-hook-registry 1.4.8
      • +
      • simd_cesu8 1.1.1
      • +
      • smallvec 1.16.5
      • +
      • socket2 0.6.3
      • +
      • sqlparser 0.62.0
      • +
      • sqlparser_derive 0.5.0
      • +
      • stable_deref_trait 1.2.1
      • +
      • str_stack 0.1.1
      • +
      • symlink 0.1.0
      • system-configuration-sys 0.6.0
      • -
      • system-configuration 0.6.1
      • -
      • tempfile 3.23.0
      • +
      • system-configuration 0.7.0
      • +
      • tempfile 3.27.0
      • thread-tree 0.3.3
      • -
      • thread_local 1.1.9
      • -
      • unicase 2.8.1
      • -
      • unicode-segmentation 1.12.0
      • -
      • unicode-width 0.2.2
      • -
      • url 2.5.7
      • -
      • uuid 1.18.1
      • +
      • thread_local 1.1.10
      • +
      • tinytemplate 1.2.1
      • +
      • unicase 2.9.0
      • +
      • unicode-normalization 0.1.25
      • +
      • unicode-segmentation 1.13.2
      • +
      • unicode-width 0.2.3
      • +
      • url 2.5.8
      • +
      • uuid 1.29.0
      • version_check 0.9.5
      • wasi 0.11.1+wasi-snapshot-preview1
      • wasi 0.14.7+wasi-0.2.4
      • -
      • wasm-bindgen-backend 0.2.104
      • -
      • wasm-bindgen-futures 0.4.54
      • -
      • wasm-bindgen-macro-support 0.2.104
      • -
      • wasm-bindgen-macro 0.2.104
      • -
      • wasm-bindgen-shared 0.2.104
      • -
      • wasm-bindgen 0.2.104
      • -
      • web-sys 0.3.81
      • -
      • wit-bindgen 0.46.0
      • +
      • wasip2 1.0.3+wasi-0.2.9
      • +
      • wasm-bindgen-futures 0.4.80
      • +
      • wasm-bindgen-macro-support 0.2.130
      • +
      • wasm-bindgen-macro 0.2.130
      • +
      • wasm-bindgen-shared 0.2.130
      • +
      • wasm-bindgen 0.2.130
      • +
      • web-sys 0.3.107
      • +
      • wit-bindgen 0.57.1
      • wkb 0.9.2
      • wkt 0.14.0
      • xmlparser 0.13.6
      • @@ -8522,7 +10985,7 @@ limitations under the License.

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8732,14 +11195,12 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8949,41 +11410,55 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9192,10 +11667,209 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +Copyright (c) 2015-2022 Amod Malviya
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        + +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                      Apache License
                                 Version 2.0, January 2004
        @@ -9390,11 +12064,13 @@ APPENDIX: How to apply the Apache License to your work.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9603,8 +12279,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9813,7 +12488,9 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
                                    Version 2.0, January 2004
        @@ -10022,7 +12699,9 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
         Version 2.0, January 2004
        @@ -10301,128 +12980,169 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
         Version 2.0, January 2004
        @@ -10739,10 +13459,10 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Rust-chrono is dual-licensed under The MIT License [1] and
        -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
        +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
         contributors.
         
         Nota Bene: This is same as the Rust Project's own license.
        @@ -10981,6 +13701,40 @@ See the License for the specific language governing permissions and
         limitations under the License.
         ~~~~
         
        +
        +
      • +
      • +

        BSD 2-Clause "Simplified" License

        +

        Used by:

        + +
        Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are
        +met:
        +
        +1. Redistributions of source code must retain the above copyright
        +   notice, this list of conditions and the following disclaimer.
        +
        +2. Redistributions in binary form must reproduce the above copyright
        +   notice, this list of conditions and the following disclaimer in the
        +   documentation and/or other materials provided with the
        +   distribution.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
        +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
        +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
        +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
        +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
      • @@ -11015,6 +13769,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
      • + +
      • +

        BSD 2-Clause "Simplified" License

        +

        Used by:

        + +
        Copyright (c) 2017-2020
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are met:
        +
        +1. Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +2. Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
        +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
        +//
        +// Redistribution and use in source and binary forms, with or without
        +// modification, are permitted provided that the following conditions are met:
        +//
        +// 1. Redistributions of source code must retain the above copyright notice, this
        +//    list of conditions and the following disclaimer.
        +//
        +// 2. Redistributions in binary form must reproduce the above copyright notice,
        +//    this list of conditions and the following disclaimer in the documentation
        +//    and/or other materials provided with the distribution.
        +//
        +// 3. Neither the name of the copyright holder nor the names of its
        +//    contributors may be used to endorse or promote products derived from
        +//    this software without specific prior written permission.
        +//
        +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +/// The PUA code points special-cased in the GB18030 encoder.
        +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
        +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
        +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
        +];
        +
        +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
        +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
        +    [0xA6, 0xD9],
        +    [0xA6, 0xDA],
        +    [0xA6, 0xDB],
        +    [0xA6, 0xDC],
        +    [0xA6, 0xDD],
        +    [0xA6, 0xDE],
        +    [0xA6, 0xDF],
        +    [0xA6, 0xEC],
        +    [0xA6, 0xED],
        +    [0xA6, 0xF3],
        +    [0xFE, 0x59],
        +    [0xFE, 0x61],
        +    [0xFE, 0x66],
        +    [0xFE, 0x67],
        +    [0xFE, 0x6D],
        +    [0xFE, 0x7E],
        +    [0xFE, 0x90],
        +    [0xFE, 0xA0],
        +];
         
      • @@ -11022,6 +13869,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

        Used by:

        BSD 3-Clause License
         
        @@ -11058,26 +13906,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        BSD 3-Clause License
         
        -Copyright (c) 2013, Jyun-Yan You
        -All rights reserved.
        +Copyright (c) 2026, Alexandre Bury
         
         Redistribution and use in source and binary forms, with or without
         modification, are permitted provided that the following conditions are met:
         
        -* Redistributions of source code must retain the above copyright notice, this
        -  list of conditions and the following disclaimer.
        +1. Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
         
        -* Redistributions in binary form must reproduce the above copyright notice,
        -  this list of conditions and the following disclaimer in the documentation
        -  and/or other materials provided with the distribution.
        +2. Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
         
        -* Neither the name of the copyright holder nor the names of its
        -  contributors may be used to endorse or promote products derived from
        -  this software without specific prior written permission.
        +3. Neither the name of the copyright holder nor the names of its
        +   contributors may be used to endorse or promote products derived from
        +   this software without specific prior written permission.
         
         THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
         AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        @@ -11095,10 +13944,50 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        +
        BSD License
        +
        +For Zstandard software
        +
        +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without modification,
        +are permitted provided that the following conditions are met:
        +
        + * Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        + * Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        + * Neither the name Facebook, nor Meta, nor the names of its contributors may
        +   be used to endorse or promote products derived from this software without
        +   specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        +
        Copyright (c) 2001, Dr Martin Porter
         Copyright (c) 2004,2005, Richard Boulton
        +Copyright (c) 2013, Yoshiki Shibukawa
        +Copyright (c) 2006-2025, Olly Betts
         All rights reserved.
         
         Redistribution and use in source and binary forms, with or without
        @@ -11123,16 +14012,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
         LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
         ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
         (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
      • BSD 3-Clause "New" or "Revised" License

        Used by:

        Copyright (c) 2016 Dropbox, Inc.
         All rights reserved.
        @@ -11189,8 +14078,47 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        +
        Copyright (c) 2026, frostem contributors
        +Copyright (c) 2001, Dr Martin Porter
        +Copyright (c) 2004,2005, Richard Boulton
        +Copyright (c) 2013, Yoshiki Shibukawa
        +Copyright (c) 2006-2025, Olly Betts
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions
        +are met:
        +
        +  1. Redistributions of source code must retain the above copyright notice,
        +     this list of conditions and the following disclaimer.
        +  2. Redistributions in binary form must reproduce the above copyright notice,
        +     this list of conditions and the following disclaimer in the documentation
        +     and/or other materials provided with the distribution.
        +  3. Neither the name of the Snowball project nor the names of its contributors
        +     may be used to endorse or promote products derived from this software
        +     without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        +
        Copyright (c) <year> <owner>. 
         
        @@ -11237,13 +14165,53 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
         CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
         OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
         OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        The auto-generated bindings are under the 3-clause BSD license:
        +
        +BSD License
        +
        +For Zstandard software
        +
        +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without modification,
        +are permitted provided that the following conditions are met:
        +
        + * Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        + * Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        + * Neither the name Facebook, nor Meta, nor the names of its contributors may
        +   be used to endorse or promote products derived from this software without
        +   specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
      • Boost Software License 1.0

        Used by:

        Boost Software License - Version 1.0 - August 17th, 2003
         
        @@ -11397,13 +14365,405 @@ express Statement of Purpose.
          d. Affirmer understands and acknowledges that Creative Commons is not a
             party to this document and has no duty or obligation with respect to
             this CC0 or use of the Work.
        +
        +
      • +
      • +

        Common Development and Distribution License 1.0

        +

        Used by:

        + +
        Unless otherwise noted, all files in this distribution are released
        +under the Common Development and Distribution License (CDDL).
        +Exceptions are noted within the associated source files.
        +
        +--------------------------------------------------------------------
        +
        +
        +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
        +
        +1. Definitions.
        +
        +    1.1. "Contributor" means each individual or entity that creates
        +         or contributes to the creation of Modifications.
        +
        +    1.2. "Contributor Version" means the combination of the Original
        +         Software, prior Modifications used by a Contributor (if any),
        +         and the Modifications made by that particular Contributor.
        +
        +    1.3. "Covered Software" means (a) the Original Software, or (b)
        +         Modifications, or (c) the combination of files containing
        +         Original Software with files containing Modifications, in
        +         each case including portions thereof.
        +
        +    1.4. "Executable" means the Covered Software in any form other
        +         than Source Code.
        +
        +    1.5. "Initial Developer" means the individual or entity that first
        +         makes Original Software available under this License.
        +
        +    1.6. "Larger Work" means a work which combines Covered Software or
        +         portions thereof with code not governed by the terms of this
        +         License.
        +
        +    1.7. "License" means this document.
        +
        +    1.8. "Licensable" means having the right to grant, to the maximum
        +         extent possible, whether at the time of the initial grant or
        +         subsequently acquired, any and all of the rights conveyed
        +         herein.
        +
        +    1.9. "Modifications" means the Source Code and Executable form of
        +         any of the following:
        +
        +        A. Any file that results from an addition to, deletion from or
        +           modification of the contents of a file containing Original
        +           Software or previous Modifications;
        +
        +        B. Any new file that contains any part of the Original
        +           Software or previous Modifications; or
        +
        +        C. Any new file that is contributed or otherwise made
        +           available under the terms of this License.
        +
        +    1.10. "Original Software" means the Source Code and Executable
        +          form of computer software code that is originally released
        +          under this License.
        +
        +    1.11. "Patent Claims" means any patent claim(s), now owned or
        +          hereafter acquired, including without limitation, method,
        +          process, and apparatus claims, in any patent Licensable by
        +          grantor.
        +
        +    1.12. "Source Code" means (a) the common form of computer software
        +          code in which modifications are made and (b) associated
        +          documentation included in or with such code.
        +
        +    1.13. "You" (or "Your") means an individual or a legal entity
        +          exercising rights under, and complying with all of the terms
        +          of, this License.  For legal entities, "You" includes any
        +          entity which controls, is controlled by, or is under common
        +          control with You.  For purposes of this definition,
        +          "control" means (a) the power, direct or indirect, to cause
        +          the direction or management of such entity, whether by
        +          contract or otherwise, or (b) ownership of more than fifty
        +          percent (50%) of the outstanding shares or beneficial
        +          ownership of such entity.
        +
        +2. License Grants.
        +
        +    2.1. The Initial Developer Grant.
        +
        +    Conditioned upon Your compliance with Section 3.1 below and
        +    subject to third party intellectual property claims, the Initial
        +    Developer hereby grants You a world-wide, royalty-free,
        +    non-exclusive license:
        +
        +        (a) under intellectual property rights (other than patent or
        +            trademark) Licensable by Initial Developer, to use,
        +            reproduce, modify, display, perform, sublicense and
        +            distribute the Original Software (or portions thereof),
        +            with or without Modifications, and/or as part of a Larger
        +            Work; and
        +
        +        (b) under Patent Claims infringed by the making, using or
        +            selling of Original Software, to make, have made, use,
        +            practice, sell, and offer for sale, and/or otherwise
        +            dispose of the Original Software (or portions thereof).
        +
        +        (c) The licenses granted in Sections 2.1(a) and (b) are
        +            effective on the date Initial Developer first distributes
        +            or otherwise makes the Original Software available to a
        +            third party under the terms of this License.
        +
        +        (d) Notwithstanding Section 2.1(b) above, no patent license is
        +            granted: (1) for code that You delete from the Original
        +            Software, or (2) for infringements caused by: (i) the
        +            modification of the Original Software, or (ii) the
        +            combination of the Original Software with other software
        +            or devices.
        +
        +    2.2. Contributor Grant.
        +
        +    Conditioned upon Your compliance with Section 3.1 below and
        +    subject to third party intellectual property claims, each
        +    Contributor hereby grants You a world-wide, royalty-free,
        +    non-exclusive license:
        +
        +        (a) under intellectual property rights (other than patent or
        +            trademark) Licensable by Contributor to use, reproduce,
        +            modify, display, perform, sublicense and distribute the
        +            Modifications created by such Contributor (or portions
        +            thereof), either on an unmodified basis, with other
        +            Modifications, as Covered Software and/or as part of a
        +            Larger Work; and
        +
        +        (b) under Patent Claims infringed by the making, using, or
        +            selling of Modifications made by that Contributor either
        +            alone and/or in combination with its Contributor Version
        +            (or portions of such combination), to make, use, sell,
        +            offer for sale, have made, and/or otherwise dispose of:
        +            (1) Modifications made by that Contributor (or portions
        +            thereof); and (2) the combination of Modifications made by
        +            that Contributor with its Contributor Version (or portions
        +            of such combination).
        +
        +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
        +            effective on the date Contributor first distributes or
        +            otherwise makes the Modifications available to a third
        +            party.
        +
        +        (d) Notwithstanding Section 2.2(b) above, no patent license is
        +            granted: (1) for any code that Contributor has deleted
        +            from the Contributor Version; (2) for infringements caused
        +            by: (i) third party modifications of Contributor Version,
        +            or (ii) the combination of Modifications made by that
        +            Contributor with other software (except as part of the
        +            Contributor Version) or other devices; or (3) under Patent
        +            Claims infringed by Covered Software in the absence of
        +            Modifications made by that Contributor.
        +
        +3. Distribution Obligations.
        +
        +    3.1. Availability of Source Code.
        +
        +    Any Covered Software that You distribute or otherwise make
        +    available in Executable form must also be made available in Source
        +    Code form and that Source Code form must be distributed only under
        +    the terms of this License.  You must include a copy of this
        +    License with every copy of the Source Code form of the Covered
        +    Software You distribute or otherwise make available.  You must
        +    inform recipients of any such Covered Software in Executable form
        +    as to how they can obtain such Covered Software in Source Code
        +    form in a reasonable manner on or through a medium customarily
        +    used for software exchange.
        +
        +    3.2. Modifications.
        +
        +    The Modifications that You create or to which You contribute are
        +    governed by the terms of this License.  You represent that You
        +    believe Your Modifications are Your original creation(s) and/or
        +    You have sufficient rights to grant the rights conveyed by this
        +    License.
        +
        +    3.3. Required Notices.
        +
        +    You must include a notice in each of Your Modifications that
        +    identifies You as the Contributor of the Modification.  You may
        +    not remove or alter any copyright, patent or trademark notices
        +    contained within the Covered Software, or any notices of licensing
        +    or any descriptive text giving attribution to any Contributor or
        +    the Initial Developer.
        +
        +    3.4. Application of Additional Terms.
        +
        +    You may not offer or impose any terms on any Covered Software in
        +    Source Code form that alters or restricts the applicable version
        +    of this License or the recipients' rights hereunder.  You may
        +    choose to offer, and to charge a fee for, warranty, support,
        +    indemnity or liability obligations to one or more recipients of
        +    Covered Software.  However, you may do so only on Your own behalf,
        +    and not on behalf of the Initial Developer or any Contributor.
        +    You must make it absolutely clear that any such warranty, support,
        +    indemnity or liability obligation is offered by You alone, and You
        +    hereby agree to indemnify the Initial Developer and every
        +    Contributor for any liability incurred by the Initial Developer or
        +    such Contributor as a result of warranty, support, indemnity or
        +    liability terms You offer.
        +
        +    3.5. Distribution of Executable Versions.
        +
        +    You may distribute the Executable form of the Covered Software
        +    under the terms of this License or under the terms of a license of
        +    Your choice, which may contain terms different from this License,
        +    provided that You are in compliance with the terms of this License
        +    and that the license for the Executable form does not attempt to
        +    limit or alter the recipient's rights in the Source Code form from
        +    the rights set forth in this License.  If You distribute the
        +    Covered Software in Executable form under a different license, You
        +    must make it absolutely clear that any terms which differ from
        +    this License are offered by You alone, not by the Initial
        +    Developer or Contributor.  You hereby agree to indemnify the
        +    Initial Developer and every Contributor for any liability incurred
        +    by the Initial Developer or such Contributor as a result of any
        +    such terms You offer.
        +
        +    3.6. Larger Works.
        +
        +    You may create a Larger Work by combining Covered Software with
        +    other code not governed by the terms of this License and
        +    distribute the Larger Work as a single product.  In such a case,
        +    You must make sure the requirements of this License are fulfilled
        +    for the Covered Software.
        +
        +4. Versions of the License.
        +
        +    4.1. New Versions.
        +
        +    Sun Microsystems, Inc. is the initial license steward and may
        +    publish revised and/or new versions of this License from time to
        +    time.  Each version will be given a distinguishing version number.
        +    Except as provided in Section 4.3, no one other than the license
        +    steward has the right to modify this License.
        +
        +    4.2. Effect of New Versions.
        +
        +    You may always continue to use, distribute or otherwise make the
        +    Covered Software available under the terms of the version of the
        +    License under which You originally received the Covered Software.
        +    If the Initial Developer includes a notice in the Original
        +    Software prohibiting it from being distributed or otherwise made
        +    available under any subsequent version of the License, You must
        +    distribute and make the Covered Software available under the terms
        +    of the version of the License under which You originally received
        +    the Covered Software.  Otherwise, You may also choose to use,
        +    distribute or otherwise make the Covered Software available under
        +    the terms of any subsequent version of the License published by
        +    the license steward.
        +
        +    4.3. Modified Versions.
        +
        +    When You are an Initial Developer and You want to create a new
        +    license for Your Original Software, You may create and use a
        +    modified version of this License if You: (a) rename the license
        +    and remove any references to the name of the license steward
        +    (except to note that the license differs from this License); and
        +    (b) otherwise make it clear that the license contains terms which
        +    differ from this License.
        +
        +5. DISCLAIMER OF WARRANTY.
        +
        +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
        +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
        +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
        +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
        +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
        +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
        +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
        +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
        +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
        +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
        +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
        +    DISCLAIMER.
        +
        +6. TERMINATION.
        +
        +    6.1. This License and the rights granted hereunder will terminate
        +    automatically if You fail to comply with terms herein and fail to
        +    cure such breach within 30 days of becoming aware of the breach.
        +    Provisions which, by their nature, must remain in effect beyond
        +    the termination of this License shall survive.
        +
        +    6.2. If You assert a patent infringement claim (excluding
        +    declaratory judgment actions) against Initial Developer or a
        +    Contributor (the Initial Developer or Contributor against whom You
        +    assert such claim is referred to as "Participant") alleging that
        +    the Participant Software (meaning the Contributor Version where
        +    the Participant is a Contributor or the Original Software where
        +    the Participant is the Initial Developer) directly or indirectly
        +    infringes any patent, then any and all rights granted directly or
        +    indirectly to You by such Participant, the Initial Developer (if
        +    the Initial Developer is not the Participant) and all Contributors
        +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
        +    notice from Participant terminate prospectively and automatically
        +    at the expiration of such 60 day notice period, unless if within
        +    such 60 day period You withdraw Your claim with respect to the
        +    Participant Software against such Participant either unilaterally
        +    or pursuant to a written agreement with Participant.
        +
        +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
        +    all end user licenses that have been validly granted by You or any
        +    distributor hereunder prior to termination (excluding licenses
        +    granted to You by any distributor) shall survive termination.
        +
        +7. LIMITATION OF LIABILITY.
        +
        +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
        +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
        +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
        +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
        +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
        +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
        +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
        +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
        +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
        +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
        +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
        +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
        +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
        +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
        +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
        +    APPLY TO YOU.
        +
        +8. U.S. GOVERNMENT END USERS.
        +
        +    The Covered Software is a "commercial item," as that term is
        +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
        +    computer software" (as that term is defined at 48
        +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
        +    documentation" as such terms are used in 48 C.F.R. 12.212
        +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
        +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
        +    U.S. Government End Users acquire Covered Software with only those
        +    rights set forth herein.  This U.S. Government Rights clause is in
        +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
        +    provision that addresses Government rights in computer software
        +    under this License.
        +
        +9. MISCELLANEOUS.
        +
        +    This License represents the complete agreement concerning subject
        +    matter hereof.  If any provision of this License is held to be
        +    unenforceable, such provision shall be reformed only to the extent
        +    necessary to make it enforceable.  This License shall be governed
        +    by the law of the jurisdiction specified in a notice contained
        +    within the Original Software (except to the extent applicable law,
        +    if any, provides otherwise), excluding such jurisdiction's
        +    conflict-of-law provisions.  Any litigation relating to this
        +    License shall be subject to the jurisdiction of the courts located
        +    in the jurisdiction and venue specified in a notice contained
        +    within the Original Software, with the losing party responsible
        +    for costs, including, without limitation, court costs and
        +    reasonable attorneys' fees and expenses.  The application of the
        +    United Nations Convention on Contracts for the International Sale
        +    of Goods is expressly excluded.  Any law or regulation which
        +    provides that the language of a contract shall be construed
        +    against the drafter shall not apply to this License.  You agree
        +    that You alone are responsible for compliance with the United
        +    States export administration regulations (and the export control
        +    laws and regulation of any other countries) when You use,
        +    distribute or otherwise make available any Covered Software.
        +
        +10. RESPONSIBILITY FOR CLAIMS.
        +
        +    As between Initial Developer and the Contributors, each party is
        +    responsible for claims and damages arising, directly or
        +    indirectly, out of its utilization of rights under this License
        +    and You agree to work with Initial Developer and Contributors to
        +    distribute such responsibility on an equitable basis.  Nothing
        +    herein is intended or shall be deemed to constitute any admission
        +    of liability.
        +
        +--------------------------------------------------------------------
        +
        +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
        +DISTRIBUTION LICENSE (CDDL)
        +
        +For Covered Software in this distribution, this License shall
        +be governed by the laws of the State of California (excluding
        +conflict-of-law provisions).
        +
        +Any litigation relating to this License shall be subject to the
        +jurisdiction of the Federal Courts of the Northern District of
        +California and the state courts of the State of California, with
        +venue lying in Santa Clara County, California.
         
      • Community Data License Agreement Permissive 2.0

        Used by:

        # Community Data License Agreement - Permissive - Version 2.0
         
        @@ -11472,9 +14832,9 @@ insights.
                         

        ISC License

        Used by:

        -
        /* Copyright (c) 2018, Google Inc.
        +                
        /* Copyright (c) 2014, Intel Corporation.
          *
          * Permission to use, copy, modify, and/or distribute this software for any
          * purpose with or without fee is hereby granted, provided that the above
        @@ -11488,15 +14848,65 @@ insights.
          * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
         
        -#include <openssl/crypto.h>
        +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
         
        -#include <gtest/gtest.h>
        +#include "../../limbs/limbs.h"
        +
        +#define P384_LIMBS (384u / LIMB_BITS)
        +
        +typedef struct {
        +  Limb X[P384_LIMBS];
        +  Limb Y[P384_LIMBS];
        +  Limb Z[P384_LIMBS];
        +} P384_POINT;
        +
        +typedef struct {
        +  Limb X[P384_LIMBS];
        +  Limb Y[P384_LIMBS];
        +} P384_POINT_AFFINE;
         
         
        -TEST(SelfTests, KAT) {
        -#if !defined(_MSC_VER)
        -  EXPECT_TRUE(BORINGSSL_self_test());
        -#endif
        +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2015-2016 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! EdDSA Signatures.
        +
        +use super::ops::ELEM_LEN;
        +use crate::digest;
        +
        +pub mod signing;
        +pub mod verification;
        +
        +/// The length of an Ed25519 public key.
        +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
        +
        +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
        +    let mut ctx = digest::Context::new(&digest::SHA512);
        +    ctx.update(signature_r);
        +    ctx.update(public_key);
        +    ctx.update(msg);
        +    ctx.finish()
         }
         
      • @@ -11526,29 +14936,44 @@ TEST(SelfTests, KAT) {

        ISC License

        Used by:

        -
        // Copyright 2021 Brian Smith.
        +                
        // Copyright 2015-2022 Brian Smith.
         //
         // Permission to use, copy, modify, and/or distribute this software for any
         // purpose with or without fee is hereby granted, provided that the above
         // copyright notice and this permission notice appear in all copies.
         //
        -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
         // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
        -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
        -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
        -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
        -#[test]
        -fn cert_without_extensions_test() {
        -    // Check the certificate is valid with
        -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
        -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
        +use crate::limb::Limb;
         
        -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
        +#[derive(Clone, Copy)]
        +#[repr(transparent)]
        +pub struct N0([Limb; 2]);
        +
        +impl N0 {
        +    #[cfg(feature = "alloc")]
        +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
        +
        +    #[inline]
        +    pub const fn precalculated(n0: u64) -> Self {
        +        #[cfg(target_pointer_width = "64")]
        +        {
        +            Self([n0, 0])
        +        }
        +
        +        #[cfg(target_pointer_width = "32")]
        +        {
        +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
        +        }
        +    }
         }
         
        @@ -11556,21 +14981,372 @@ fn cert_without_extensions_test() {

        ISC License

        Used by:

        -
        Copyright (c) 2017 Adam Wick
        +                
        // Copyright 2015-2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
        -Permission to use, copy, modify, and/or distribute this software for any purpose
        -with or without fee is hereby granted, provided that the above copyright notice
        -and this permission notice appear in all copies.
        +use crate::{bb, error};
         
        -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
        -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
        -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
        -THIS SOFTWARE.
        +#[deprecated(
        +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
        +)]
        +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
        +    bb::verify_slices_are_equal(a, b)
        +}
        +
        + +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2016 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Elliptic curve operations and schemes using Curve25519.
        +
        +pub mod ed25519;
        +
        +pub mod x25519;
        +
        +mod ops;
        +mod scalar;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2016-2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +use crate::error::{KeyRejected, Unspecified};
        +
        +impl From<untrusted::EndOfInput> for Unspecified {
        +    fn from(source: untrusted::EndOfInput) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +impl From<core::array::TryFromSliceError> for Unspecified {
        +    fn from(source: core::array::TryFromSliceError) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +impl From<KeyRejected> for Unspecified {
        +    fn from(source: KeyRejected) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2018 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Serialization and deserialization.
        +
        +#[doc(hidden)]
        +pub mod der;
        +
        +#[cfg(feature = "alloc")]
        +mod writer;
        +
        +#[cfg(feature = "alloc")]
        +pub(crate) mod der_writer;
        +
        +pub(crate) mod positive;
        +
        +pub use self::positive::Positive;
        +
        +#[cfg(feature = "alloc")]
        +pub(crate) use self::writer::TooLongError;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2019-2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +use super::BlockLen;
        +
        +pub(super) use self::{
        +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
        +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
        +};
        +
        +pub(super) const CHAINING_WORDS: usize = 8;
        +
        +#[cfg(any(
        +    all(target_arch = "aarch64", target_endian = "little"),
        +    all(target_arch = "arm", target_endian = "little"),
        +    target_arch = "x86_64"
        +))]
        +#[macro_use]
        +mod ffi;
        +
        +pub(super) mod fallback;
        +mod sha2_32;
        +mod sha2_64;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
        +#[allow(dead_code)]
        +#[inline(always)]
        +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
        +    r
        +}
        +
        +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
        +#[allow(dead_code)]
        +#[inline(always)]
        +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
        +    r
        +}
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Integration tests for non-public APIs.
        +
        +mod bits_tests;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +pub use self::{
        +    array::Array,
        +    base::{IndexError, Overlapping},
        +    partial_block::PartialBlock,
        +};
        +
        +mod array;
        +mod base;
        +mod partial_block;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
        +
        +pub(in super::super) mod mont;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +#![cfg(target_arch = "x86_64")]
        +
        +pub(in super::super::super) mod mont;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +mod storage;
        +
        +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +pub(super) mod aarch64;
        +pub(super) mod x86_64;
         
      • @@ -11598,7 +15374,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

        ISC License

        Used by:

        Copyright © 2015, Simonas Kazlauskas
         
        @@ -11618,7 +15394,7 @@ THIS SOFTWARE.
                         

        ISC License

        Used by:

        Except as otherwise noted, this project is licensed under the following
         (ISC-style) terms:
        @@ -11645,12 +15421,12 @@ third-party/chromium/LICENSE.
                         

        ISC License

        Used by:

        ISC License
         
         Copyright (c) 2016, Mapbox
        -Copyright (c) 2018, Tree Cricket
        +Copyright (c) 2023, Taku Fukada
         
         Permission to use, copy, modify, and/or distribute this software for any purpose
         with or without fee is hereby granted, provided that the above copyright notice
        @@ -11669,7 +15445,8 @@ THIS SOFTWARE.
                         

        ISC License

        Used by:

        ISC License:
         
        @@ -11685,7 +15462,580 @@ THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
                         

        MIT License

        Used by:

        +
                                          MIT License
        +
        +Copyright 2024 Antoine Catton
        +Copyright 2016-2024 David Tolnay
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        # 3rd Party Notices
        +
        +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
        +
        +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
        +
        +    tectonic_cfg_support is licensed under the MIT License.
        +
        +    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.
        +---
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Codegen exports used by `tonic-build`.
        +
        +pub use async_trait::async_trait;
        +pub use tokio_stream;
        +
        +pub use std::future::Future;
        +pub use std::pin::Pin;
        +pub use std::sync::Arc;
        +pub use std::task::{Context, Poll};
        +pub use tower_service::Service;
        +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
        +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
        +pub use crate::extensions::GrpcMethod;
        +pub use crate::service::interceptor::InterceptedService;
        +pub use bytes::Bytes;
        +pub use http;
        +pub use http_body::Body;
        +
        +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
        +pub type BoxStream<T> =
        +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Utilities for using Tower services with Tonic.
        +
        +pub mod interceptor;
        +pub(crate) mod layered;
        +#[cfg(feature = "router")]
        +pub(crate) mod router;
        +
        +#[doc(inline)]
        +pub use self::interceptor::{Interceptor, InterceptorLayer};
        +pub use self::layered::{LayerExt, Layered};
        +#[doc(inline)]
        +#[cfg(feature = "router")]
        +pub use self::router::{Routes, RoutesBuilder};
        +#[cfg(feature = "router")]
        +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
        +
        +pub mod recover_error;
        +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Various utilities used throughout tonic.
        +
        +// some combinations of features might cause things here not to be used
        +#![allow(dead_code)]
        +
        +pub(crate) mod base64 {
        +    use base64::{
        +        alphabet,
        +        engine::{
        +            DecodePaddingMode,
        +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
        +        },
        +    };
        +
        +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
        +        &alphabet::STANDARD,
        +        GeneralPurposeConfig::new()
        +            .with_encode_padding(true)
        +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
        +    );
        +
        +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
        +        &alphabet::STANDARD,
        +        GeneralPurposeConfig::new()
        +            .with_encode_padding(false)
        +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
        +    );
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +/// A gRPC Method info extension.
        +#[derive(Debug, Clone)]
        +pub struct GrpcMethod<'a> {
        +    service: &'a str,
        +    method: &'a str,
        +}
        +
        +impl<'a> GrpcMethod<'a> {
        +    /// Create a new `GrpcMethod` extension.
        +    #[doc(hidden)]
        +    pub fn new(service: &'a str, method: &'a str) -> Self {
        +        Self { service, method }
        +    }
        +
        +    /// gRPC service name
        +    pub fn service(&self) -> &str {
        +        self.service
        +    }
        +    /// gRPC method name
        +    pub fn method(&self) -> &str {
        +        self.method
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +mod add_origin;
        +use self::add_origin::AddOrigin;
        +
        +mod user_agent;
        +use self::user_agent::UserAgent;
        +
        +mod reconnect;
        +use self::reconnect::Reconnect;
        +
        +mod connection;
        +pub(super) use self::connection::Connection;
        +
        +mod discover;
        +pub use self::discover::Change;
        +pub(super) use self::discover::DynamicServiceStream;
        +
        +mod io;
        +use self::io::BoxedIo;
        +
        +mod connector;
        +pub(crate) use self::connector::Connector;
        +
        +mod executor;
        +pub(super) use self::executor::{Executor, SharedExec};
        +
        +#[cfg(feature = "_tls-any")]
        +mod tls;
        +#[cfg(feature = "_tls-any")]
        +pub(super) use self::tls::TlsConnector;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +mod io;
        +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
        +
        +#[cfg(feature = "_tls-any")]
        +mod tls;
        +#[cfg(feature = "_tls-any")]
        +pub(crate) use self::tls::TlsAcceptor;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +pub(crate) mod grpc_timeout;
        +#[cfg(feature = "_tls-any")]
        +pub(crate) mod tls;
        +
        +pub(crate) use self::grpc_timeout::GrpcTimeout;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +use crate::transport::channel::BoxFuture;
        +use hyper_util::rt::TokioExecutor;
        +use std::{future::Future, sync::Arc};
        +
        +pub(crate) use hyper::rt::Executor;
        +
        +#[derive(Clone)]
        +pub(crate) struct SharedExec {
        +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
        +}
        +
        +impl SharedExec {
        +    pub(crate) fn new<E>(exec: E) -> Self
        +    where
        +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
        +    {
        +        Self {
        +            inner: Arc::new(exec),
        +        }
        +    }
        +
        +    pub(crate) fn tokio() -> Self {
        +        Self::new(TokioExecutor::new())
        +    }
        +}
        +
        +impl<F> Executor<F> for SharedExec
        +where
        +    F: Future<Output = ()> + Send + 'static,
        +{
        +    fn execute(&self, fut: F) {
        +        self.inner.execute(Box::pin(fut))
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +use super::Connected;
        +use std::sync::Arc;
        +
        +/// Connection info for Unix domain socket streams.
        +///
        +/// This type will be accessible through [request extensions][ext] if you're using
        +/// a unix stream.
        +///
        +/// See [Connected] for more details.
        +///
        +/// [ext]: crate::Request::extensions
        +#[derive(Clone, Debug)]
        +pub struct UdsConnectInfo {
        +    /// Peer address. This will be "unnamed" for client unix sockets.
        +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
        +    /// Process credentials for the unix socket.
        +    pub peer_cred: Option<tokio::net::unix::UCred>,
        +}
        +
        +impl Connected for tokio::net::UnixStream {
        +    type ConnectInfo = UdsConnectInfo;
        +
        +    fn connect_info(&self) -> Self::ConnectInfo {
        +        UdsConnectInfo {
        +            peer_addr: self.peer_addr().ok().map(Arc::new),
        +            peer_cred: self.peer_cred().ok(),
        +        }
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        // Copyright (c) 2019 Nuclear Furnace
        +//
        +// 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
         
        @@ -11712,7 +16062,7 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2014 Carl Lerche and other MIO contributors
         
        @@ -11739,7 +16089,6 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2014-2019 Geoffroy Couprie
        @@ -11768,9 +16117,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2014-2021 Sean McArthur
        +                
        Copyright (c) 2014-2026 Sean McArthur
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -11795,34 +16144,8 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2014-2025 Sean McArthur
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2015 Jonathan Reem
         
        @@ -11855,34 +16178,7 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2015 fangyuanziti
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2015 steffengy
         
        @@ -11897,16 +16193,27 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES
                         

        MIT License

        Used by:

        -
        Copyright (c) 2016 Paul Masurel
        +                
        Copyright (c) 2017 Gilad Naaman
         
        -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:
        +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 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.
        -
        +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.
      • MIT License

        @@ -11942,8 +16249,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

        MIT License

        Used by:

        Copyright (c) 2017 h2 authors
         
        @@ -11976,7 +16282,7 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2018 Carl Lerche
         
        @@ -12009,52 +16315,34 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2018 Paul Masurel
        +                
        Copyright (c) 2018 Tom Parker-Shemilt
         
        -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:
        +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 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.
        -
        +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.
      • MIT License

        Used by:

        -
        Copyright (c) 2018 by Quickwit, Inc. 
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2018-2019 Sean McArthur
         
        @@ -12145,7 +16433,7 @@ DEALINGS IN THE SOFTWARE.
                         

        Used by:

        Copyright (c) 2019 Carl Lerche
         
        @@ -12232,44 +16520,13 @@ SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019 Hyper Contributors
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2019 Tokio Contributors
         
        @@ -12304,7 +16561,7 @@ DEALINGS IN THE SOFTWARE.
                         
                         
        Copyright (c) 2019 Tower Contributors
         
        @@ -12337,10 +16594,9 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019-2021 Tower Contributors
        +                
        Copyright (c) 2019 axum Contributors
         
         Permission is hereby granted, free of charge, to any
         person obtaining a copy of this software and associated
        @@ -12371,9 +16627,10 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
        +                
        Copyright (c) 2019-2021 Tower Contributors
         
         Permission is hereby granted, free of charge, to any
         person obtaining a copy of this software and associated
        @@ -12437,7 +16694,68 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        +
        Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright (c) 2021 Metrics Contributors
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Copyright (c) 2023-2025 Sean McArthur
         
        @@ -12458,36 +16776,6 @@ 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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2024 by Quickwit Inc.
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2024-Present Paul Masurel
        -
        -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.
         
      • @@ -12495,6 +16783,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

        Used by:

        Copyright 2016 Nika Layzell
         
        @@ -12502,6 +16791,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         
         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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2019 gRPC authors.
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2020 David Koloski
        +
        +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.
         
      • @@ -12524,25 +16855,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

        MIT License

        Used by:

        -
        Includes portions of humantime
        -Copyright (c) 2016 The humantime Developers
        +                
        Copyright 2021 David Koloski
         
         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.
        -
        -
         
      • MIT License

        Used by:

        +
        Copyright 2023 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2023 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2024 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12565,6 +16944,65 @@ 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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2016 Michael Ma
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2016 fengcen
        +Copyright (c) 2019 svartalf
        +
        +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.
        +
      • MIT License

        @@ -12687,9 +17125,41 @@ SOFTWARE.

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2017 Sam Rijs
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12748,7 +17218,36 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2018 sgodwincs
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12777,7 +17276,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -12806,36 +17305,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        -
        MIT License
        -
        -Copyright (c) 2019 Aeledfyr
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        MIT License
         
        @@ -12864,8 +17334,37 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2019 Kornel
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12894,7 +17393,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -12948,6 +17447,40 @@ 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.
         
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2019–2025 axum Contributors
        +
        +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.
      • MIT License

        @@ -12982,11 +17515,30 @@ SOFTWARE.

        MIT License

        Used by:

        MIT License
         
        -Copyright (c) 2020 David Purdum
        +Copyright (c) 2020 Katharos Technology
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020 Scripta Qumranica Electronica
        +
        +Created by Bronson Brown-deVost
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13011,13 +17563,11 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        -Copyright (c) 2020 Scripta Qumranica Electronica
        -
        -Created by Bronson Brown-deVost
        +Copyright (c) 2020 magiclen.org (Ron Li)
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13058,6 +17608,93 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020-2022 Oliver Margetts
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020-2026 Nugine
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2021 Adel Prokurov
        +
        +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
        @@ -13087,6 +17724,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2022 Arthur Silva
        +
        +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
        @@ -13101,6 +17767,7 @@ SOFTWARE.
                         

        Used by:

        MIT License
         
        @@ -13116,6 +17783,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2022 Jeroen Van Der Donckt
        +
        +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
        @@ -13157,7 +17853,36 @@ SOFTWARE.

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2022 sarah
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13186,8 +17911,8 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13216,8 +17941,66 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2023 sarah
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2024 Spire Team
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13241,30 +18024,64 @@ 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.
         
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2025 rutrum
        +
        +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.
      • MIT License

        Used by:

        MIT License
        @@ -13291,9 +18108,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13322,7 +18139,99 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) [2021] [Marvin Countryman]
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Permission is hereby granted, free of charge, to any person obtaining
         a copy of this software and associated documentation files (the
        @@ -13348,37 +18257,39 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        The MIT License (MIT)
        +                
        Portions of this project are derived from atty, which bears the following
        +copyright notice and permission notice:
         
        -Copyright (c) 2014 Benjamin Sago
        -Copyright (c) 2021-2022 The Nushell Project Developers
        +Copyright (c) 2015-2019 Doug Tangren
         
        -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:
        +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 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.
        +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.
         
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13401,13 +18312,63 @@ 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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Mathijs van de Nes
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Y. T. CHUNG
        +
        +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.
        +
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13435,21 +18396,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        The MIT License (MIT)
         
        -Copyright (c) 2015 Andrew Gallant
        +Copyright (c) 2015 
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13458,28 +18409,39 @@ 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 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.
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
         
      • MIT License

        Used by:

        The MIT License (MIT)
         
         Copyright (c) 2015 Andrew Gallant
        -Copyright (c) 2019 Paul Masurel
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13529,6 +18491,36 @@ 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.
         
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Carl Lerche + nix-rust Authors
        +
        +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.
         
      • @@ -13560,6 +18552,64 @@ 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. +
      • + +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Gerd Zellweger
        +
        +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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Guillaume Gomez
        +
        +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.
        +
         
      • @@ -13595,11 +18645,72 @@ SOFTWARE.

        MIT License

        Used by:

        The MIT License (MIT)
         
        -Copyright (c) 2015 Vincent Prouillet
        +Copyright (c) 2015 Markus Westerlind
        +
        +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.
        +
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Michael Sproul
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015-2020 the fiat-crypto authors (see
        +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13624,7 +18735,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13640,6 +18751,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2016 nabijaczleweli
        +
        +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
        @@ -13713,8 +18853,36 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        The MIT License (MIT)
        +
        +Copyright (c) 2019 Simon Heath
        +
        +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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        The MIT License (MIT)
         
        @@ -13781,6 +18949,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Benjamin Sago
        +Copyright (c) 2021-2022 The Nushell Project 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.
         
      • @@ -13845,8 +19043,9 @@ SOFTWARE.
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13899,6 +19098,387 @@ 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.
        +
        + +
      • +

        Mozilla Public License 2.0

        +

        Used by:

        + +
        Mozilla Public License Version 2.0
        +==================================
        +
        +1. Definitions
        +--------------
        +
        +1.1. "Contributor"
        +    means each individual or legal entity that creates, contributes to
        +    the creation of, or owns Covered Software.
        +
        +1.2. "Contributor Version"
        +    means the combination of the Contributions of others (if any) used
        +    by a Contributor and that particular Contributor's Contribution.
        +
        +1.3. "Contribution"
        +    means Covered Software of a particular Contributor.
        +
        +1.4. "Covered Software"
        +    means Source Code Form to which the initial Contributor has attached
        +    the notice in Exhibit A, the Executable Form of such Source Code
        +    Form, and Modifications of such Source Code Form, in each case
        +    including portions thereof.
        +
        +1.5. "Incompatible With Secondary Licenses"
        +    means
        +
        +    (a) that the initial Contributor has attached the notice described
        +        in Exhibit B to the Covered Software; or
        +
        +    (b) that the Covered Software was made available under the terms of
        +        version 1.1 or earlier of the License, but not also under the
        +        terms of a Secondary License.
        +
        +1.6. "Executable Form"
        +    means any form of the work other than Source Code Form.
        +
        +1.7. "Larger Work"
        +    means a work that combines Covered Software with other material, in 
        +    a separate file or files, that is not Covered Software.
        +
        +1.8. "License"
        +    means this document.
        +
        +1.9. "Licensable"
        +    means having the right to grant, to the maximum extent possible,
        +    whether at the time of the initial grant or subsequently, any and
        +    all of the rights conveyed by this License.
        +
        +1.10. "Modifications"
        +    means any of the following:
        +
        +    (a) any file in Source Code Form that results from an addition to,
        +        deletion from, or modification of the contents of Covered
        +        Software; or
        +
        +    (b) any new file in Source Code Form that contains any Covered
        +        Software.
        +
        +1.11. "Patent Claims" of a Contributor
        +    means any patent claim(s), including without limitation, method,
        +    process, and apparatus claims, in any patent Licensable by such
        +    Contributor that would be infringed, but for the grant of the
        +    License, by the making, using, selling, offering for sale, having
        +    made, import, or transfer of either its Contributions or its
        +    Contributor Version.
        +
        +1.12. "Secondary License"
        +    means either the GNU General Public License, Version 2.0, the GNU
        +    Lesser General Public License, Version 2.1, the GNU Affero General
        +    Public License, Version 3.0, or any later versions of those
        +    licenses.
        +
        +1.13. "Source Code Form"
        +    means the form of the work preferred for making modifications.
        +
        +1.14. "You" (or "Your")
        +    means an individual or a legal entity exercising rights under this
        +    License. For legal entities, "You" includes any entity that
        +    controls, is controlled by, or is under common control with You. For
        +    purposes of this definition, "control" means (a) the power, direct
        +    or indirect, to cause the direction or management of such entity,
        +    whether by contract or otherwise, or (b) ownership of more than
        +    fifty percent (50%) of the outstanding shares or beneficial
        +    ownership of such entity.
        +
        +2. License Grants and Conditions
        +--------------------------------
        +
        +2.1. Grants
        +
        +Each Contributor hereby grants You a world-wide, royalty-free,
        +non-exclusive license:
        +
        +(a) under intellectual property rights (other than patent or trademark)
        +    Licensable by such Contributor to use, reproduce, make available,
        +    modify, display, perform, distribute, and otherwise exploit its
        +    Contributions, either on an unmodified basis, with Modifications, or
        +    as part of a Larger Work; and
        +
        +(b) under Patent Claims of such Contributor to make, use, sell, offer
        +    for sale, have made, import, and otherwise transfer either its
        +    Contributions or its Contributor Version.
        +
        +2.2. Effective Date
        +
        +The licenses granted in Section 2.1 with respect to any Contribution
        +become effective for each Contribution on the date the Contributor first
        +distributes such Contribution.
        +
        +2.3. Limitations on Grant Scope
        +
        +The licenses granted in this Section 2 are the only rights granted under
        +this License. No additional rights or licenses will be implied from the
        +distribution or licensing of Covered Software under this License.
        +Notwithstanding Section 2.1(b) above, no patent license is granted by a
        +Contributor:
        +
        +(a) for any code that a Contributor has removed from Covered Software;
        +    or
        +
        +(b) for infringements caused by: (i) Your and any other third party's
        +    modifications of Covered Software, or (ii) the combination of its
        +    Contributions with other software (except as part of its Contributor
        +    Version); or
        +
        +(c) under Patent Claims infringed by Covered Software in the absence of
        +    its Contributions.
        +
        +This License does not grant any rights in the trademarks, service marks,
        +or logos of any Contributor (except as may be necessary to comply with
        +the notice requirements in Section 3.4).
        +
        +2.4. Subsequent Licenses
        +
        +No Contributor makes additional grants as a result of Your choice to
        +distribute the Covered Software under a subsequent version of this
        +License (see Section 10.2) or under the terms of a Secondary License (if
        +permitted under the terms of Section 3.3).
        +
        +2.5. Representation
        +
        +Each Contributor represents that the Contributor believes its
        +Contributions are its original creation(s) or it has sufficient rights
        +to grant the rights to its Contributions conveyed by this License.
        +
        +2.6. Fair Use
        +
        +This License is not intended to limit any rights You have under
        +applicable copyright doctrines of fair use, fair dealing, or other
        +equivalents.
        +
        +2.7. Conditions
        +
        +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
        +in Section 2.1.
        +
        +3. Responsibilities
        +-------------------
        +
        +3.1. Distribution of Source Form
        +
        +All distribution of Covered Software in Source Code Form, including any
        +Modifications that You create or to which You contribute, must be under
        +the terms of this License. You must inform recipients that the Source
        +Code Form of the Covered Software is governed by the terms of this
        +License, and how they can obtain a copy of this License. You may not
        +attempt to alter or restrict the recipients' rights in the Source Code
        +Form.
        +
        +3.2. Distribution of Executable Form
        +
        +If You distribute Covered Software in Executable Form then:
        +
        +(a) such Covered Software must also be made available in Source Code
        +    Form, as described in Section 3.1, and You must inform recipients of
        +    the Executable Form how they can obtain a copy of such Source Code
        +    Form by reasonable means in a timely manner, at a charge no more
        +    than the cost of distribution to the recipient; and
        +
        +(b) You may distribute such Executable Form under the terms of this
        +    License, or sublicense it under different terms, provided that the
        +    license for the Executable Form does not attempt to limit or alter
        +    the recipients' rights in the Source Code Form under this License.
        +
        +3.3. Distribution of a Larger Work
        +
        +You may create and distribute a Larger Work under terms of Your choice,
        +provided that You also comply with the requirements of this License for
        +the Covered Software. If the Larger Work is a combination of Covered
        +Software with a work governed by one or more Secondary Licenses, and the
        +Covered Software is not Incompatible With Secondary Licenses, this
        +License permits You to additionally distribute such Covered Software
        +under the terms of such Secondary License(s), so that the recipient of
        +the Larger Work may, at their option, further distribute the Covered
        +Software under the terms of either this License or such Secondary
        +License(s).
        +
        +3.4. Notices
        +
        +You may not remove or alter the substance of any license notices
        +(including copyright notices, patent notices, disclaimers of warranty,
        +or limitations of liability) contained within the Source Code Form of
        +the Covered Software, except that You may alter any license notices to
        +the extent required to remedy known factual inaccuracies.
        +
        +3.5. Application of Additional Terms
        +
        +You may choose to offer, and to charge a fee for, warranty, support,
        +indemnity or liability obligations to one or more recipients of Covered
        +Software. However, You may do so only on Your own behalf, and not on
        +behalf of any Contributor. You must make it absolutely clear that any
        +such warranty, support, indemnity, or liability obligation is offered by
        +You alone, and You hereby agree to indemnify every Contributor for any
        +liability incurred by such Contributor as a result of warranty, support,
        +indemnity or liability terms You offer. You may include additional
        +disclaimers of warranty and limitations of liability specific to any
        +jurisdiction.
        +
        +4. Inability to Comply Due to Statute or Regulation
        +---------------------------------------------------
        +
        +If it is impossible for You to comply with any of the terms of this
        +License with respect to some or all of the Covered Software due to
        +statute, judicial order, or regulation then You must: (a) comply with
        +the terms of this License to the maximum extent possible; and (b)
        +describe the limitations and the code they affect. Such description must
        +be placed in a text file included with all distributions of the Covered
        +Software under this License. Except to the extent prohibited by statute
        +or regulation, such description must be sufficiently detailed for a
        +recipient of ordinary skill to be able to understand it.
        +
        +5. Termination
        +--------------
        +
        +5.1. The rights granted under this License will terminate automatically
        +if You fail to comply with any of its terms. However, if You become
        +compliant, then the rights granted under this License from a particular
        +Contributor are reinstated (a) provisionally, unless and until such
        +Contributor explicitly and finally terminates Your grants, and (b) on an
        +ongoing basis, if such Contributor fails to notify You of the
        +non-compliance by some reasonable means prior to 60 days after You have
        +come back into compliance. Moreover, Your grants from a particular
        +Contributor are reinstated on an ongoing basis if such Contributor
        +notifies You of the non-compliance by some reasonable means, this is the
        +first time You have received notice of non-compliance with this License
        +from such Contributor, and You become compliant prior to 30 days after
        +Your receipt of the notice.
        +
        +5.2. If You initiate litigation against any entity by asserting a patent
        +infringement claim (excluding declaratory judgment actions,
        +counter-claims, and cross-claims) alleging that a Contributor Version
        +directly or indirectly infringes any patent, then the rights granted to
        +You by any and all Contributors for the Covered Software under Section
        +2.1 of this License shall terminate.
        +
        +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
        +end user license agreements (excluding distributors and resellers) which
        +have been validly granted by You or Your distributors under this License
        +prior to termination shall survive termination.
        +
        +************************************************************************
        +*                                                                      *
        +*  6. Disclaimer of Warranty                                           *
        +*  -------------------------                                           *
        +*                                                                      *
        +*  Covered Software is provided under this License on an "as is"       *
        +*  basis, without warranty of any kind, either expressed, implied, or  *
        +*  statutory, including, without limitation, warranties that the       *
        +*  Covered Software is free of defects, merchantable, fit for a        *
        +*  particular purpose or non-infringing. The entire risk as to the     *
        +*  quality and performance of the Covered Software is with You.        *
        +*  Should any Covered Software prove defective in any respect, You     *
        +*  (not any Contributor) assume the cost of any necessary servicing,   *
        +*  repair, or correction. This disclaimer of warranty constitutes an   *
        +*  essential part of this License. No use of any Covered Software is   *
        +*  authorized under this License except under this disclaimer.         *
        +*                                                                      *
        +************************************************************************
        +
        +************************************************************************
        +*                                                                      *
        +*  7. Limitation of Liability                                          *
        +*  --------------------------                                          *
        +*                                                                      *
        +*  Under no circumstances and under no legal theory, whether tort      *
        +*  (including negligence), contract, or otherwise, shall any           *
        +*  Contributor, or anyone who distributes Covered Software as          *
        +*  permitted above, be liable to You for any direct, indirect,         *
        +*  special, incidental, or consequential damages of any character      *
        +*  including, without limitation, damages for lost profits, loss of    *
        +*  goodwill, work stoppage, computer failure or malfunction, or any    *
        +*  and all other commercial damages or losses, even if such party      *
        +*  shall have been informed of the possibility of such damages. This   *
        +*  limitation of liability shall not apply to liability for death or   *
        +*  personal injury resulting from such party's negligence to the       *
        +*  extent applicable law prohibits such limitation. Some               *
        +*  jurisdictions do not allow the exclusion or limitation of           *
        +*  incidental or consequential damages, so this exclusion and          *
        +*  limitation may not apply to You.                                    *
        +*                                                                      *
        +************************************************************************
        +
        +8. Litigation
        +-------------
        +
        +Any litigation relating to this License may be brought only in the
        +courts of a jurisdiction where the defendant maintains its principal
        +place of business and such litigation shall be governed by laws of that
        +jurisdiction, without reference to its conflict-of-law provisions.
        +Nothing in this Section shall prevent a party's ability to bring
        +cross-claims or counter-claims.
        +
        +9. Miscellaneous
        +----------------
        +
        +This License represents the complete agreement concerning the subject
        +matter hereof. If any provision of this License is held to be
        +unenforceable, such provision shall be reformed only to the extent
        +necessary to make it enforceable. Any law or regulation which provides
        +that the language of a contract shall be construed against the drafter
        +shall not be used to construe this License against a Contributor.
        +
        +10. Versions of the License
        +---------------------------
        +
        +10.1. New Versions
        +
        +Mozilla Foundation is the license steward. Except as provided in Section
        +10.3, no one other than the license steward has the right to modify or
        +publish new versions of this License. Each version will be given a
        +distinguishing version number.
        +
        +10.2. Effect of New Versions
        +
        +You may distribute the Covered Software under the terms of the version
        +of the License under which You originally received the Covered Software,
        +or under the terms of any subsequent version published by the license
        +steward.
        +
        +10.3. Modified Versions
        +
        +If you create software not governed by this License, and you want to
        +create a new license for such software, you may create and use a
        +modified version of this License if you rename the license and remove
        +any references to the name of the license steward (except to note that
        +such modified license differs from this License).
        +
        +10.4. Distributing Source Code Form that is Incompatible With Secondary
        +Licenses
        +
        +If You choose to distribute Source Code Form that is Incompatible With
        +Secondary Licenses under the terms of this version of the License, the
        +notice described in Exhibit B of this License must be attached.
        +
        +Exhibit A - Source Code Form License Notice
        +-------------------------------------------
        +
        +  This Source Code Form is subject to the terms of the Mozilla Public
        +  License, v. 2.0. If a copy of the MPL was not distributed with this
        +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
        +
        +If it is not possible or desirable to put the notice in a particular
        +file, then You may include the notice in a location (such as a LICENSE
        +file in a relevant directory) where a recipient would be likely to look
        +for such a notice.
        +
        +You may add additional accurate notices of copyright ownership.
        +
        +Exhibit B - "Incompatible With Secondary Licenses" Notice
        +---------------------------------------------------------
        +
        +  This Source Code Form is "Incompatible With Secondary Licenses", as
        +  defined by the Mozilla Public License, v. 2.0.
         
      • @@ -14280,187 +19860,13 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. -
      • - -
      • -

        OpenSSL License

        -

        Used by:

        - -
        /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
        - * All rights reserved.
        - *
        - * This package is an SSL implementation written
        - * by Eric Young (eay@cryptsoft.com).
        - * The implementation was written so as to conform with Netscapes SSL.
        - *
        - * This library is free for commercial and non-commercial use as long as
        - * the following conditions are aheared to.  The following conditions
        - * apply to all code found in this distribution, be it the RC4, RSA,
        - * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
        - * included with this distribution is covered by the same copyright terms
        - * except that the holder is Tim Hudson (tjh@cryptsoft.com).
        - *
        - * Copyright remains Eric Young's, and as such any Copyright notices in
        - * the code are not to be removed.
        - * If this package is used in a product, Eric Young should be given attribution
        - * as the author of the parts of the library used.
        - * This can be in the form of a textual message at program startup or
        - * in documentation (online or textual) provided with the package.
        - *
        - * Redistribution and use in source and binary forms, with or without
        - * modification, are permitted provided that the following conditions
        - * are met:
        - * 1. Redistributions of source code must retain the copyright
        - *    notice, this list of conditions and the following disclaimer.
        - * 2. Redistributions in binary form must reproduce the above copyright
        - *    notice, this list of conditions and the following disclaimer in the
        - *    documentation and/or other materials provided with the distribution.
        - * 3. All advertising materials mentioning features or use of this software
        - *    must display the following acknowledgement:
        - *    "This product includes cryptographic software written by
        - *     Eric Young (eay@cryptsoft.com)"
        - *    The word 'cryptographic' can be left out if the rouines from the library
        - *    being used are not cryptographic related :-).
        - * 4. If you include any Windows specific code (or a derivative thereof) from
        - *    the apps directory (application code) you must include an acknowledgement:
        - *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
        - *
        - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
        - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
        - * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
        - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
        - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
        - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
        - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
        - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
        - * SUCH DAMAGE.
        - *
        - * The licence and distribution terms for any publically available version or
        - * derivative of this code cannot be changed.  i.e. this code cannot simply be
        - * copied and put under another distribution licence
        - * [including the GNU Public Licence.]
        - */
        -/* ====================================================================
        - * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
        - *
        - * Redistribution and use in source and binary forms, with or without
        - * modification, are permitted provided that the following conditions
        - * are met:
        - *
        - * 1. Redistributions of source code must retain the above copyright
        - *    notice, this list of conditions and the following disclaimer.
        - *
        - * 2. Redistributions in binary form must reproduce the above copyright
        - *    notice, this list of conditions and the following disclaimer in
        - *    the documentation and/or other materials provided with the
        - *    distribution.
        - *
        - * 3. All advertising materials mentioning features or use of this
        - *    software must display the following acknowledgment:
        - *    "This product includes software developed by the OpenSSL Project
        - *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
        - *
        - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
        - *    endorse or promote products derived from this software without
        - *    prior written permission. For written permission, please contact
        - *    openssl-core@openssl.org.
        - *
        - * 5. Products derived from this software may not be called "OpenSSL"
        - *    nor may "OpenSSL" appear in their names without prior written
        - *    permission of the OpenSSL Project.
        - *
        - * 6. Redistributions of any form whatsoever must retain the following
        - *    acknowledgment:
        - *    "This product includes software developed by the OpenSSL Project
        - *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
        - *
        - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
        - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        - * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
        - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
        - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
        - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
        - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
        - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
        - * OF THE POSSIBILITY OF SUCH DAMAGE.
        - * ====================================================================
        - *
        - * This product includes cryptographic software written by Eric Young
        - * (eay@cryptsoft.com).  This product includes software written by Tim
        - * Hudson (tjh@cryptsoft.com).
        - *
        - */
        -
        -#include <openssl/ssl.h>
        -
        -#if !defined(OPENSSL_WINDOWS) && !defined(OPENSSL_PNACL) && \
        -    !defined(OPENSSL_NO_FILESYSTEM)
        -
        -#include <dirent.h>
        -#include <errno.h>
        -#include <string.h>
        -
        -#include <openssl/err.h>
        -#include <openssl/mem.h>
        -
        -
        -int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
        -                                       const char *path) {
        -  DIR *dir = opendir(path);
        -  if (dir == NULL) {
        -    OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
        -    ERR_add_error_data(3, "opendir('", dir, "')");
        -    return 0;
        -  }
        -
        -  int ret = 0;
        -  for (;;) {
        -    // |readdir| may fail with or without setting |errno|.
        -    errno = 0;
        -    struct dirent *dirent = readdir(dir);
        -    if (dirent == NULL) {
        -      if (errno) {
        -        OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
        -        ERR_add_error_data(3, "readdir('", path, "')");
        -      } else {
        -        ret = 1;
        -      }
        -      break;
        -    }
        -
        -    char buf[1024];
        -    if (strlen(path) + strlen(dirent->d_name) + 2 > sizeof(buf)) {
        -      OPENSSL_PUT_ERROR(SSL, SSL_R_PATH_TOO_LONG);
        -      break;
        -    }
        -
        -    int r = snprintf(buf, sizeof(buf), "%s/%s", path, dirent->d_name);
        -    if (r <= 0 ||
        -        r >= (int)sizeof(buf) ||
        -        !SSL_add_file_cert_subjects_to_stack(stack, buf)) {
        -      break;
        -    }
        -  }
        -
        -  closedir(dir);
        -  return ret;
        -}
        -
        -#endif  // !WINDOWS && !PNACL && !OPENSSL_NO_FILESYSTEM
         
      • Unicode License v3

        Used by:

        UNICODE LICENSE V3
         
        @@ -14507,24 +19913,28 @@ authorization of the copyright holder.
                         

        Unicode License v3

        Used by:

        UNICODE LICENSE V3
         
        @@ -14573,12 +19983,63 @@ SPDX-License-Identifier: Unicode-3.0
         Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
         ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
         
        +
      • +
      • +

        zlib License

        +

        Used by:

        + +
        Copyright (c) 2021 Matias Rodriguez.
        +
        +This software is provided 'as-is', without any express or implied
        +warranty. In no event will the authors be held liable for any damages
        +arising from the use of this software.
        +
        +Permission is granted to anyone to use this software for any purpose,
        +including commercial applications, and to alter it and redistribute it
        +freely, subject to the following restrictions:
        +
        +1. The origin of this software must not be misrepresented; you must not
        +   claim that you wrote the original software. If you use this software
        +   in a product, an acknowledgment in the product documentation would be
        +   appreciated but is not required.
        +2. Altered source versions must be plainly marked as such, and must not be
        +   misrepresented as being the original software.
        +3. This notice may not be removed or altered from any source distribution.
        +
      • +
      • +

        zlib License

        +

        Used by:

        + +
        Copyright (c) 2023 Matias Rodriguez.
        +
        +This software is provided 'as-is', without any express or implied
        +warranty. In no event will the authors be held liable for any damages
        +arising from the use of this software.
        +
        +Permission is granted to anyone to use this software for any purpose,
        +including commercial applications, and to alter it and redistribute it
        +freely, subject to the following restrictions:
        +
        +1. The origin of this software must not be misrepresented; you must not
        +   claim that you wrote the original software. If you use this software
        +   in a product, an acknowledgment in the product documentation would be
        +   appreciated but is not required.
        +2. Altered source versions must be plainly marked as such, and must not be
        +   misrepresented as being the original software.
        +3. This notice may not be removed or altered from any source distribution.
      • zlib License

        Used by:

        Copyright (c) 2024 Orson Peters
         
        diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts
        index 376533961..27dd14954 100644
        --- a/nodejs/__test__/arrow.test.ts
        +++ b/nodejs/__test__/arrow.test.ts
        @@ -1567,11 +1567,17 @@ describe.each(arrowVersions)("Arrow %#", (arrow: ApacheArrow) => {
               const records = [
                 { text: "dog", vector: [0.1, 0.2] },
                 { text: "cat", vector: [0.3, 0.4] },
        +        { text: null, vector: null },
               ];
        -      const table = await convertToTable(records);
        +      const table = arrow.tableFromArrays({
        +        text: records.map((row) => row.text),
        +        vector: records.map((row) => row.vector),
        +      });
               const batch = table.batches[0];
         
        -      const buffer = await fromRecordBatchToBuffer(batch);
        +      const buffer = await fromRecordBatchToBuffer(
        +        batch as Parameters[0],
        +      );
               const result = await fromBufferToRecordBatch(buffer);
         
               expect(JSON.stringify(batch.toArray())).toEqual(
        diff --git a/nodejs/__test__/blob_open.test.ts b/nodejs/__test__/blob_open.test.ts
        new file mode 100644
        index 000000000..34d1c764c
        --- /dev/null
        +++ b/nodejs/__test__/blob_open.test.ts
        @@ -0,0 +1,257 @@
        +// SPDX-License-Identifier: Apache-2.0
        +// SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import { createServer } from "node:http";
        +import type { AddressInfo } from "node:net";
        +import {
        +  type BlobDescriptor,
        +  type Connection,
        +  type Table,
        +  connect,
        +} from "../lancedb";
        +
        +jest.setTimeout(15000);
        +
        +const IDENTITY = `v1:${"a".repeat(64)}`;
        +const MIB = 1024 * 1024;
        +
        +function descriptor(size: bigint): BlobDescriptor {
        +  return {
        +    kind: 2,
        +    position: 0n,
        +    size,
        +    // biome-ignore lint/style/useNamingConvention: Matches the descriptor.
        +    blob_id: 1,
        +    // biome-ignore lint/style/useNamingConvention: Matches the descriptor.
        +    blob_uri: "",
        +    source: {
        +      uri: "s3://fixture/table.lance",
        +      version: 46n,
        +      // biome-ignore lint/style/useNamingConvention: Matches the descriptor.
        +      committed_at_micros: 1795627189287568n,
        +      branch: null,
        +      column: "image",
        +      // biome-ignore lint/style/useNamingConvention: Matches the descriptor.
        +      row_reference: 0n,
        +      // biome-ignore lint/style/useNamingConvention: Matches the descriptor.
        +      row_is_address: false,
        +    },
        +  };
        +}
        +
        +async function readBody(req: import("node:http").IncomingMessage) {
        +  const chunks: Buffer[] = [];
        +  for await (const chunk of req) {
        +    chunks.push(chunk as Buffer);
        +  }
        +  return Buffer.concat(chunks).toString();
        +}
        +
        +async function withOpenServer(
        +  run: (
        +    db: Connection,
        +    table: Table,
        +    state: {
        +      directStatus: number;
        +      blobLocationsCalls: number;
        +      objectCalls: number;
        +      proxyCalls: number;
        +      lastLocationBody: Record | undefined;
        +    },
        +  ) => Promise,
        +  size: bigint = 10n * BigInt(MIB),
        +) {
        +  let port = 0;
        +  const state = {
        +    directStatus: 200,
        +    blobLocationsCalls: 0,
        +    objectCalls: 0,
        +    proxyCalls: 0,
        +    lastLocationBody: undefined as Record | undefined,
        +  };
        +  const payload = Buffer.alloc(Number(size), 0x61);
        +  const server = createServer(async (req, res) => {
        +    const url = req.url ?? "";
        +    if (url === "/v1/table/test/describe/") {
        +      res.writeHead(200, {
        +        "content-type": "application/json",
        +        "phalanx-version": "1.15.0-beta.0",
        +        "x-lancedb-blob-locations": "1",
        +      });
        +      res.end(JSON.stringify({ version: 46, schema: { fields: [] } }));
        +      return;
        +    }
        +    if (url === "/v1/table/test/blob_locations/") {
        +      state.blobLocationsCalls++;
        +      const body = JSON.parse(await readBody(req)) as Record;
        +      state.lastLocationBody = body;
        +      if (state.directStatus !== 200) {
        +        res.writeHead(state.directStatus).end("resolver unavailable");
        +        return;
        +      }
        +      res.writeHead(200, {
        +        "content-type": "application/json",
        +        "x-lancedb-version": "46",
        +        "x-lancedb-query-snapshot": IDENTITY,
        +      });
        +      res.end(
        +        JSON.stringify({
        +          sources: [
        +            {
        +              url: `http://127.0.0.1:${port}/object?signature=test`,
        +              // biome-ignore lint/style/useNamingConvention: Matches the resolver response.
        +              expires_at_unix_secs: 4102444800,
        +            },
        +          ],
        +          items: [
        +            {
        +              kind: "presigned",
        +              // biome-ignore lint/style/useNamingConvention: Matches the resolver response.
        +              source_index: 0,
        +              offset: 0,
        +              size: Number(size),
        +            },
        +          ],
        +        }),
        +      );
        +      return;
        +    }
        +    if (url.startsWith("/object")) {
        +      state.objectCalls++;
        +      const range = req.headers.range ?? "";
        +      const match = /^bytes=(\d+)-(\d+)$/.exec(range);
        +      if (match === null) {
        +        res.writeHead(416).end();
        +        return;
        +      }
        +      const start = Number(match[1]);
        +      const end = Number(match[2]);
        +      const body = payload.subarray(start, end + 1);
        +      res.writeHead(206, {
        +        "content-range": `bytes ${start}-${end}/${size}`,
        +        "content-length": body.length,
        +        "x-lancedb-version": "46",
        +        "x-lancedb-query-snapshot": IDENTITY,
        +        connection: "close",
        +      });
        +      res.end(body);
        +      return;
        +    }
        +    if (url.startsWith("/v1/table/test/blob/image/0/bytes")) {
        +      state.proxyCalls++;
        +      const range = req.headers.range ?? "";
        +      const match = /^bytes=(\d+)-(\d+)$/.exec(range);
        +      if (match === null) {
        +        res.writeHead(416).end();
        +        return;
        +      }
        +      const start = Number(match[1]);
        +      const end = Number(match[2]);
        +      const body = payload.subarray(start, end + 1);
        +      res.writeHead(206, {
        +        "content-range": `bytes ${start}-${end}/${size}`,
        +        "content-length": body.length,
        +        "x-lancedb-version": "46",
        +        "x-lancedb-query-snapshot": IDENTITY,
        +        connection: "close",
        +      });
        +      res.end(body);
        +      return;
        +    }
        +    res.writeHead(404).end(`unexpected request: ${req.method} ${url}`);
        +  });
        +  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
        +  port = (server.address() as AddressInfo).port;
        +  const db = await connect("db://dev", {
        +    apiKey: "fake",
        +    hostOverride: `http://127.0.0.1:${port}`,
        +    clientConfig: { timeoutConfig: { timeout: 10 } },
        +  });
        +  const table = await db.openTable("test");
        +  try {
        +    await run(db, table, state);
        +  } finally {
        +    await new Promise((resolve) => {
        +      server.closeAllConnections();
        +      server.close(() => resolve());
        +    });
        +  }
        +}
        +
        +describe("openBlobFile", () => {
        +  it("opens a large descriptor through the direct resolver and reads bytes", async () => {
        +    await withOpenServer(async (_db, table, state) => {
        +      const handle = (await table.openBlobFile(descriptor(10n * BigInt(MIB))))!;
        +      expect(handle).not.toBeNull();
        +      // Below the per-read threshold the same handle stays on the proxy.
        +      expect(await handle.readRange(0n, 4n)).toEqual(Buffer.alloc(4, 0x61));
        +      expect(state.proxyCalls).toBe(1);
        +      expect(state.objectCalls).toBe(0);
        +      const large = await handle.readRange(0n, 10n * BigInt(MIB));
        +      expect(large.length).toBe(10 * MIB);
        +      expect(large.equals(Buffer.alloc(10 * MIB, 0x61))).toBe(true);
        +      expect(state.blobLocationsCalls).toBe(1);
        +      expect(state.objectCalls).toBe(1);
        +      expect(state.proxyCalls).toBe(1);
        +      expect(state.lastLocationBody).toMatchObject({
        +        version: 46,
        +        // biome-ignore lint/style/useNamingConvention: Matches the resolver body.
        +        row_ids: [0],
        +        // biome-ignore lint/style/useNamingConvention: Matches the resolver body.
        +        source_uri: "s3://fixture/table.lance",
        +        // biome-ignore lint/style/useNamingConvention: Matches the resolver body.
        +        source_commit_micros: 1795627189287568,
        +        // biome-ignore lint/style/useNamingConvention: Matches the resolver body.
        +        row_is_address: false,
        +      });
        +      await handle.close();
        +    });
        +  });
        +
        +  it("falls back to the proxy when the resolver returns 503", async () => {
        +    await withOpenServer(async (_db, table, state) => {
        +      state.directStatus = 503;
        +      const handle = (await table.openBlobFile(descriptor(10n * BigInt(MIB))))!;
        +      expect(handle).not.toBeNull();
        +      const large = await handle.readRange(0n, 10n * BigInt(MIB));
        +      expect(large.length).toBe(10 * MIB);
        +      expect(large.equals(Buffer.alloc(10 * MIB, 0x61))).toBe(true);
        +      expect(state.blobLocationsCalls).toBe(1);
        +      expect(state.objectCalls).toBe(0);
        +      expect(state.proxyCalls).toBe(1);
        +      await handle.close();
        +    });
        +  });
        +
        +  it("keeps descriptors below the direct threshold on the proxy path", async () => {
        +    await withOpenServer(async (_db, table, state) => {
        +      const handle = (await table.openBlobFile(descriptor(BigInt(MIB))))!;
        +      expect(await handle.readRange(0n, 4n)).toEqual(Buffer.alloc(4, 0x61));
        +      expect(state.blobLocationsCalls).toBe(0);
        +      expect(state.objectCalls).toBe(0);
        +      expect(state.proxyCalls).toBe(1);
        +      await handle.close();
        +    }, BigInt(MIB));
        +  });
        +
        +  it("preserves nulls and order in openBlobFiles", async () => {
        +    await withOpenServer(async (_db, table, state) => {
        +      const handles = [];
        +      for await (const handle of table.openBlobFiles([
        +        null,
        +        descriptor(10n * BigInt(MIB)),
        +        null,
        +      ])) {
        +        handles.push(handle);
        +      }
        +      expect(handles[0]).toBeNull();
        +      expect(handles[1]).not.toBeNull();
        +      expect(handles[2]).toBeNull();
        +      expect(await handles[1]!.readRange(0n, 4n)).toEqual(
        +        Buffer.alloc(4, 0x61),
        +      );
        +      expect(state.blobLocationsCalls).toBe(1);
        +      await handles[1]!.close();
        +    });
        +  });
        +});
        diff --git a/nodejs/__test__/blob_ranges.test.ts b/nodejs/__test__/blob_ranges.test.ts
        new file mode 100644
        index 000000000..9e7b0e53d
        --- /dev/null
        +++ b/nodejs/__test__/blob_ranges.test.ts
        @@ -0,0 +1,644 @@
        +// SPDX-License-Identifier: Apache-2.0
        +// SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import { createHash } from "crypto";
        +import { getEventListeners } from "events";
        +import { createReadStream } from "fs";
        +import * as http from "http";
        +import { AddressInfo } from "net";
        +import {
        +  Table as ArrowTable,
        +  Binary,
        +  Field,
        +  LargeBinary,
        +  Struct,
        +  Uint8,
        +  Uint32,
        +  Uint64,
        +  Utf8,
        +  tableToIPC,
        +  vectorFromArray,
        +} from "apache-arrow";
        +import { BlobRangeRequest, Connection, Table, connect } from "../lancedb";
        +
        +jest.setTimeout(30000);
        +
        +const IDENTITY = `v1:${"a".repeat(64)}`;
        +const MIB = 1024 * 1024;
        +type Range = {
        +  // biome-ignore lint/style/useNamingConvention: Matches the server JSON contract.
        +  row_id: number;
        +  offset: number;
        +  length: number;
        +};
        +type Request = {
        +  column: string;
        +  branch: string | null;
        +  version: number | null;
        +  ranges: Range[];
        +  identity?: string;
        +};
        +
        +function payload(row: number, offset: number, length: number, version: number) {
        +  const bytes = Buffer.alloc(length);
        +  for (let i = 0; i < length; i++) {
        +    bytes[i] = (row * 17 + ((offset + i) % 251) + version) % 251;
        +  }
        +  return bytes;
        +}
        +
        +async function withRangeServer(
        +  run: (db: Connection, calls: Request[], paths: string[]) => Promise,
        +  fault?: string | number,
        +  capability: string | null = "1",
        +  onStall?: (response: http.ServerResponse) => void,
        +) {
        +  let takes = 0;
        +  let rangeReads = 0;
        +  const calls: Request[] = [];
        +  const paths: string[] = [];
        +  const server = http.createServer((req, res) => {
        +    req.setTimeout(15000);
        +    paths.push(req.url ?? "");
        +    if (
        +      req.url === "/v1/table/test/describe/" ||
        +      req.url === "/v1/table/test/branches/list/"
        +    ) {
        +      res.writeHead(200, {
        +        "Content-Type": "application/json",
        +        "phalanx-version": "1.13.0-beta.0",
        +        ...(req.url.endsWith("/describe/") && capability !== null
        +          ? { "x-lancedb-blob-ranges": capability }
        +          : {}),
        +      });
        +      const response = req.url.endsWith("branches/list/")
        +        ? {
        +            branches: {
        +              experiment: {
        +                parentBranch: null,
        +                parentVersion: 1,
        +                createAt: 1,
        +                manifestSize: 1,
        +              },
        +            },
        +          }
        +        : { version: 8, schema: { fields: [] } };
        +      res.end(JSON.stringify(response));
        +      return;
        +    }
        +    if (capability !== "1" && req.method === "GET") {
        +      const url = new URL(req.url!, "http://localhost");
        +      expect(url.searchParams.get("branch")).toBe("experiment");
        +      expect(url.searchParams.get("version")).toBe("3");
        +      const [start, end] = req.headers.range!.slice(6).split("-").map(Number);
        +      const bytes = Buffer.from("alpha").subarray(start, end + 1);
        +      res.writeHead(206, {
        +        "Content-Range": `bytes ${start}-${end}/5`,
        +        "Content-Length": bytes.length,
        +        "x-lancedb-version": "3",
        +      });
        +      if (fault === "stall-read" && ++rangeReads === 1) {
        +        // Withhold the rest of the body so native completion cannot win the abort.
        +        res.write(bytes.subarray(0, 1));
        +        onStall?.(res);
        +        return;
        +      }
        +      res.end(bytes);
        +      return;
        +    }
        +    expect(req.method).toBe("POST");
        +    expect(req.url).toBe(
        +      capability === "1"
        +        ? "/v1/table/test/fetch_blob_ranges/"
        +        : "/v1/table/test/query/",
        +    );
        +    const chunks: Buffer[] = [];
        +    let size = 0;
        +    req.on("data", (chunk: Buffer) => {
        +      size += chunk.length;
        +      expect(size).toBeLessThanOrEqual(256 * 1024);
        +      chunks.push(chunk);
        +    });
        +    req.on("end", () => {
        +      if (capability !== "1") {
        +        const body = JSON.parse(Buffer.concat(chunks).toString()) as {
        +          branch: string;
        +          version: number;
        +          filter: string;
        +        };
        +        expect(body.branch).toBe("experiment");
        +        expect(body.version).toBe(3);
        +        takes++;
        +        const ids = (body.filter.match(/\d+/g) ?? [])
        +          .map(Number)
        +          .filter((id) => [10, 20, 40].includes(id))
        +          .reverse();
        +        const descriptor = new Struct([
        +          new Field("kind", new Uint8(), false),
        +          new Field("position", new Uint64(), false),
        +          new Field("size", new Uint64(), false),
        +          new Field("blob_id", new Uint32(), false),
        +          new Field("blob_uri", new Utf8(), false),
        +        ]);
        +        const arrow = new ArrowTable({
        +          image: vectorFromArray(
        +            ids.map((id) =>
        +              id === 20
        +                ? null
        +                : {
        +                    kind: 0,
        +                    position: 0n,
        +                    size: id === 40 ? 0n : 5n,
        +                    // biome-ignore lint/style/useNamingConvention: Arrow descriptor field.
        +                    blob_id: 0,
        +                    // biome-ignore lint/style/useNamingConvention: Arrow descriptor field.
        +                    blob_uri: "",
        +                  },
        +            ),
        +            descriptor,
        +          ),
        +          _rowid: vectorFromArray(ids.map(BigInt), new Uint64()),
        +        });
        +        expect(takes).toBeGreaterThan(0);
        +        res
        +          .writeHead(200, {
        +            "Content-Type": "application/vnd.apache.arrow.stream",
        +            "x-lancedb-version": "3",
        +          })
        +          .end(tableToIPC(arrow, "stream"));
        +        return;
        +      }
        +      const body = JSON.parse(Buffer.concat(chunks).toString()) as Request;
        +      body.identity = req.headers["x-lancedb-query-snapshot"] as
        +        | string
        +        | undefined;
        +      calls.push(body);
        +      expect(body.column).toBe("image");
        +      expect(body.branch).toBe("experiment");
        +      expect(body.ranges.length).toBeLessThanOrEqual(1024);
        +      expect(
        +        body.ranges.reduce((sum, range) => sum + range.length, 0),
        +      ).toBeLessThanOrEqual(64 * MIB);
        +      const version = body.version ?? (calls.length === 1 ? 7 : 8);
        +      const failure =
        +        calls.length > 1 || String(fault).startsWith("first-")
        +          ? fault
        +          : undefined;
        +      if (failure === "recreated" || failure === "gone") {
        +        res
        +          .writeHead(failure === "recreated" ? 400 : 404)
        +          .end("query snapshot identity mismatch: source gone or replaced");
        +        return;
        +      }
        +      if (failure === "stall" && calls.length === 2) {
        +        res.writeHead(200, {
        +          "Content-Type": "application/vnd.apache.arrow.stream",
        +          "x-lancedb-version": "7",
        +          "x-lancedb-query-snapshot": IDENTITY,
        +        });
        +        res.flushHeaders();
        +        onStall?.(res);
        +        return;
        +      }
        +      if (typeof failure === "number") {
        +        res.writeHead(failure).end("ordinary server failure");
        +        return;
        +      }
        +      if (failure === "disconnect") {
        +        req.socket.destroy();
        +        return;
        +      }
        +      let values = body.ranges.map((range) =>
        +        range.row_id === 20
        +          ? null
        +          : payload(range.row_id, range.offset, range.length, version),
        +      );
        +      if (failure === "count") values = [];
        +      if (failure === "length") values = [Buffer.alloc(0)];
        +      const arrow = new ArrowTable({
        +        [failure === "column" ? "wrong" : "value"]: vectorFromArray(
        +          values,
        +          failure === "type" ? new Binary() : new LargeBinary(),
        +        ),
        +      });
        +      let ipc = tableToIPC(arrow, "stream");
        +      if (failure === "eos") ipc = ipc.subarray(0, ipc.length - 8);
        +      if (failure === "body") ipc = ipc.subarray(0, Math.floor(ipc.length / 2));
        +      res.writeHead(200, {
        +        "Content-Type": "application/vnd.apache.arrow.stream",
        +        connection: "close",
        +        "Content-Length": ipc.length + (failure === "transport" ? 10 : 0),
        +        ...(failure === "version" ? {} : { "x-lancedb-version": version }),
        +        ...(["missing-identity", "first-missing-identity"].includes(
        +          String(failure),
        +        )
        +          ? {}
        +          : {
        +              "x-lancedb-query-snapshot":
        +                failure === "wrong-identity"
        +                  ? `v1:${"b".repeat(64)}`
        +                  : failure === "first-invalid-identity"
        +                    ? "broken"
        +                    : IDENTITY,
        +            }),
        +      });
        +      // Fragment the generated IPC payload across actual HTTP writes.
        +      for (let i = 0; i < ipc.length; i += 8192)
        +        res.write(ipc.subarray(i, i + 8192));
        +      res.end();
        +    });
        +  });
        +  server.listen(0, "127.0.0.1");
        +  await new Promise((resolve) => server.once("listening", resolve));
        +  const port = (server.address() as AddressInfo).port;
        +  const db = await connect("db://dev", {
        +    apiKey: "fake",
        +    hostOverride: `http://127.0.0.1:${port}`,
        +    clientConfig: {
        +      retryConfig: { retries: 2, connectRetries: 2, readRetries: 2 },
        +      blobRequestConcurrency: 1,
        +      timeoutConfig: { timeout: 20 },
        +    },
        +  });
        +  try {
        +    await run(db, calls, paths);
        +  } finally {
        +    await new Promise((resolve) => {
        +      server.closeAllConnections();
        +      server.close(() => resolve());
        +    });
        +  }
        +}
        +
        +async function open(db: Connection, version?: number): Promise
    • { + return db.openTable("test", [], { branch: "experiment", version }); +} + +describe("fetchBlobRanges", () => { + it.each([null, "0", "2"])( + "uses old routes before data requests for capability %s", + async (capability) => { + await withRangeServer( + async (db, calls, paths) => { + // Reopening exercises both the initial and cached database describe paths. + for (let i = 0; i < 2; i++) { + const table = await open(db, 3); + const requests = [ + { rowId: 10n, offset: 1n, length: 3n }, + { rowId: 20n, offset: 0n, length: 1n }, + { rowId: 40n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 5n, length: 0n }, + { rowId: 10n, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("lph"), + null, + Buffer.alloc(0), + Buffer.alloc(0), + Buffer.from("lph"), + ]); + for (const row of [ + { rowId: 10n, offset: 4n, length: 2n }, + { rowId: 99n, offset: 0n, length: 1n }, + ]) + await expect( + table.fetchBlobRanges("image", [row]), + ).rejects.toThrow(); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + expect(paths).toHaveLength(before); + } + expect(calls).toHaveLength(0); + expect(paths.some((path) => path.includes("fetch_blob_ranges"))).toBe( + false, + ); + }, + undefined, + capability, + ); + }, + ); + + it("renegotiates advertised support when reopening a cached table", async () => { + await withRangeServer(async (db, calls) => { + for (let i = 0; i < 2; i++) { + const table = await open(db); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, i === 0 ? 7 : 8)]); + } + expect(calls).toHaveLength(2); + }); + }); + + it("cancels an in-flight BlobFile read and leaves the handle usable", async () => { + let responseTimedOut = false; + let markStalled!: () => void; + const stalled = new Promise((resolve) => { + markStalled = resolve; + }); + let markDisconnected!: () => void; + const disconnected = new Promise((resolve) => { + markDisconnected = resolve; + }); + await withRangeServer( + async (db) => { + const table = await open(db, 3); + const [handle] = await table.fetchBlobFiles("image", [10n]); + const controller = new AbortController(); + try { + const pending = handle!.readRange(0n, handle!.size(), { + signal: controller.signal, + }); + const rejected = expect(pending).rejects.toMatchObject({ + name: "AbortError", + }); + await stalled; + controller.abort(); + await rejected; + await disconnected; + expect(responseTimedOut).toBe(false); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + expect(handle!.isClosed()).toBe(false); + expect(await handle!.tell()).toBe(0n); + // The single request permit must also be released by cancellation. + expect(await handle!.readRange(0n, 5n)).toEqual(Buffer.from("alpha")); + } finally { + controller.abort(); + await handle!.close(); + } + }, + "stall-read", + null, + (response) => { + response.once("timeout", () => { + responseTimedOut = true; + }); + response.once("close", markDisconnected); + markStalled(); + }, + ); + }); + + it("cancels while waiting for a later response body and releases the only permit", async () => { + let markStalled!: () => void; + const stalled = new Promise((resolve) => { + markStalled = resolve; + }); + await withRangeServer( + async (db, calls) => { + const table = await open(db); + const controller = new AbortController(); + const pending = table.fetchBlobRanges( + "image", + Array.from({ length: 2049 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + { signal: controller.signal }, + ); + const rejected = expect(pending).rejects.toMatchObject({ + name: "AbortError", + }); + await stalled; + controller.abort(); + await rejected; + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + expect(calls).toHaveLength(2); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, 8)]); + expect(calls).toHaveLength(3); + }, + "stall", + "1", + () => markStalled(), + ); + }); + it.each([undefined, 3])( + "preserves order, nulls, duplicates and snapshot (checkout %s)", + async (version) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db, version); + const requests: BlobRangeRequest[] = Array.from( + { length: 1025 }, + (_, i) => ({ + rowId: i % 9 === 0 ? 20 : 10 + (i % 7), + offset: BigInt(i), + length: BigInt(i % 4), + }), + ); + requests.push( + { rowId: 10n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 2n, length: 3n }, + { rowId: 10n, offset: 2n, length: 3n }, + ); + const result = await table.fetchBlobRanges("image", requests); + expect(result).toEqual( + requests.map((range) => + Number(range.rowId) === 20 + ? null + : payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + version ?? 7, + ), + ), + ); + expect(calls.map((body) => body.version)).toEqual([ + version ?? null, + version ?? 7, + ]); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, version ?? 8)]); + expect(calls[2].version).toBe(version ?? null); + expect( + paths.filter((path) => path.endsWith("fetch_blob_ranges/")), + ).toHaveLength(3); + }); + }, + ); + + it("partitions the byte budget and reassembles one range larger than 64 MiB", async () => { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = [ + { rowId: 10n, offset: 3n, length: BigInt(65 * MIB) }, + { rowId: 30n, offset: 7n, length: 2n }, + ]; + const result = await table.fetchBlobRanges("image", requests); + for (const [i, range] of requests.entries()) { + expect(result[i]?.length).toBe(Number(range.length)); + expect( + createHash("sha256") + .update(result[i] as Buffer) + .digest("hex"), + ).toBe( + createHash("sha256") + .update( + payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + 7, + ), + ) + .digest("hex"), + ); + } + expect(calls).toHaveLength(2); + expect(calls.map((body) => body.version)).toEqual([null, 7]); + }); + }); + + it.each([ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ])("rejects the whole call after a later %s failure", async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(); + expect(calls).toHaveLength(2); + expect( + paths.every( + (path) => + path.endsWith("describe/") || + path.endsWith("branches/list/") || + path.endsWith("fetch_blob_ranges/"), + ), + ).toBe(true); + }, fault); + }); + + it.each(["missing-identity", "wrong-identity", "recreated", "gone"])( + "retains original identity through row and byte partitions (%s)", + async (fault) => { + for (const huge of [false, true]) { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = huge + ? [{ rowId: 10n, offset: 0n, length: BigInt(64 * MIB + 1) }] + : Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })); + await expect( + table.fetchBlobRanges("image", requests), + ).rejects.toThrow(); + expect(calls.map((call) => call.identity)).toEqual([ + undefined, + IDENTITY, + ]); + expect(calls.map((call) => call.version)).toEqual([null, 7]); + }, fault); + } + }, + ); + + it.each(["first-missing-identity", "first-invalid-identity"])( + "requires a first authoritative bulk identity (%s)", + async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(/snapshot identity/); + expect(calls).toHaveLength(1); + expect(paths).toHaveLength(before + 1); + }, fault); + }, + ); + + it("validates integers, overflow and cancellation and leaves empty calls at zero I/O", async () => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + for (const request of [ + { rowId: -1, offset: 0n, length: 1n }, + { rowId: 1.5, offset: 0n, length: 1n }, + { rowId: Number.MAX_SAFE_INTEGER + 1, offset: 0n, length: 1n }, + { rowId: -1n, offset: 0n, length: 1n }, + { rowId: 1n << 64n, offset: 0n, length: 1n }, + { rowId: 10n, offset: -1n, length: 1n }, + { rowId: 10n, offset: 0n, length: -1n }, + { rowId: 10n, offset: 0n, length: 1n << 64n }, + { rowId: 20n, offset: (1n << 64n) - 1n, length: 1n }, + ]) { + await expect( + table.fetchBlobRanges("image", [request]), + ).rejects.toThrow(); + } + // Runtime type validation must also reject a number passed as an offset. + await expect( + table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0 as unknown as bigint, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + controller.abort(new Error("cancelled by caller")); + await expect( + table.fetchBlobRanges( + "image", + [{ rowId: 10n, offset: 0n, length: 1n }], + { signal: controller.signal }, + ), + ).rejects.toThrow("cancelled by caller"); + expect(paths).toHaveLength(before); + expect(calls).toHaveLength(0); + }); + }); + + it("records the loaded native artifact", async () => { + const artifacts = Object.keys(require.cache).filter( + (path) => path.endsWith(".node") && path.includes("lancedb"), + ); + expect(artifacts.length).toBeGreaterThan(0); + for (const path of artifacts) { + const hash = createHash("sha256"); + for await (const chunk of createReadStream(path)) hash.update(chunk); + console.log( + `loaded native artifact=${path} sha256=${hash.digest("hex")}`, + ); + } + }); +}); diff --git a/nodejs/__test__/cleanup.test.ts b/nodejs/__test__/cleanup.test.ts new file mode 100644 index 000000000..8c68f833a --- /dev/null +++ b/nodejs/__test__/cleanup.test.ts @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + type CleanupOptions, + decodeCleanupPlan, + decodeCleanupResult, + validateCleanupOptions, +} from "../lancedb/cleanup"; + +test.each([null, [], 1, true, "options"])( + "cleanup rejects malformed options instead of inheriting retention (%p)", + (options) => { + expect(() => + validateCleanupOptions(options as unknown as CleanupOptions), + ).toThrow("cleanup options must be an object"); + }, +); + +test("cleanup never silently discards an unknown option", () => { + expect(() => + validateCleanupOptions({ force: true } as unknown as CleanupOptions), + ).toThrow("Unknown cleanup option"); +}); + +test.each([undefined, 0, 604800])( + "cleanup retention accepts omission and explicit zero (%s)", + (age) => { + expect(() => validateCleanupOptions({ minAgeSeconds: age })).not.toThrow(); + }, +); + +test.each([ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, +])("cleanup retention rejects invalid values (%s)", (age) => { + expect(() => validateCleanupOptions({ minAgeSeconds: age })).toThrow(); +}); + +test.each([0, 2, null])( + "cleanup results distinguish known zero and unknown (%s)", + (count) => { + const result = decodeCleanupResult( + JSON.parse( + JSON.stringify({ + ["format_version"]: 1, + ["min_age_seconds"]: 0, + ["statistics_complete"]: count !== null, + ["old_versions"]: count, + ["bytes_removed"]: count, + future: "ignored", + }), + ), + ); + expect(result.oldVersions).toBe(count); + }, +); + +test.each([ + null, + {}, + { ["format_version"]: 2 }, + { + ["format_version"]: 1, + ["min_age_seconds"]: 0, + ["statistics_complete"]: false, + ["old_versions"]: 1, + }, +])("cleanup rejects incompatible results (%p)", (value) => { + expect(() => decodeCleanupResult(value)).toThrow(); +}); + +test("cleanup preview validates its versioned contract", () => { + const value = JSON.parse( + '{"format_version":1,"source_version":42,"min_age_seconds":0,"cutoff_millis":-1,"versions_to_remove":2,"bytes_to_remove":100}', + ); + expect(decodeCleanupPlan(value).versionsToRemove).toBe(2); + value.format_version = 2; + expect(() => decodeCleanupPlan(value)).toThrow(); +}); diff --git a/nodejs/__test__/job.test.ts b/nodejs/__test__/job.test.ts new file mode 100644 index 000000000..31049f820 --- /dev/null +++ b/nodejs/__test__/job.test.ts @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { Job } from "../lancedb/job"; +import type { Job as NativeJob } from "../lancedb/native"; + +describe("Job attempt contract", () => { + test("preserves lineage and unknown detailed states", async () => { + const inner = { + jobId: "attempt-2", + operationId: "attempt-1", + attempt: 2, + retryOf: "attempt-1", + lifecycleState: "future_publication_state", + sourceTableVersion: 7, + executionEpoch: 3, + status: jest.fn().mockResolvedValue("future_publication_state"), + } as unknown as NativeJob; + const job = new Job(inner); + expect(job.jobId).toBe("attempt-2"); + expect(job.operationId).toBe("attempt-1"); + expect(job.attempt).toBe(2); + expect(job.retryOf).toBe("attempt-1"); + expect(await job.statusTyped()).toBe("future_publication_state"); + expect(job.sourceTableVersion).toBe(7); + expect(job.executionEpoch).toBe(3); + }); + + test("passes wait deadlines through without cancelling execution", async () => { + const wait = jest.fn().mockRejectedValue(new Error("Timeout error")); + const cancel = jest.fn(); + const job = new Job({ wait, cancel } as unknown as NativeJob); + await expect(job.wait({ timeoutMs: 1 })).rejects.toThrow("Timeout"); + expect(wait).toHaveBeenCalledWith(undefined, 1); + expect(cancel).not.toHaveBeenCalled(); + }); + test("retry retains the typed result decoder", async () => { + const successor = { + waitResult: jest.fn().mockResolvedValue({ value: 7 }), + } as unknown as NativeJob; + const inner = { + retry: jest.fn().mockResolvedValue(successor), + } as unknown as NativeJob; + const job = new Job(inner, (value) => (value as { value: number }).value); + const retry = await job.retry(); + expect(await retry.wait()).toBe(7); + }); +}); diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts index 0840395fe..00d2e40e3 100644 --- a/nodejs/__test__/materialized_view.test.ts +++ b/nodejs/__test__/materialized_view.test.ts @@ -121,7 +121,34 @@ describe("materialized views", () => { .spyOn(view.table(), "refreshMaterializedView") .mockResolvedValue(remoteResult); expect(await view.refresh({ full: true })).toEqual(remoteResult); - expect(refresh).toHaveBeenCalledWith(undefined, true); + expect(refresh).toHaveBeenCalledWith( + undefined, + true, + undefined, + undefined, + undefined, + undefined, + undefined, + ); + expect( + await view.refresh({ + full: true, + totalCpuMillis: 4000, + totalMemoryBytes: 8_000_000_000, + totalGpuCount: 4, + gpuClass: "any", + gpuCount: 2, + }), + ).toEqual(remoteResult); + expect(refresh).toHaveBeenLastCalledWith( + undefined, + true, + 4000, + 8_000_000_000, + 4, + "any", + 2, + ); }); experimentalTest("lists views and rejects non-views", async () => { diff --git a/nodejs/__test__/prewarm.test.ts b/nodejs/__test__/prewarm.test.ts new file mode 100644 index 000000000..ac6c23c22 --- /dev/null +++ b/nodejs/__test__/prewarm.test.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { decodePrewarmDataPlan } from "../lancedb/prewarm"; +import { Table } from "../lancedb/table"; + +test.each([null, 0, 2])( + "preview preserves unknown and zero range counts: %s", + (ranges) => { + const plan = decodePrewarmDataPlan( + JSON.parse(`{ + "table_version":42,"plan":"display text", + "pruning":{"mode":"future_mode","input_fragments":3,"selected_fragments":0, + "pruned_fragments":3,"selected_row_ranges":${ranges}} + }`), + ); + expect(plan.tableVersion).toBe(42); + expect(plan.pruning.mode).toBe("future_mode"); + expect(plan.pruning.selectedRowRanges).toBe(ranges); + expect(plan.pruning.fallbackReason).toBeNull(); + }, +); + +test("custom tables inherit an unsupported preview default", async () => { + // Only the inherited default is exercised; unrelated abstract operations + // do not need implementations in this fixture. + const table = Object.create(Table.prototype) as Table; + await expect( + table.explainPrewarmData({ columns: ["payload"], filter: "id > 0" }), + ).rejects.toThrow( + "data prewarm previews are not supported by this table implementation", + ); +}); diff --git a/nodejs/__test__/profiling.test.ts b/nodejs/__test__/profiling.test.ts new file mode 100644 index 000000000..5c4394025 --- /dev/null +++ b/nodejs/__test__/profiling.test.ts @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { type IncomingHttpHeaders, createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { type Connection, type FunctionProfileKind, connect } from "../lancedb"; + +type Response = { body: unknown; status?: number }; + +function metadata(kind: FunctionProfileKind, status: string) { + return { + ["profile_id"]: "profile-1", + ["job_id"]: "job-1", + ["worker_id"]: "worker-1", + ["execution_epoch"]: 3, + ["session_slot"]: 0, + kind, + ["duration_seconds"]: 2, + status, + ["requested_at_millis"]: 1000, + ["deadline_at_millis"]: 46000, + ["expires_at_millis"]: 3601000, + ["completed_at_millis"]: null, + error: status === "failed" ? "gpu_unavailable" : null, + ["artifact_id"]: status === "complete" ? "profile-1" : null, + }; +} + +const artifacts: Record> = { + cpu: { + $schema: "https://www.speedscope.app/file-format-schema.json", + shared: { frames: [{ name: "work" }] }, + profiles: [], + futureField: 7, + }, + memory: { + format: "lancedb.tracemalloc.v1", + allocations: [{ ["size_bytes"]: 4096 }], + truncated: false, + }, + gpu: { + format: "lancedb.cuda.v1", + traceEvents: [{ name: "compute", cat: "kernel", ph: "X", ts: 10, dur: 2 }], + truncated: true, + }, +}; + +async function withProfileServer( + handler: ( + path: string, + body: Record, + headers: IncomingHttpHeaders, + ) => Response, + run: (db: Connection) => Promise, +) { + let serverError: unknown; + const server = createServer(async (request, response) => { + try { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(chunk); + const bytes = Buffer.concat(chunks); + const body = bytes.length === 0 ? {} : JSON.parse(bytes.toString()); + const result = handler(request.url ?? "", body, request.headers); + response.writeHead(result.status ?? 200, { + "Content-Type": "application/json", + }); + response.end(JSON.stringify(result.body)); + } catch (error) { + serverError = error; + response.writeHead(500); + response.end("test request handler failed"); + } + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as AddressInfo).port; + try { + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${port}`, + }); + try { + await run(db); + } catch (error) { + throw serverError ?? error; + } + if (serverError) throw serverError; + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +describe("Function worker profiles", () => { + it.each( + (["cpu", "memory", "gpu"] as FunctionProfileKind[]).flatMap((kind) => + [false, true].map((submitted) => [kind, submitted] as const), + ), + )( + "captures and exports retained %s evidence (submitted handle: %s)", + async (kind, submitted) => { + let polls = 0; + let finished = false; + const paths: string[] = []; + const directory = await mkdtemp(join(tmpdir(), "lancedb-profile-")); + try { + await withProfileServer( + (path, body, headers) => { + paths.push(path); + expect(headers["x-api-key"]).toBe("fake"); + expect(headers["x-lancedb-database"]).toBe("dev"); + if (path === "/v1/table/test/describe/") + return { body: { version: 1, schema: { fields: [] } } }; + if (path === "/v1/table/test/backfill_column") { + expect(body.column).toBe("result"); + return { status: 202, body: { ["job_id"]: "job-1" } }; + } + if (path === "/v1/jobs/describe") + return { + body: { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: finished ? "DONE" : "IN_PROGRESS", + }, + }; + if (path === "/v1/jobs/profile/capture") { + expect(body).toEqual({ + ["job_id"]: "job-1", + ["worker_id"]: "worker-1", + ["session_slot"]: 0, + kind, + ["duration_seconds"]: 2, + }); + return { status: 202, body: metadata(kind, "pending") }; + } + expect(body).toEqual({ + ["job_id"]: "job-1", + ["profile_id"]: "profile-1", + }); + if (path === "/v1/jobs/profile/status") + return { + body: metadata(kind, ++polls > 1 ? "complete" : "capturing"), + }; + expect(path).toBe("/v1/jobs/profile/artifact"); + return { body: artifacts[kind] }; + }, + async (db) => { + const job = submitted + ? await (await db.openTable("test")).refreshColumnAsync("result") + : await db.openJob("job-1"); + if (submitted) await job.refresh(); + const capture = await job.captureProfile("worker-1", { + kind, + durationSeconds: 2, + }); + expect(capture).toMatchObject({ + profileId: "profile-1", + workerId: "worker-1", + executionEpoch: 3, + sessionSlot: 0, + status: "pending", + }); + const complete = await job.waitForProfile(capture.profileId, { + timeoutMs: 2000, + pollIntervalMs: 10, + }); + expect(complete.status).toBe("complete"); + expect(job.state).toBe("running"); + finished = true; + await job.refresh(); + expect(job.state).toBe("finished"); + expect(await job.profileArtifact(capture.profileId)).toEqual( + artifacts[kind], + ); + const path = join(directory, "capture.json"); + await job.exportProfile(capture.profileId, path); + expect(JSON.parse(await readFile(path, "utf8"))).toEqual( + artifacts[kind], + ); + expect( + paths.filter((path) => path === "/v1/jobs/describe"), + ).toHaveLength(2); + expect(paths.some((path) => path.endsWith("/cancel"))).toBe(false); + }, + ); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }, + ); + + it("can resume after a wait timeout without cancelling the refresh", async () => { + let complete = false; + const paths: string[] = []; + await withProfileServer( + (path) => { + paths.push(path); + if (path === "/v1/jobs/describe") + return { + body: { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: "IN_PROGRESS", + }, + }; + expect(path).toBe("/v1/jobs/profile/status"); + return { body: metadata("gpu", complete ? "complete" : "pending") }; + }, + async (db) => { + const job = await db.openJob("job-1"); + await expect( + job.waitForProfile("profile-1", { + timeoutMs: 50, + pollIntervalMs: 10, + }), + ).rejects.toThrow(/waiting for Function worker profile/); + expect(await job.status()).toBe("running"); + complete = true; + expect( + (await job.waitForProfile("profile-1", { timeoutMs: 2000 })).status, + ).toBe("complete"); + expect(paths.some((path) => path.endsWith("/cancel"))).toBe(false); + }, + ); + }); + + it("reports failed captures independently of the parent", async () => { + await withProfileServer( + (path) => ({ + body: + path === "/v1/jobs/describe" + ? { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: "IN_PROGRESS", + } + : metadata("gpu", "failed"), + }), + async (db) => { + const job = await db.openJob("job-1"); + expect(await job.profileStatus("profile-1")).toMatchObject({ + status: "failed", + error: "gpu_unavailable", + }); + await expect(job.waitForProfile("profile-1")).rejects.toThrow( + "gpu_unavailable", + ); + expect(job.state).toBe("running"); + }, + ); + }); + + it("preserves permission errors and existing export files", async () => { + const directory = await mkdtemp(join(tmpdir(), "lancedb-profile-")); + const path = join(directory, "capture.json"); + await writeFile(path, "previous capture"); + try { + await withProfileServer( + (path) => { + if (path === "/v1/jobs/describe") + return { + body: { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: "DONE", + }, + }; + if (path.endsWith("/status")) + return { body: metadata("gpu", "complete") }; + return { status: 403, body: { error: "System Operate required" } }; + }, + async (db) => { + const job = await db.openJob("job-1"); + await expect(job.exportProfile("profile-1", path)).rejects.toThrow( + "403", + ); + expect(await readFile(path, "utf8")).toBe("previous capture"); + }, + ); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it("rejects invalid options before submitting a capture", async () => { + await withProfileServer( + (path) => { + expect(path).toBe("/v1/jobs/describe"); + return { + body: { + ["job_id"]: "job-1", + ["job_type"]: "function_refresh", + ["job_state"]: "IN_PROGRESS", + }, + }; + }, + async (db) => { + const job = await db.openJob("job-1"); + for (const durationSeconds of [ + Number.NaN, + Number.POSITIVE_INFINITY, + -1, + 0, + 6, + ]) { + await expect( + job.captureProfile("worker-1", { kind: "gpu", durationSeconds }), + ).rejects.toThrow(/duration/); + } + for (const sessionSlot of [ + -1, + 0.5, + Number.NaN, + Number.MAX_SAFE_INTEGER + 1, + ]) { + await expect( + job.captureProfile("worker-1", { sessionSlot }), + ).rejects.toThrow("sessionSlot"); + } + await expect( + job.captureProfile("worker-1", { duration: 10 } as never), + ).rejects.toThrow("Unknown profiling option"); + await expect( + job.waitForProfile("profile-1", { timeoutMs: -1 }), + ).rejects.toThrow("timeoutMs"); + await expect( + job.waitForProfile("profile-1", { pollIntervalMs: 0 }), + ).rejects.toThrow("poll interval"); + }, + ); + }); +}); diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts index 068e55c2f..c0b30ac63 100644 --- a/nodejs/__test__/query.test.ts +++ b/nodejs/__test__/query.test.ts @@ -564,7 +564,8 @@ describe("IVF search effort", () => { it.each([ [null, 6], [0, 1], - [0.25, 3], + [0.1, 2], + [0.25, 4], [0.5, 6], [0.75, 10], [1, 16], diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index b11a79a67..8844afcf2 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -3,6 +3,7 @@ import * as http from "http"; import { RequestListener } from "http"; +import { tableFromArrays } from "apache-arrow"; import packageJson = require("../package.json"); import { ClientAuthMethod, @@ -309,6 +310,9 @@ describe("remote connection", () => { }, async (db) => { const table = (await db.openTable("test")) as LocalTable; + await expect(table.delta(1)).rejects.toThrow( + "table.delta is only supported on LanceDB Embedded tables", + ); const cases: [() => Promise, string][] = [ [() => table.usesV2ManifestPaths(), "uses_v2_manifest_paths"], [() => table.migrateManifestPathsV2(), "migrate_manifest_paths_v2"], @@ -483,6 +487,222 @@ describe("remote connection", () => { expect(insertRequests).toBe(2); }); + it.each([ + { status: 429, retries: undefined, attempts: 2 }, + { status: 429, retries: 0, attempts: 1 }, + { status: 504, retries: undefined, attempts: 1 }, + { status: 504, retries: 0, attempts: 1 }, + ])("applies per-call add retries: %j", async (scenario) => { + let attempts = 0; + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + expect(req.url).toContain("/insert/"); + req.resume(); + req.on("end", () => { + attempts++; + res + .writeHead(attempts === 1 ? scenario.status : 200) + .end('{"version":2}'); + }); + }, + async (db) => { + const table = await db.openTable("items"); + const result = table.add([{ id: 1n }], { retries: scenario.retries }); + if (scenario.attempts === 2) { + await expect(result).resolves.toMatchObject({ version: 2 }); + } else { + await expect(result).rejects.toThrow(); + } + for (const retries of [-1, 256, 1.5]) { + await expect(table.add([{ id: 2n }], { retries })).rejects.toThrow( + "retries must be an integer between 0 and 255", + ); + } + }, + { + clientConfig: { + retryConfig: { + retries: 3, + statuses: [429, 504], + backoffFactor: 0, + backoffJitter: 0, + }, + }, + }, + ); + expect(attempts).toBe(scenario.attempts); + }); + + it.each( + [409, 429, 502, 503, 504].flatMap((status) => + [undefined, 0, 2].flatMap((retries) => + [[], ["analytics", "features"]].map((namespacePath) => ({ + status, + retries, + namespacePath, + })), + ), + ), + )("applies per-call merge retries: %j", async (scenario) => { + let attempts = 0; + const identifier = [...scenario.namespacePath, "items"].join("$"); + const succeeds = + [409, 429].includes(scenario.status) && scenario.retries !== 0; + await withMockDatabase( + (req, res) => { + const url = new URL(req.url ?? "", "http://localhost"); + if (url.pathname === `/v1/table/${identifier}/describe/`) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + try { + expect(url.pathname).toBe(`/v1/table/${identifier}/merge_insert/`); + expect(url.searchParams.get("use_index")).toBe("false"); + expect(req.headers["x-request-timeout-ms"]).toBe("10000"); + // Rust compresses the batches; Arrow JS can inspect the schema without a codec. + const reader = RecordBatchReader.from(Buffer.concat(chunks)).open(); + expect(reader.schema.fields.map((field) => field.name)).toEqual([ + "id", + ]); + } finally { + attempts++; + res + .writeHead(attempts === 1 ? scenario.status : 200) + .end('{"version":2}'); + } + }); + }, + async (db) => { + const table = await db.openTable("items", scenario.namespacePath); + const merge = table + .mergeInsert("id") + .whenNotMatchedInsertAll() + .useIndex(false); + const result = merge.execute([{ id: 1n }], { + timeoutMs: 10_000, + retries: scenario.retries, + }); + if (succeeds) { + await expect(result).resolves.toMatchObject({ version: 2 }); + } else { + await expect(result).rejects.toThrow(); + } + }, + { + clientConfig: { + retryConfig: { + retries: 3, + statuses: [409, 429, 502, 503, 504], + backoffFactor: 0, + backoffJitter: 0, + }, + }, + }, + ); + expect(attempts).toBe(succeeds ? 2 : 1); + }); + + it("isolates merge retry overrides across reused builders and reads", async () => { + let attempts = 0; + let readAttempts = 0; + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + req.resume(); + req.on("end", () => { + if (req.url?.endsWith("/count_rows/")) { + readAttempts++; + res.writeHead(readAttempts % 2 ? 429 : 200).end("1"); + } else { + attempts++; + res + .writeHead([1, 2, 4, 6].includes(attempts) ? 429 : 200) + .end('{"version":2}'); + expect(req.url).toContain("/merge_insert/"); + } + }); + }, + async (db) => { + const table = await db.openTable("items"); + const merge = table.mergeInsert("id").whenNotMatchedInsertAll(); + for (const retries of [ + -1, + 256, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + ]) { + await expect( + merge.execute([{ id: 1n }], { retries }), + ).rejects.toThrow("retries must be an integer between 0 and 255"); + } + expect(attempts).toBe(0); + await expect( + merge.execute([{ id: 1n }], { retries: 0 }), + ).rejects.toThrow(); + expect(attempts).toBe(1); + await expect(merge.execute([{ id: 1n }])).resolves.toMatchObject({ + version: 2, + }); + await expect( + merge.execute([{ id: 1n }], { retries: 255 }), + ).resolves.toMatchObject({ version: 2 }); + expect(attempts).toBe(5); + await expect(table.countRows()).resolves.toBe(1); + expect(readAttempts).toBe(2); + await expect( + table + .mergeInsert("id") + .whenNotMatchedInsertAll() + .execute([{ id: 1n }]), + ).resolves.toMatchObject({ version: 2 }); + expect(attempts).toBe(7); + }, + { + clientConfig: { + retryConfig: { retries: 3, backoffFactor: 0, backoffJitter: 0 }, + }, + }, + ); + }); + it("should accept partial connection options", async () => { await connect("db://test", { apiKey: "fake", @@ -635,15 +855,751 @@ describe("remote connection", () => { ]); expect(errors.records[0].rowOffset).toBe(9); expect(errors.fragments[0].rowsSkipped).toBe(500); - await table.functionErrors(); + expect(errors.workflowVersion).toBeUndefined(); + expect(errors.errorGroups).toBeUndefined(); + await expect( + table.functionErrorRows({ columns: ["text"] }), + ).rejects.toThrow("Function row-failure workflow"); + await table.functionErrors({ history: false }); await expect(table.functionErrors({ limit: -1 })).rejects.toThrow( "limit must be a non-negative integer", ); + for (const operation of [ + () => table.functionErrors({ history: true }), + () => table.retryFailed("embedding"), + () => table.upgradeColumn("embedding", { version: "2" }), + () => table.quarantineFailed("embedding"), + () => table.quarantineFailed("embedding", { quarantined: false }), + () => table.functionProvenance("embedding"), + ]) { + await expect(operation()).rejects.toThrow( + "Function row-failure workflow", + ); + } }, ); expect(bodies).toEqual([ JSON.parse('{"job_id": "j-7", "column": "embedding", "limit": 2}'), {}, + {}, + ...Array.from({ length: 6 }, () => ({ limit: 1 })), + ]); + }); + + it("reads Function failure history and joins current inputs by exact row identity", async () => { + const stableId = 9_007_199_254_740_993n; + const physicalAddress = 9_007_203_549_708_297n; + const currentRows = tableFromArrays({ + text: ["physical failure", "moved stable row", "unrelated row"], + ["_rowid"]: new BigUint64Array([ + physicalAddress, + stableId, + stableId - 1n, + ]), + ["_rowaddr"]: new BigUint64Array([physicalAddress, 14n, 10n]), + }); + const records = `[ + {"job_id":"j-7", "fragment_id":0, "row_offset":10, + "row_id":${stableId}, "row_address":10, "column":"embedding", + "function":"embed", "function_version":"2", "table_version":11, + "error_type":"ValueError", "error_message":"bad input", + "created_at_millis":1700000000001, "first_seen_at_millis":1700000000000, + "last_seen_at_millis":1700000000001, "attempts":3, "quarantined":true}, + {"job_id":"j-7", "fragment_id":2097153, "row_offset":9, + "row_address":${physicalAddress}, "column":"embedding", + "function":"embed", "function_version":"2", "table_version":11, + "error_type":"ValueError", "error_message":"bad input", "created_at_millis":1700000000001}, + {"job_id":"j-8", "fragment_id":0, "row_offset":10, + "row_id":${stableId}, "row_address":10, "column":"score", + "function":"score", "function_version":"1", "table_version":11, + "error_type":"TypeError", "error_message":"bad input", "created_at_millis":1700000000001} + ]`; + const groups = `[ + {"column":"embedding", "error_type":"ValueError", "error_message":"bad input", "rows_failed":2}, + {"column":"score", "error_type":"TypeError", "error_message":"bad input", "rows_failed":1} + ]`; + const errorRequests: unknown[] = []; + const queryRequests: unknown[] = []; + await withMockDatabase( + (req, res) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + if (req.url === "/v1/table/docs/describe/") { + res.writeHead(200).end('{"version":12,"schema":{"fields":[]}}'); + } else if (req.url === "/v1/table/docs/errors") { + const request = JSON.parse(body); + errorRequests.push(request); + const empty = request.column === "empty"; + const truncated = request.limit === 2; + res.writeHead(200).end(`{ + "workflow_version":1, "records":${empty ? "[]" : records}, + "fragments":[], "truncated":${truncated}, + "error_groups":${empty ? "[]" : groups} + }`); + } else if (req.url === "/v1/table/docs/query/") { + const query = JSON.parse(body); + queryRequests.push(query); + const rows = + queryRequests.length === 1 + ? currentRows.slice(0, 2) + : currentRows.slice(0, 1); + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + }) + .end(Buffer.from(tableToIPC(rows, "stream"))); + } else { + res.writeHead(404).end(); + } + }); + }, + async (db) => { + const table = await db.openTable("docs"); + const errors = await table.functionErrors(); + expect(errors.workflowVersion).toBe(1); + expect(errors.records[0]).toMatchObject({ + rowId: stableId, + rowAddress: 10n, + attempts: 3, + firstSeenAtMillis: 1_700_000_000_000, + lastSeenAtMillis: 1_700_000_000_001, + quarantined: true, + }); + expect(errors.records[1].rowAddress).toBe(physicalAddress); + expect(errors.errorGroups).toEqual([ + { + column: "embedding", + errorType: "ValueError", + errorMessage: "bad input", + rowsFailed: 2n, + }, + { + column: "score", + errorType: "TypeError", + errorMessage: "bad input", + rowsFailed: 1n, + }, + ]); + const rows = await table.functionErrorRows({ columns: ["text"] }); + expect(rows.map(({ input, error }) => [input, error.column])).toEqual([ + [{ text: "moved stable row" }, "embedding"], + [{ text: "physical failure" }, "embedding"], + [{ text: "moved stable row" }, "score"], + ]); + await expect( + table.functionErrorRows({ columns: ["text"] }), + ).rejects.toThrow("no longer addressable"); + const history = await table.functionErrors({ + history: true, + jobId: "j-7", + }); + expect(history.records[0].rowId).toBe(stableId); + await expect( + table.functionErrorRows({ columns: ["text"], limit: 2 }), + ).rejects.toThrow("Function errors are incomplete"); + await expect( + table.functionErrorRows({ column: "empty" }), + ).resolves.toEqual([]); + }, + ); + expect(errorRequests).toEqual([ + {}, + {}, + {}, + { limit: 1 }, + { history: true, ["job_id"]: "j-7" }, + { limit: 2 }, + { column: "empty" }, + ]); + expect(queryRequests).toHaveLength(2); + for (const request of queryRequests) { + expect(request).toMatchObject({ + columns: ["text", "_rowid", "_rowaddr"], + filter: `_rowid IN (${stableId}) OR _rowaddr IN (${physicalAddress})`, + k: 2, + }); + } + }); + + it("forwards exact Function recovery requests and preserves async job results", async () => { + const requests: [string, unknown][] = []; + const stableId = 9_007_199_254_740_993n; + await withMockDatabase( + (req, res) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + const path = req.url ?? ""; + const request = body ? JSON.parse(body) : {}; + requests.push([path, request]); + if (path === "/v1/table/docs/describe/") { + res.writeHead(200).end('{"version":8,"schema":{"fields":[]}}'); + } else if (path === "/v1/table/docs/errors") { + res + .writeHead(200) + .end( + '{"workflow_version":1,"records":[],"fragments":[],"truncated":false}', + ); + } else if (path === "/v1/table/docs/backfill_column") { + res.writeHead(202).end('{"job_id":"refresh-1"}'); + } else if (path === "/v1/jobs/describe") { + res.writeHead(200).end(`{ + "job_id":"refresh-1", "job_type":"function_refresh", "job_state":"DONE", + "result":{"rows_assigned":19, "rows_failed":1, "rows_remaining":0, + "source_version":7, "published_version":8, "error_groups_truncated":true, + "error_groups":[{"column":"embedding", "error_type":"ValueError", + "error_message":"bad input", "rows_failed":1}]} + }`); + } else if (path === "/v1/table/docs/errors/quarantine") { + res.writeHead(200).end('{"rows_affected":2}'); + } else if (path === "/v1/table/docs/function_provenance") { + res.writeHead(200).end(`{"truncated":true,"records":[{ + "column":"embedding", "job_id":"refresh-1", "function_name":"embed", + "function_version":"2", "row_id":${stableId}, "row_address":null, + "source_version":7, "published_version":8 + }]}`); + } else { + res.writeHead(404).end(); + } + }); + }, + async (db) => { + const table = await db.openTable("docs"); + const job = await table.retryFailed("embedding", { + errorType: "ValueError", + jobId: "first", + includeQuarantined: true, + functionVersion: "2", + maxFailedFraction: 1, + }); + expect(job.id).toBe("refresh-1"); + expect(await job.wait()).toEqual({ + rowsAssigned: 19n, + rowsFailed: 1n, + rowsRemaining: 0n, + sourceVersion: 7n, + publishedVersion: 8n, + errorGroupsTruncated: true, + errorGroups: [ + { + column: "embedding", + errorType: "ValueError", + errorMessage: "bad input", + rowsFailed: 1n, + }, + ], + }); + await table.retryFailed("embedding"); + await table.upgradeColumn("embedding", { + version: "3", + recompute: "failed", + }); + await table.upgradeColumn("embedding", { version: "4" }); + await table.upgradeColumn("embedding", { + version: "5", + recompute: "none", + }); + await expect( + table.quarantineFailed("embedding", { + jobId: "first", + afterAttempts: 3, + errorType: "ValueError", + }), + ).resolves.toBe(2); + await expect( + table.quarantineFailed("embedding", { quarantined: false }), + ).resolves.toBe(2); + const provenance = await table.functionProvenance("embedding", { + version: 8n, + limit: 1, + }); + expect(provenance.truncated).toBe(true); + expect(provenance.records[0]).toMatchObject({ + jobId: "refresh-1", + functionName: "embed", + functionVersion: "2", + rowId: stableId, + sourceVersion: 7n, + publishedVersion: 8n, + }); + await expect( + table.upgradeColumn("embedding", { version: "" }), + ).rejects.toThrow("nonempty function_version"); + await expect( + table.quarantineFailed("embedding", { afterAttempts: 2 ** 32 + 1 }), + ).rejects.toThrow("afterAttempts"); + await expect( + table.functionProvenance("embedding", { version: -(2n ** 64n) }), + ).rejects.toThrow("positive lossless u64 bigint"); + const ordinary = await table.refreshColumnAsync("embedding"); + await expect(ordinary.wait()).resolves.toBeUndefined(); + }, + ); + const probe = ["/v1/table/docs/errors", { limit: 1 }]; + expect(requests).toEqual([ + ["/v1/table/docs/describe/", {}], + probe, + [ + "/v1/table/docs/backfill_column", + JSON.parse(`{ + "column":"embedding", "retry_errors":true, "retry_job_id":"first", + "retry_error_type":"ValueError", "include_quarantined":true, + "function_version":"2", "recompute":"failed", "max_failed_fraction":1 + }`), + ], + ["/v1/jobs/describe", { ["job_id"]: "refresh-1" }], + probe, + [ + "/v1/table/docs/backfill_column", + { column: "embedding", ["retry_errors"]: true }, + ], + ...[ + ["3", "failed"], + ["4", "all"], + ["5", "none"], + ].flatMap(([version, recompute]) => [ + probe, + [ + "/v1/table/docs/backfill_column", + { column: "embedding", ["function_version"]: version, recompute }, + ], + ]), + probe, + [ + "/v1/table/docs/errors/quarantine", + { + column: "embedding", + quarantined: true, + ["job_id"]: "first", + ["after_attempts"]: 3, + ["error_type"]: "ValueError", + }, + ], + probe, + [ + "/v1/table/docs/errors/quarantine", + { + column: "embedding", + quarantined: false, + ["job_id"]: null, + ["after_attempts"]: null, + ["error_type"]: null, + }, + ], + probe, + [ + "/v1/table/docs/function_provenance", + { column: "embedding", version: 8, limit: 1 }, + ], + ["/v1/table/docs/backfill_column", { column: "embedding" }], + ["/v1/jobs/describe", { ["job_id"]: "refresh-1" }], + ]); + }); + + it("passes a pinned version and decodes Function scheduler status", async () => { + const queries: Record[] = []; + await withMockDatabase( + (req, res) => { + const url = new URL(req.url ?? "/", "http://localhost"); + if (url.pathname.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "docs", + version: 42, + schema: { fields: [] }, + }), + ); + return; + } + if (url.pathname === "/v1/table/docs/function_columns/status") { + queries.push(Object.fromEntries(url.searchParams.entries())); + res.writeHead(200, { "Content-Type": "application/json" }).end( + `[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":2, + "stale":2, + "never_computed":0, + "failed":0, + "last_refresh_job":{ + "job_id":"job-cancelled", + "state":"cancelled", + "automatic":true, + "completed_at_millis":1790000002000 + }, + "last_failure_job":{ + "job_id":"job-failed", + "state":"failed", + "automatic":true, + "completed_at_millis":1790000001000, + "failure":{ + "phase":"finalize", + "message":"worker timed out", + "traceback":"Traceback: timeout", + "retryable":true, + "sql_job_id":"sql-job-7" + } + }, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "active_job_id":"job-queued", + "state":"queued", + "failure_streak":1, + "next_run_at_millis":null, + "next_run_at_reason":"job_queued_not_started" + } + }]`, + ); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("docs"); + await table.checkout(42); + const status = await table.functionColumnStatus("embedding"); + expect(status.tableVersion).toBe(42n); + expect(status.autoRefresh.state).toBe("queued"); + expect(status.autoRefresh.activeJobId).toBe("job-queued"); + expect(status.autoRefresh.failureStreak).toBe(1); + expect(status.autoRefresh.nextRunAtReason).toBe( + "job_queued_not_started", + ); + expect(status.lastRefreshJob?.state).toBe("cancelled"); + expect(status.lastRefreshJob?.failure).toBeUndefined(); + expect(status.lastFailureJob?.jobId).toBe("job-failed"); + expect(status.lastFailureJob?.failure).toEqual({ + phase: "finalize", + message: "worker timed out", + traceback: "Traceback: timeout", + retryable: true, + sqlJobId: "sql-job-7", + }); + }, + ); + expect(queries).toEqual([{ column: "embedding", version: "42" }]); + }); + + it("forwards refresh options to the backfill request", async () => { + const bodies: unknown[] = []; + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "docs", + version: 1, + schema: { fields: [] }, + }), + ); + return; + } + if (path === "/v1/table/docs/backfill_column") { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + bodies.push(JSON.parse(body)); + res + .writeHead(202, { "Content-Type": "application/json" }) + .end('{"job_id": "j-9"}'); + }); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("docs"); + const job = await table.refreshColumnAsync("embedding", { + where: "id % 2 = 0", + batchSize: 16, + publicationIntervalRows: 60, + maxConcurrency: 3, + gpuClass: "a10g", + totalGpuCount: 2, + errorPolicy: "skip", + maxFailedFraction: 0.01, + maxFailedRows: 50, + rowTimeoutSeconds: 30, + initTimeoutSeconds: 120, + maxExecutorProcessesPerWorker: 2, + }); + expect(job.id).toBe("j-9"); + await table.refreshColumnAsync("embedding"); + await table.refreshColumnAsync("embedding", { + publicationIntervalRows: undefined, + }); + for (const publicationIntervalRows of [ + 1, + 2 ** 32 + 1, + Number.MAX_SAFE_INTEGER, + ]) { + await table.refreshColumnAsync("embedding", { + publicationIntervalRows, + }); + } + await table.refreshColumnAsync("embedding", { + totalCpuMillis: 8_000, + totalMemoryBytes: 16 * 1024 ** 3, + }); + await expect( + table.refreshColumnAsync("embedding", { + maxConcurrency: true as unknown as number, + }), + ).rejects.toThrow(); + for (const publicationIntervalRows of [true, "60", 60n]) { + await expect( + table.refreshColumnAsync("embedding", { + publicationIntervalRows: + publicationIntervalRows as unknown as number, + }), + ).rejects.toThrow(); + } + // Invalid options reject before any request is sent. + for (const [options, message] of [ + [{ maxFailedRows: -1 }, "maxFailedRows"], + [{ errorPolicy: "retry" }, "errorPolicy"], + [{ where: " " }, "where"], + [{ maxFailedFraction: 2 }, "max_failed_fraction"], + [{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"], + [{ publicationIntervalRows: 0 }, "publicationIntervalRows"], + [{ publicationIntervalRows: -1 }, "publicationIntervalRows"], + [{ publicationIntervalRows: 1.5 }, "publicationIntervalRows"], + [{ publicationIntervalRows: Number.NaN }, "publicationIntervalRows"], + [ + { publicationIntervalRows: Number.POSITIVE_INFINITY }, + "publicationIntervalRows", + ], + [ + { publicationIntervalRows: Number.NEGATIVE_INFINITY }, + "publicationIntervalRows", + ], + [ + { publicationIntervalRows: Number.MAX_SAFE_INTEGER + 1 }, + "publicationIntervalRows", + ], + [{ maxConcurrency: 1.5 }, "maxConcurrency"], + [{ maxConcurrency: 0 }, "maxConcurrency"], + [{ maxConcurrency: -1 }, "maxConcurrency"], + [{ maxConcurrency: 2 ** 32 }, "maxConcurrency"], + [{ maxConcurrency: Number.NaN }, "maxConcurrency"], + [{ maxConcurrency: Number.POSITIVE_INFINITY }, "maxConcurrency"], + [{ numWorkers: 0 }, "num_workers"], + + [ + { + totalCpuMillis: 0, + totalMemoryBytes: 1_024, + }, + "totalCpuMillis", + ], + [ + { + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: 1.5, + }, + "totalGpuCount", + ], + [ + { + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: -1, + }, + "totalGpuCount", + ], + [ + { + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: 2 ** 32, + }, + "totalGpuCount", + ], + [ + { + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: Number.NaN, + }, + "totalGpuCount", + ], + [ + { + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + totalGpuCount: Number.POSITIVE_INFINITY, + }, + "totalGpuCount", + ], + [ + { + supervisorResources: { + cpuMillis: 0, + memoryBytes: 1_024, + ephemeralStorageBytes: 2_048, + }, + }, + "supervisorResources.cpuMillis", + ], + [ + { + supervisorResources: { + cpuMillis: 1_000, + memoryBytes: 1_024, + ephemeralStorageBytes: 0, + }, + }, + "supervisorResources.ephemeralStorageBytes", + ], + [ + { + planningWorkers: { + resources: { + cpuMillis: 1_000, + memoryBytes: 1_024, + ephemeralStorageBytes: 2_048, + }, + maxWorkers: 0, + rowsPerWorker: 100, + fragmentsPerWorker: 1, + }, + }, + "planningWorkers.maxWorkers", + ], + [{ retryPolicy: { maxAttempts: 0 } }, "retry_policy.max_attempts"], + ] as const) { + await expect( + table.refreshColumnAsync("embedding", options), + ).rejects.toThrow(message); + } + }, + ); + expect(bodies).toEqual([ + JSON.parse( + `{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16, + "publication_interval_rows": 60, + "max_concurrency": 3, "gpu_class": "a10g", "total_gpu_count": 2, + "error_policy": "skip", + "max_failed_fraction": 0.01, "max_failed_rows": 50, + "row_timeout_seconds": 30, "init_timeout_seconds": 120, + "max_executor_processes_per_worker": 2}`, + ), + { column: "embedding" }, + { column: "embedding" }, + JSON.parse('{"column": "embedding", "publication_interval_rows": 1}'), + JSON.parse( + '{"column": "embedding", "publication_interval_rows": 4294967297}', + ), + JSON.parse( + '{"column": "embedding", "publication_interval_rows": 9007199254740991}', + ), + JSON.parse( + '{"column":"embedding","total_cpu_millis":8000,"total_memory_bytes":17179869184}', + ), + ]); + }); + + it("forwards structured Function refresh options and Node retry policy", async () => { + const bodies: unknown[] = []; + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "docs", + version: 1, + schema: { fields: [] }, + }), + ); + return; + } + if (path === "/v1/table/docs/backfill_column") { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + bodies.push(JSON.parse(body)); + res + .writeHead(202, { "Content-Type": "application/json" }) + .end('{"job_id": "j-structured"}'); + }); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("docs"); + const job = await table.refreshColumnAsync("embedding", { + supervisorResources: { + cpuMillis: 2_000, + memoryBytes: 4 * 1024 ** 3, + ephemeralStorageBytes: 10 * 1024 ** 3, + }, + planningWorkers: { + resources: { + cpuMillis: 1_000, + memoryBytes: 2 * 1024 ** 3, + ephemeralStorageBytes: 5 * 1024 ** 3, + }, + maxWorkers: 4, + rowsPerWorker: 100_000, + fragmentsPerWorker: 8, + }, + retryPolicy: { transient: true }, + }); + expect(job.id).toBe("j-structured"); + }, + ); + expect(bodies).toEqual([ + { + column: "embedding", + ["supervisor_resources"]: { + ["cpu_millis"]: 2_000, + ["memory_bytes"]: 4 * 1024 ** 3, + ["ephemeral_storage_bytes"]: 10 * 1024 ** 3, + }, + ["planning_workers"]: { + resources: { + ["cpu_millis"]: 1_000, + ["memory_bytes"]: 2 * 1024 ** 3, + ["ephemeral_storage_bytes"]: 5 * 1024 ** 3, + }, + ["max_workers"]: 4, + ["rows_per_worker"]: 100_000, + ["fragments_per_worker"]: 8, + }, + ["retry_policy"]: { + ["max_attempts"]: 3, + ["initial_backoff_seconds"]: 0.2, + ["max_backoff_seconds"]: 30, + ["exception_types"]: [], + ["message_pattern"]: null, + ["error_codes"]: [], + transient: true, + ["honor_retry_after"]: true, + }, + }, ]); }); @@ -735,6 +1691,111 @@ describe("remote connection", () => { ); }); + it("forks Enterprise branches from tags and defaults tag versions", async () => { + const requests: { path: string; body: Record }[] = []; + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/branches/list/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + branches: { + exp: { parentVersion: 1, createAt: 1, manifestSize: 1 }, + }, + }), + ); + return; + } + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "t", + version: 2, + schema: { fields: [] }, + }), + ); + return; + } + + let raw = ""; + req.on("data", (chunk) => { + raw += chunk; + }); + req.on("end", () => { + const body = raw ? JSON.parse(raw) : {}; + requests.push({ path, body }); + if (path.endsWith("/tags/version/")) { + res + .writeHead(200, { "Content-Type": "application/json" }) + .end(JSON.stringify({ version: 3, branch: "base" })); + return; + } + if (path.endsWith("/tags/create/")) { + res + .writeHead(200, { "Content-Type": "application/json" }) + .end("{}"); + return; + } + if (path.endsWith("/branches/create/")) { + if (body["name"] === "missing") { + res + .writeHead(404, { "Content-Type": "application/json" }) + .end(JSON.stringify({ message: "not found" })); + return; + } + res + .writeHead(200, { "Content-Type": "application/json" }) + .end("{}"); + return; + } + res.writeHead(404).end(); + }); + }, + async (db) => { + const table = await db.openTable("t", undefined, { branch: "exp" }); + await (await table.tags()).create("baseline"); + + const branches = await table.branches(); + const fromTag = await branches.create("from-tag", { + fromTag: "baseline", + }); + expect(fromTag.currentBranch()).toBe("from-tag"); + + // An Enterprise 404 is an ambiguous table-or-source failure, so the + // Embedded branch hint must not be appended based on its message. + const missing = await branches + .create("missing", { fromTag: "baseline" }) + .then( + () => undefined, + (error: Error) => error, + ); + expect(missing).toBeDefined(); + expect(missing?.message).not.toContain("fromTag"); + }, + ); + + // Omitting the tag version resolves the handle's visible branch version. + expect(requests).toContainEqual({ + path: "/v1/table/t/tags/create/", + body: { + tag: "baseline", + version: 2, + branch: "exp", + }, + }); + // A tag source uses the existing coordinate lookup and the normal + // branches/create body; there is no from_tag field on the wire. + expect(requests).toContainEqual({ + path: "/v1/table/t/tags/version/", + body: { tag: "baseline" }, + }); + expect(requests).toContainEqual({ + path: "/v1/table/t/branches/create/", + // biome-ignore lint/style/useNamingConvention: snake_case is the server wire format + body: { name: "from-tag", from_branch: "base", from_version: 3 }, + }); + }); + it("sends FTS options to remote tables", async () => { let createIndexBody: Record | undefined; @@ -788,6 +1849,172 @@ describe("remote connection", () => { expect(createIndexBody?.["custom_stop_words"]).toEqual(["the"]); }); + it("sends RTree options to remote tables", async () => { + const createIndexBodies: Record[] = []; + + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "t", + version: 1, + schema: { + fields: [ + { + name: "geom", + type: { + type: "struct", + fields: [ + { + name: "x", + type: { type: "double" }, + nullable: false, + }, + { + name: "y", + type: { type: "double" }, + nullable: false, + }, + ], + }, + nullable: true, + metadata: { "ARROW:extension:name": "geoarrow.point" }, + }, + ], + }, + }), + ); + return; + } + + if (path.endsWith("/create_index/")) { + let raw = ""; + req.on("data", (chunk) => { + raw += chunk; + }); + req.on("end", () => { + createIndexBodies.push(JSON.parse(raw)); + res.writeHead(200).end(); + }); + return; + } + + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("t"); + await table.createIndex("geom", { config: Index.rtree() }); + await table.createIndex("geom", { + config: Index.rtree({ pageSize: 1024 }), + name: "geom_rtree", + }); + }, + ); + + expect(createIndexBodies).toEqual([ + { + column: "geom", + // biome-ignore lint/style/useNamingConvention: server wire format + index_type: "RTREE", + }, + { + column: "geom", + // biome-ignore lint/style/useNamingConvention: server wire format + index_type: "RTREE", + name: "geom_rtree", + // biome-ignore lint/style/useNamingConvention: server wire format + page_size: 1024, + }, + ]); + }); + + it("uses an explicit type and nested params for remote scalar plugin indexes", async () => { + const createIndexBodies: Record[] = []; + + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "t", + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int32" }, nullable: false }, + ], + }, + }), + ); + return; + } + + if (path.endsWith("/create_index/")) { + let raw = ""; + req.on("data", (chunk) => { + raw += chunk; + }); + req.on("end", () => { + createIndexBodies.push(JSON.parse(raw)); + res.writeHead(200).end(); + }); + return; + } + + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("t"); + await table.createIndex("id", { config: Index.plugin(" ZoneMap ") }); + await table.createIndex("id", { + config: Index.plugin("bloomfilter", { + // biome-ignore lint/style/useNamingConvention: plugin param name + number_of_items: 4096, + column: "not_id", + }), + name: "id_bloom", + }); + await table.createIndex("id", { + config: Index.plugin("bloomfilter", '{"probability": 0.01}'), + }); + await table.createIndex("id", { config: Index.plugin("zonemap", {}) }); + }, + ); + + expect(createIndexBodies).toEqual([ + // biome-ignore lint/style/useNamingConvention: wire format + { column: "id", index_type: "PLUGIN", plugin_type: "ZONEMAP" }, + { + column: "id", + // biome-ignore lint/style/useNamingConvention: wire format + index_type: "PLUGIN", + // biome-ignore lint/style/useNamingConvention: wire format + plugin_type: "BLOOMFILTER", + name: "id_bloom", + // biome-ignore lint/style/useNamingConvention: plugin param name + params: { number_of_items: 4096, column: "not_id" }, + }, + { + column: "id", + // biome-ignore lint/style/useNamingConvention: wire format + index_type: "PLUGIN", + // biome-ignore lint/style/useNamingConvention: wire format + plugin_type: "BLOOMFILTER", + params: { probability: 0.01 }, + }, + { + column: "id", + // biome-ignore lint/style/useNamingConvention: wire format + index_type: "PLUGIN", + // biome-ignore lint/style/useNamingConvention: wire format + plugin_type: "ZONEMAP", + params: {}, + }, + ]); + }); + it("diffs and cherry-picks remote branches", async () => { const sampleDiff = { fromBranch: "exp", @@ -1451,7 +2678,13 @@ describe("remote connection jobs surface", () => { .end( '{"jobs": [{"job_id": "job-2", "table": "t2", ' + '"job_type": "create_index", "state": "succeeded", ' + - '"created_at_millis": 2000}]}', + '"created_at_millis": 2000, "completed_at_millis": 2000, ' + + '"duration_millis": 0, "columns": ["embedding"], ' + + '"function_name": "features$embed", "function_version": "7"}, ' + + '{"job_id": "job-3", "table": "t2", "job_type": "function_refresh", ' + + '"state": "failed", "created_at_millis": 3000, "duration_millis": 200, ' + + '"completed_at_millis": 3200, "failure": {"phase": "execute", ' + + '"message": "worker failed", "retryable": false}}]}', ); } } else if (req.url === "/v1/jobs/describe") { @@ -1520,9 +2753,31 @@ describe("remote connection jobs surface", () => { }, async (db) => { const jobs = await collect(db.listJobs()); - expect(jobs.map((job) => job.jobId)).toEqual(["job-1", "job-2"]); + expect(jobs.map((job) => job.jobId)).toEqual([ + "job-1", + "job-2", + "job-3", + ]); expect(jobs[0].state).toEqual("running"); expect(jobs[1].state).toEqual("finished"); + expect(jobs[0].completedAtMillis).toBeUndefined(); + expect(jobs[0].durationMillis).toBeUndefined(); + expect(jobs[0].columns).toEqual([]); + expect(jobs[0].functionName).toBeUndefined(); + expect(jobs[0].functionVersion).toBeUndefined(); + expect(jobs[0].failure).toBeUndefined(); + expect(jobs[1].completedAtMillis).toBe(2000); + expect(jobs[1].durationMillis).toBe(0); + expect(jobs[1].columns).toEqual(["embedding"]); + expect(jobs[1].functionName).toBe("features$embed"); + expect(jobs[1].functionVersion).toBe("7"); + expect(jobs[1].failure).toBeUndefined(); + expect(jobs[2].state).toBe("failed"); + expect(jobs[2].durationMillis).toBe(200); + expect(jobs[2].failure?.phase).toBe("execute"); + expect(jobs[2].failure?.message).toBe("worker failed"); + expect(jobs[2].failure?.retryable).toBe(false); + expect(jobs[2].failure?.traceback).toBeUndefined(); expect(jobs[0].progress).toEqual({ // biome-ignore lint/style/useNamingConvention: server wire format job_type: "create_index", @@ -1565,6 +2820,8 @@ describe("remote connection jobs surface", () => { expect(job.result).toBeNull(); expect(job.failure?.message).toEqual("worker died"); expect(await job.progress()).toEqual({ + // biome-ignore lint/style/useNamingConvention: server wire format + job_id: "job-1", // biome-ignore lint/style/useNamingConvention: server wire format job_type: "create_index", state: "failed", @@ -1671,10 +2928,30 @@ describe("remote connection jobs surface", () => { queue_reason: "Waiting for Function worker capacity", }); const descriptions = [ - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 3000, unknownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 2000, knownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(40, 60, 1000, unknownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(60, 0, 0, unknownFleet)}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 20, + 80, + 3000, + unknownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 20, + 80, + 2000, + knownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 40, + 60, + 1000, + unknownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress( + 60, + 0, + 0, + unknownFleet, + )}}`, ]; let describeCount = 0; @@ -1746,12 +3023,24 @@ describe("remote connection jobs surface", () => { it("does not derive ETA across a zero-rate, epoch, or pause boundary", async () => { const now = Date.now(); const descriptions = [ - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 5000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 4000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 3000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 2000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1500}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1000}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${ + now - 5000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${ + now - 4000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 3000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 2000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 1500 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 1000 + }}}`, ]; await withMockDatabase( @@ -1927,6 +3216,7 @@ describe("lazy resource listings", () => { if (kind === "jobs") { expect(url.pathname).toBe("/v1/jobs/list"); expect(request.body).toEqual({ + database: "dev", // biome-ignore lint/style/useNamingConvention: server wire format page_token: token, limit: 2, @@ -1982,3 +3272,539 @@ describe("lazy resource listings", () => { }); } }); + +describe("remote compaction job results", () => { + test.each([true, false])( + "reopens typed compaction result (counts=%s)", + async (counts) => { + await withMockDatabase( + (request, response) => { + expect(request.url).toBe("/v1/jobs/describe"); + const result = JSON.parse(`{ + "partial_commit": false, + "rows_succeeded": 12, + "rows_failed": 0, + "completion_percentage": 100 + }`); + if (counts) { + Object.assign( + result, + JSON.parse(`{ + "files_added": 1, + "files_removed": 3, + "fragments_added": 1, + "fragments_removed": 3 + }`), + ); + } + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + `{"job_id":"compacting-job","job_type":"compact","job_state":"DONE","result":${JSON.stringify(result)}}`, + ); + }, + async (db) => { + const job = + await db.openJob( + "compacting-job", + ); + const result = await job.wait(); + expect(result.rowsSucceeded).toBe(12); + expect(result.moreWork).toBe(false); + expect(result.fragmentsRemoved).toBe(counts ? 3 : null); + }, + ); + }, + ); +}); + +describe("data prewarm typed results", () => { + test.each([null, {}])( + "rejects a missing typed outcome (%p)", + async (result) => { + await withMockDatabase( + (_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + `{"job_id":"warming-job","job_type":"prewarm_page_cache","job_state":"DONE","result":${JSON.stringify(result)}}`, + ); + }, + async (db) => { + const job = await db.openJob("warming-job"); + await expect(job.wait()).rejects.toThrow(); + }, + ); + }, + ); + + test.each([true, false])( + "reopens a result (counters=%s)", + async (counters) => { + await withMockDatabase( + (_request, response) => { + const result = JSON.parse( + counters + ? '{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}' + : '{"table_version":42}', + ); + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify({ + ["job_id"]: "warming-job", + ["job_type"]: "prewarm_page_cache", + ["job_state"]: "DONE", + progress: null, + ["operation_progress"]: { + phase: "reading", + ["executors_completed"]: 2, + }, + result, + }), + ); + }, + async (db) => { + const job = + await db.openJob( + "warming-job", + ); + const result = await job.wait(); + expect(result.tableVersion).toBe(42); + expect(result.executorsCompleted).toBe(counters ? 2 : null); + expect(result.bytesRead).toBeNull(); + expect((await job.progress())?.executors_completed).toBe(2); + }, + ); + }, + ); +}); + +describe("job wait deadlines", () => { + function response(kind: string, done: boolean) { + const result = + kind === "compact" + ? '{"partial_commit":false,"rows_succeeded":12,"rows_failed":0,"completion_percentage":100}' + : kind === "prewarm_page_cache" + ? '{"table_version":42,"executors_targeted":2,"executors_completed":2}' + : "null"; + return `{"job_id":"bounded-job","job_type":"${kind}","job_state":"${done ? "DONE" : "IN_PROGRESS"}","result":${done ? result : "null"}}`; + } + + test.each(["compact", "prewarm_page_cache", "create_index"])( + "%s stops polling at timeout, resumes, and reopens", + async (kind) => { + let done = false; + let describes = 0; + const progress: JobProgress[] = []; + await withMockDatabase( + (request, res) => { + expect(request.url).toBe("/v1/jobs/describe"); + describes++; + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response(kind, done)); + }, + async (db) => { + const fallback = setTimeout(() => { + done = true; + }, 1000); + try { + const job = await db.openJob("bounded-job"); + await expect( + job.wait({ timeoutMs: 50, onProgress: (p) => progress.push(p) }), + ).rejects.toThrow(/bounded-job.*continues/); + expect(job.state).toBe("running"); + await new Promise((resolve) => setImmediate(resolve)); + const requestsAtTimeout = describes; + const updatesAtTimeout = progress.length; + await new Promise((resolve) => setTimeout(resolve, 350)); + expect(describes).toBe(requestsAtTimeout); + expect(progress).toHaveLength(updatesAtTimeout); + done = true; + const result = await job.wait({ + timeoutMs: 1000, + onProgress: (p) => progress.push(p), + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(progress.some((p) => p.state === "finished")).toBe(true); + expect(job.state).toBe("finished"); + expect(result).toEqual( + kind === "compact" + ? expect.objectContaining({ rowsSucceeded: 12 }) + : kind === "prewarm_page_cache" + ? expect.objectContaining({ tableVersion: 42 }) + : undefined, + ); + // Existing callback-only and argument-free calls remain supported. + expect(await job.wait((p) => progress.push(p))).toEqual(result); + expect(await job.wait()).toEqual(result); + const reopened = await db.openJob("bounded-job"); + expect(await reopened.wait({ timeoutMs: 1000 })).toEqual(result); + } finally { + clearTimeout(fallback); + } + }, + ); + }, + ); + + it("bounds a pending HTTP response and permits a later wait", async () => { + let slow = false; + let requests = 0; + await withMockDatabase( + (request, res) => { + expect(request.url).toBe("/v1/jobs/describe"); + requests++; + const send = () => { + if (!res.destroyed) { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response("prewarm_page_cache", slow)); + } + }; + if (slow) setTimeout(send, 300); + else send(); + }, + async (db) => { + const job = await db.openJob("bounded-job"); + slow = true; + await expect(job.wait({ timeoutMs: 50 })).rejects.toThrow("continues"); + expect(job.state).toBe("running"); + const stoppedAt = requests; + await new Promise((resolve) => setTimeout(resolve, 350)); + expect(requests).toBe(stoppedAt); + const result = await job.wait({ timeoutMs: 1000 }); + expect(result).toEqual(expect.objectContaining({ tableVersion: 42 })); + }, + ); + }); + + it("accepts zero timeout and validates options before polling", async () => { + let requests = 0; + let done = false; + await withMockDatabase( + (_request, res) => { + requests++; + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response("compact", done)); + }, + async (db) => { + const fallback = setTimeout(() => { + done = true; + }, 1000); + try { + const job = await db.openJob("bounded-job"); + for (const timeoutMs of [ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, + "10", + true, + ]) { + await expect( + job.wait({ timeoutMs: timeoutMs as number }), + ).rejects.toThrow("nonnegative safe integer"); + } + await expect(job.wait({ timeout: 10 } as never)).rejects.toThrow( + "Unknown job wait option", + ); + await expect(job.wait({ onProgress: 7 } as never)).rejects.toThrow( + "onProgress must be a function", + ); + await expect(job.wait(10 as never)).rejects.toThrow("options object"); + expect(requests).toBe(1); + await expect(job.wait({ timeoutMs: 0 })).rejects.toThrow("Timeout"); + } finally { + clearTimeout(fallback); + } + }, + ); + }); + + test.each(["FAILED", "CANCELLED"])( + "preserves a %s outcome when a timeout is configured", + async (state) => { + await withMockDatabase( + (_request, res) => { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end( + `{"job_id":"bounded-job","job_type":"compact","job_state":"${state}"}`, + ); + }, + async (db) => { + const job = await db.openJob("bounded-job"); + await expect(job.wait({ timeoutMs: 1000 })).rejects.toThrow( + state === "FAILED" ? /failed/i : /cancelled/i, + ); + }, + ); + }, + ); +}); + +describe("table overrides", () => { + it.each([[], ["analytics", "features"]])( + "reads, recursively merges, and resets in namespace %j", + async (...namespacePath: string[]) => { + const requests: { method?: string; url: string; body?: unknown }[] = []; + const current = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { + enabled: true, + // biome-ignore lint/style/useNamingConvention: server wire format + target_rows_per_fragment: 1000, + }, + cleanup: { enabled: false }, + }, + custom: { keep: true, replace: [1, 2], clear: "value" }, + }; + const patch = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { compaction: { enabled: false } }, + custom: { replace: [3], clear: null, label: "測試" }, + }; + const merged = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { + enabled: false, + // biome-ignore lint/style/useNamingConvention: server wire format + target_rows_per_fragment: 1000, + }, + cleanup: { enabled: false }, + }, + custom: { keep: true, replace: [3], clear: null, label: "測試" }, + }; + await withMockDatabase( + (req, res) => { + const url = req.url ?? ""; + if (url.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + return; + } + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + const body = chunks.length + ? JSON.parse(Buffer.concat(chunks).toString()) + : undefined; + requests.push({ method: req.method, url, body }); + res + .writeHead(200) + .end( + JSON.stringify( + req.method === "GET" + ? current + : req.method === "PUT" + ? body.overrides + : {}, + ), + ); + }); + }, + async (db) => { + const table = await db.openTable("test", namespacePath); + await expect(table.getTableOverrides()).resolves.toEqual(current); + await expect(table.updateTableOverrides(patch)).resolves.toEqual( + merged, + ); + // The native conversion and merge must not mutate the caller's object. + expect(patch.job_types.compaction).toEqual({ enabled: false }); + expect(patch.custom.replace).toEqual([3]); + await expect(table.resetTableOverrides()).resolves.toEqual({}); + }, + ); + expect(requests.map((request) => request.method)).toEqual([ + "GET", + "GET", + "PUT", + "POST", + ]); + for (const request of requests) { + const url = new URL(request.url, "http://localhost"); + expect(url.pathname).toBe( + request.method === "POST" + ? "/admin/table/overrides/reset" + : "/admin/table/overrides", + ); + if (request.method === "PUT") { + expect(request.body).toEqual({ + db: "dev", + namespace: namespacePath, + table: "test", + overrides: merged, + }); + } else { + expect(url.searchParams.get("db")).toBe("dev"); + expect(url.searchParams.get("table")).toBe("test"); + expect(url.searchParams.getAll("namespace")).toEqual(namespacePath); + } + } + }, + ); + + it.each([{}, { custom: { keep: true } }])( + "only reads the snapshot %j for an empty update", + async (current) => { + const methods: string[] = []; + await withMockDatabase( + (req, res) => { + if (req.url?.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + return; + } + methods.push(req.method ?? ""); + res + .writeHead(req.method === "GET" ? 200 : 400) + .end(JSON.stringify(current)); + }, + async (db) => { + const table = await db.openTable("test"); + await expect(table.updateTableOverrides({})).resolves.toEqual( + current, + ); + }, + ); + expect(methods).toEqual(["GET"]); + }, + ); + + it.each([null, [], true, 1, "bad"])( + "rejects a non-object update %j before reading overrides", + async (value) => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + }, + async (db) => { + const table = await db.openTable("test"); + await expect( + table.updateTableOverrides( + value as unknown as Record, + ), + ).rejects.toThrow(/must be a JSON object/); + }, + ); + expect(requests).toEqual(["/v1/table/test/describe/"]); + }, + ); + + it.each([403, 404])( + "propagates GET failure %i without a PUT", + async (status) => { + const methods: string[] = []; + await withMockDatabase( + (req, res) => { + if (req.url?.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + } else { + methods.push(req.method ?? ""); + res.writeHead(status).end("overrides unavailable"); + } + }, + async (db) => { + const table = await db.openTable("test"); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/overrides unavailable/); + }, + ); + expect(methods).toEqual(["GET"]); + }, + ); + + it("rejects writes on historical and closed handles before HTTP", async () => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + }, + async (db) => { + const table = await db.openTable("test"); + await table.checkout(1); + requests.length = 0; + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/fixed at version 1/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /fixed at version 1/, + ); + table.close(); + await expect(table.getTableOverrides()).rejects.toThrow(/closed/); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/closed/); + await expect(table.resetTableOverrides()).rejects.toThrow(/closed/); + }, + ); + expect(requests).toEqual([]); + }); +}); + +describe("cleanup typed results", () => { + test.each(["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"])( + "reopens and waits for cleanup (%s)", + async (outcome) => { + const known = outcome !== "unknown"; + await withMockDatabase( + (request, response) => { + expect(request.url).toBe("/v1/jobs/describe"); + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify({ + ["job_id"]: "cleanup-job", + ["job_type"]: "cleanup", + ["job_state"]: ["FAILED", "CANCELLED"].includes(outcome) + ? outcome + : "DONE", + result: + outcome === "missing" + ? null + : { + ["format_version"]: 1, + ["min_age_seconds"]: 0, + ["statistics_complete"]: known, + ["old_versions"]: known + ? outcome === "no_op" + ? 0 + : 2 + : null, + ["bytes_removed"]: known + ? outcome === "no_op" + ? 0 + : 123 + : null, + }, + }), + ); + }, + async (db) => { + const job = + await db.openJob("cleanup-job"); + if (["missing", "FAILED", "CANCELLED"].includes(outcome)) { + await expect(job.wait()).rejects.toThrow(); + } else { + const result = await job.wait(); + expect(result.statisticsComplete).toBe(known); + expect(result.oldVersions).toBe( + known ? (outcome === "no_op" ? 0 : 2) : null, + ); + expect(result.minAgeSeconds).toBe(0); + } + }, + ); + }, + ); +}); diff --git a/nodejs/__test__/remote_blob_snapshot.test.ts b/nodejs/__test__/remote_blob_snapshot.test.ts new file mode 100644 index 000000000..908dfa9de --- /dev/null +++ b/nodejs/__test__/remote_blob_snapshot.test.ts @@ -0,0 +1,642 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { type Table, connect } from "../lancedb"; +import { + Table as ArrowTable, + DataType, + Field, + Float32, + LargeBinary, + RecordBatch, + Schema, + Struct, + Uint8, + Uint32, + Uint64, + Utf8, + makeArrowTable, + tableToIPC, + vectorFromArray, +} from "../lancedb/arrow"; + +const IDENTITY_A = `v1:${"a".repeat(64)}`; +const IDENTITY_B = `v1:${"b".repeat(64)}`; +const image = new Field( + "image", + new Struct([ + new Field("kind", new Uint8(), false), + new Field("position", new Uint64(), true), + new Field("size", new Uint64(), true), + new Field("blob_id", new Uint32(), false), + new Field("blob_uri", new Utf8(), false), + ]), + true, + // Native descriptor scans replace the logical extension metadata. + new Map([ + ["lance-encoding:blob", "true"], + ["lance-encoding:packed", "true"], + ]), +); +const schema = new Schema([new Field("label", new Utf8(), false), image]); +const description = { + fields: [ + { name: "label", type: { type: "string" }, nullable: false }, + { + name: "image", + nullable: true, + metadata: { "ARROW:extension:name": "lance.blob.v2" }, + type: { + type: "struct", + fields: ["position", "size"].map((name) => ({ + name, + type: { type: "uint64" }, + nullable: true, + })), + }, + }, + ], +}; + +type Request = { + path: string; + body: Record; + raw: string; + identity: string | string[] | undefined; +}; + +interface ServerOptions { + queryBlob?: Field; + describeBlobName?: string | null; + nestedBlob?: boolean; + queryVersion?: string | null; + queryIdentity?: string | null; + echo?: string | null; + empty?: boolean; + values?: boolean; + advanceQueries?: boolean; + otherLegIdentity?: string | null; + otherLegVersion?: string; +} + +// A real HTTP service: the query finishes on A, then the logical table changes +// before the deferred blob request. Recreating B reuses both version and row IDs. +async function withSnapshotServer( + change: "recreate" | "overwrite", + run: (table: Table, requests: Request[]) => Promise, + options: ServerOptions = {}, +) { + const requests: Request[] = []; + let changed = false; + const queryBlob = options.queryBlob ?? image; + const queryOutputSchema = options.nestedBlob + ? new Schema([ + schema.fields[0], + new Field("extra", new Struct([queryBlob]), true), + ]) + : new Schema([schema.fields[0], queryBlob]); + const server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + try { + const raw = Buffer.concat(chunks).toString() || "{}"; + const body = JSON.parse(raw); + const path = req.url ?? ""; + const identity = req.headers["x-lancedb-query-snapshot"]; + requests.push({ path, body, raw, identity }); + res.setHeader("phalanx-version", "0.5.0"); + if (path.endsWith("/describe/")) { + res.setHeader("content-type", "application/json"); + res.end( + JSON.stringify({ + version: changed && change === "overwrite" ? 2 : 1, + schema: { + fields: description.fields.flatMap((field) => { + if (field.name !== "image") return [field]; + if (options.describeBlobName === null) return []; + return [ + { ...field, name: options.describeBlobName ?? "image" }, + ]; + }), + }, + }), + ); + } else if (path.endsWith("/query/")) { + const vector = (body.vector?.length ?? 0) > 0; + const advanced = options.advanceQueries === true && changed; + const label = advanced ? "B" : "A"; + const columns: [string, string][] = + body.columns === undefined + ? queryOutputSchema.fields.map((field) => [ + field.name, + field.name, + ]) + : Array.isArray(body.columns) + ? body.columns.map((name: string) => [name, name]) + : Object.entries(body.columns); + const queryFields = columns.map(([output, source]) => + queryOutputSchema.fields + .find((field) => field.name === source)! + .clone({ name: output }), + ); + if (body.with_row_id) { + queryFields.push(new Field("_rowid", new Uint64(), false)); + } + if (vector || body.full_text_query) { + queryFields.push( + new Field(vector ? "_distance" : "_score", new Float32(), false), + ); + } + // Forged IPC metadata must never substitute for authoritative headers. + const querySchema = new Schema( + queryFields, + new Map([ + ["lancedb:query_version", "999"], + ["lancedb:query_snapshot", IDENTITY_B], + ]), + ); + const values = options.empty + ? [] + : options.values + ? ["A", null, ""] + : [label]; + const rows = values.map((value, index) => { + const row: Record = {}; + for (const [output, source] of columns) { + const descriptor = + value === null + ? null + : { + kind: 0, + position: 0n, + size: BigInt(value.length), + // biome-ignore lint/style/useNamingConvention: Native Arrow field name. + blob_id: 0, + // biome-ignore lint/style/useNamingConvention: Native Arrow field name. + blob_uri: "", + }; + row[output] = + source === "image" + ? descriptor + : source === "extra" + ? descriptor === null + ? null + : { image: descriptor } + : label; + } + if (body.with_row_id) row._rowid = BigInt(index); + if (vector || body.full_text_query) { + row[vector ? "_distance" : "_score"] = 0.5; + } + return row; + }); + const result = + rows.length === 0 + ? new ArrowTable(querySchema) + : new ArrowTable( + querySchema, + Object.fromEntries( + queryFields.map((field) => [ + field.name, + vectorFromArray( + rows.map((row) => row[field.name]), + field.type, + ), + ]), + ), + ); + res.setHeader("content-type", "application/vnd.apache.arrow.stream"); + const version = + vector && options.otherLegVersion !== undefined + ? options.otherLegVersion + : options.queryVersion; + const snapshot = + vector && options.otherLegIdentity !== undefined + ? options.otherLegIdentity + : options.queryIdentity; + res.setHeader("x-lancedb-version", "1"); + if (version !== null) { + res.setHeader( + "x-lancedb-query-version", + version ?? (advanced ? "2" : "1"), + ); + } + if (snapshot !== null) { + res.setHeader( + "x-lancedb-query-snapshot", + snapshot ?? (advanced ? IDENTITY_B : IDENTITY_A), + ); + } + changed = true; + res.end(tableToIPC(result, "stream")); + } else if (path.endsWith("/fetch_blobs/")) { + const requestedVersion = /"version":([0-9]+)/.exec(raw)?.[1]; + const readsOriginal = + change === "overwrite" && + requestedVersion === (options.queryVersion ?? "1"); + const actualIdentity = readsOriginal ? IDENTITY_A : IDENTITY_B; + // An older serving node may ignore the guard and answer successfully; + // its echo must still be verified before the client uses any bytes. + if (options.echo !== null) { + res.setHeader( + "x-lancedb-query-snapshot", + options.echo ?? actualIdentity, + ); + } + res.setHeader("content-type", "application/vnd.apache.arrow.stream"); + const payloads = options.values + ? ["A", null, ""] + : [readsOriginal ? "A" : "B"]; + res.end( + tableToIPC( + makeArrowTable( + (body.row_ids as number[]).map((id) => ({ + [String(body.column)]: + payloads[id] === null ? null : Buffer.from(payloads[id]!), + })), + { + schema: new Schema([ + new Field(String(body.column), new LargeBinary(), true), + ]), + }, + ), + "stream", + ), + ); + } else { + res.writeHead(404).end(path); + } + } catch (error) { + res.writeHead(500).end(String(error)); + } + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${ + (server.address() as AddressInfo).port + }`, + }); + await run(await db.openTable("test"), requests); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +const fetchRequests = (requests: Request[]) => + requests.filter((request) => request.path.endsWith("/fetch_blobs/")); +const queryRequests = (requests: Request[]) => + requests.filter((request) => request.path.endsWith("/query/")); + +const keepFtsReranker = { + async rerankHybrid(_query: string, _vector: RecordBatch, fts: RecordBatch) { + const fields = fts.schema.fields.map((field) => + field.name === "_score" + ? field.clone({ name: "_relevance_score" }) + : field, + ); + return new RecordBatch( + new Schema(fields, fts.schema.metadata), + fts.data.clone(new Struct(fields)), + ); + }, +}; + +describe("remote blob query snapshot", () => { + it.each([ + image.clone({ metadata: new Map() }), + new Field( + "image", + new Struct(image.type.children.slice(1, 3)), + true, + image.metadata, + ), + ])( + "leaves plain structs and v1 descriptors unchanged: %s", + async (queryBlob) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const result = await table.query().toArrow({ blobMode: "bytes" }); + expect(DataType.isStruct(result.getChild("image")!.type)).toBe(true); + expect(result.toArray()[0].image.size).toBe(1n); + expect(fetchRequests(requests)).toHaveLength(0); + }, + { queryBlob }, + ); + }, + ); + + it("still recognizes extension-marked Blob results", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const rows = await table.query().toArray({ blobMode: "bytes" }); + expect(Buffer.from(rows[0].image).toString()).toBe("A"); + expect(fetchRequests(requests)).toHaveLength(1); + }, + { + queryBlob: image.clone({ + metadata: new Map([["ARROW:extension:name", "lance.blob.v2"]]), + }), + }, + ); + }); + + it.each([ + [null, false], + [null, true], + ["old_image", false], + ["old_image", true], + ] as const)( + "uses the query schema after cached blob %s changes (alias: %s)", + async (describeBlobName, alias) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + expect(await table.blobColumns()).toEqual( + describeBlobName === null ? [] : [describeBlobName], + ); + const query = table.query(); + if (alias) query.select({ "photo.image": "image" }); + const output = alias ? "photo.image" : "image"; + const result = await query.toArrow({ blobMode: "bytes" }); + expect(DataType.isLargeBinary(result.getChild(output)!.type)).toBe( + true, + ); + expect( + result + .toArray() + .map((row) => + row[output] === null + ? null + : Buffer.from(row[output]).toString(), + ), + ).toEqual(["A", null, ""]); + expect( + result.schema.fields.some((field) => field.name === "_rowid"), + ).toBe(false); + expect(queryRequests(requests)).toHaveLength(1); + expect(fetchRequests(requests)).toHaveLength(1); + expect(fetchRequests(requests)[0].body.column).toBe("image"); + expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A); + }, + { describeBlobName, values: true }, + ); + }, + ); + + it("maps nested query fields through literal aliases despite a stale schema", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + expect(await table.blobColumns()).toEqual([]); + const rows = await table + .query() + .select({ "container.alias": "extra" }) + .toArray({ blobMode: "bytes" }); + expect( + rows.map((row) => + row["container.alias"] === null + ? null + : Buffer.from(row["container.alias"].image).toString(), + ), + ).toEqual(["A", null, ""]); + expect(queryRequests(requests)).toHaveLength(1); + expect(fetchRequests(requests)[0].body.column).toBe("extra.image"); + expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A); + }, + { nestedBlob: true, describeBlobName: null, values: true }, + ); + }); + + it.each(["toArrow", "toArray"] as const)( + "%s rejects payloads from a recreated table with reused version and row IDs", + async (terminal) => { + await withSnapshotServer("recreate", async (table, requests) => { + await expect( + table.query()[terminal]({ blobMode: "bytes" }), + ).rejects.toThrow(/snapshot identity/); + const [fetch] = fetchRequests(requests); + expect(fetch.body.version).toBe(1); + expect(fetch.body.row_ids).toEqual([0]); + expect(fetch.body.column).toBe("image"); + expect(fetch.identity).toBe(IDENTITY_A); + }); + }, + ); + + it("keeps the producing snapshot after an overwrite without rerunning the query", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const rows = await table.query().toArray({ blobMode: "bytes" }); + expect(rows[0].label).toBe("A"); + expect(Buffer.from(rows[0].image).toString()).toBe("A"); + expect(queryRequests(requests)).toHaveLength(1); + const [fetch] = fetchRequests(requests); + expect(fetch.body.version).toBe(1); + expect(fetch.identity).toBe(IDENTITY_A); + expect(await table.version()).toBe(2); + const [latest] = await table.query().toArray({ blobMode: "bytes" }); + expect(latest.label).toBe("B"); + expect(Buffer.from(latest.image).toString()).toBe("B"); + expect(fetchRequests(requests)[1].identity).toBe(IDENTITY_B); + }, + { advanceQueries: true }, + ); + }); + + it.each([ + { queryVersion: null }, + { queryVersion: "0" }, + { queryVersion: "18446744073709551616" }, + { queryVersion: "invalid" }, + { queryIdentity: null }, + { queryIdentity: "v2:unsupported" }, + ])("refuses bytes without authoritative capability %j", async (options) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const [descriptor] = await table.query().toArray(); + expect(descriptor.image.size).toBe(1n); + await expect( + table.query().toArray({ blobMode: "bytes" }), + ).rejects.toThrow(/blobMode.*bytes.*requires.*snapshot/); + expect(fetchRequests(requests)).toHaveLength(0); + }, + options, + ); + }); + + it("rejects a serving node without the snapshot echo", async () => { + await withSnapshotServer( + "overwrite", + async (table) => { + await expect( + table.query().toArray({ blobMode: "bytes" }), + ).rejects.toThrow(/snapshot identity/); + }, + { echo: null }, + ); + }); + + it("keeps aliases, NULL, empty bytes, and explicit row IDs", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const query = table + .query() + .select({ caption: "label", "photo.image": "image" }); + const rows = await query.withRowId().toArray({ blobMode: "bytes" }); + expect(rows.map((row) => row._rowid)).toEqual([0n, 1n, 2n]); + expect( + rows.map((row) => + row["photo.image"] === null + ? null + : Buffer.from(row["photo.image"]).toString(), + ), + ).toEqual(["A", null, ""]); + expect(rows[0].caption).toBe("A"); + expect(fetchRequests(requests)[0].body.column).toBe("image"); + const [descriptor] = await query.toArray(); + expect(descriptor["photo.image"].size).toBe(1n); + }, + { values: true }, + ); + }); + + it("preserves an empty bytes schema without fetching payloads", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const result = await table.query().toArrow({ blobMode: "bytes" }); + expect(result.numRows).toBe(0); + expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe( + true, + ); + expect(result.schema.fields.map((field) => field.name)).toEqual([ + "label", + "image", + ]); + expect(fetchRequests(requests)).toHaveLength(0); + }, + { empty: true }, + ); + }); + + it("passes the query version without rounding through a JS number", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + await table.query().toArray({ blobMode: "bytes" }); + expect(fetchRequests(requests)[0].raw).toContain( + '"version":9007199254740993', + ); + }, + { queryVersion: "9007199254740993" }, + ); + }); + + it.each(["vector", "hybrid"])( + "materializes the actual %s query entry point", + async (kind) => { + await withSnapshotServer("overwrite", async (table, requests) => { + const query = table.query().nearestTo([0.1, 0.2]); + if (kind === "hybrid") query.fullTextSearch("A"); + const rows = await query.toArray({ blobMode: "bytes" }); + expect(Buffer.from(rows[0].image).toString()).toBe("A"); + expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A); + expect(queryRequests(requests)).toHaveLength(kind === "hybrid" ? 2 : 1); + }); + }, + ); + + it("allows scalar-only bytes queries on older servers", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const [row] = await table + .query() + .select(["label"]) + .toArray({ blobMode: "bytes" }); + expect(row.label).toBe("A"); + expect(Object.keys(row)).toEqual(["label"]); + expect(fetchRequests(requests)).toHaveLength(0); + // Row IDs are requested before the executed output schema is known, + // then hidden from scalar-only results without requiring capability. + expect(queryRequests(requests)[0].body.with_row_id).toBe(true); + }, + { queryIdentity: null, queryVersion: null }, + ); + }); + + it.each([false, true])( + "preserves snapshot proof across a custom reranker (empty: %s)", + async (empty) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const result = await table + .query() + .nearestTo([0.1, 0.2]) + .fullTextSearch("A") + .rerank(keepFtsReranker) + .toArrow({ blobMode: "bytes" }); + expect(result.numRows).toBe(empty ? 0 : 1); + expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe( + true, + ); + expect(fetchRequests(requests)).toHaveLength(empty ? 0 : 1); + }, + { empty }, + ); + }, + ); + + it("does not trust a custom reranker's first-leg snapshot when the legs disagree", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const query = table + .query() + .nearestTo([0.1, 0.2]) + .fullTextSearch("A") + .rerank(keepFtsReranker); + await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow( + /snapshot/, + ); + expect(fetchRequests(requests)).toHaveLength(0); + }, + { otherLegIdentity: IDENTITY_B }, + ); + }); + + it.each([ + { otherLegIdentity: IDENTITY_B }, + { otherLegIdentity: null }, + { otherLegVersion: "2" }, + ])( + "refuses hybrid bytes when its actual query legs disagree %j", + async (options) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const query = table.query().nearestTo([0.1, 0.2]).fullTextSearch("A"); + await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow( + /snapshot/, + ); + expect(fetchRequests(requests)).toHaveLength(0); + expect(await query.toArray()).toHaveLength(1); + }, + options, + ); + }, + ); +}); diff --git a/nodejs/__test__/rerankers.test.ts b/nodejs/__test__/rerankers.test.ts index 256ef686c..8e3a36f98 100644 --- a/nodejs/__test__/rerankers.test.ts +++ b/nodejs/__test__/rerankers.test.ts @@ -1,13 +1,42 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -import { spawn } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; import * as path from "node:path"; import { RecordBatch } from "apache-arrow"; import * as tmp from "tmp"; import { Connection, Index, Table, connect, makeArrowTable } from "../lancedb"; import { RRFReranker } from "../lancedb/rerankers"; +it("reranks record batches created by an ESM Arrow import", () => { + const script = ` +import assert from "node:assert/strict"; +import { tableFromArrays } from "apache-arrow"; +import { rerankers } from "./dist/index.js"; + +const ids = [1n, 9007199254740993n]; +const batch = tableFromArrays({ _rowid: new BigUint64Array(ids) }).batches[0]; +const reranker = await rerankers.RRFReranker.create(); +const result = await reranker.rerankHybrid("", batch, batch); + +assert.equal(result.numRows, 2); +assert.deepEqual(Array.from(result.getChild("_rowid").toArray()), ids); +const scores = result.getChild("_relevance_score").toArray(); +assert.ok(Math.abs(scores[0] - 2 / 61) < 1e-8); +assert.ok(Math.abs(scores[1] - 2 / 62) < 1e-8); + +const oneSide = await reranker.rerankHybrid("", batch, batch.slice(0, 0)); +assert.deepEqual(Array.from(oneSide.getChild("_rowid").toArray()), ids); +const oneSideScores = oneSide.getChild("_relevance_score").toArray(); +assert.ok(Math.abs(oneSideScores[0] - 1 / 61) < 1e-8); +assert.ok(Math.abs(oneSideScores[1] - 1 / 62) < 1e-8); +`; + execFileSync(process.execPath, ["--input-type=module", "-e", script], { + cwd: path.resolve(__dirname, ".."), + timeout: 10_000, + }); +}); + describe("rerankers", function () { let tmpDir: tmp.DirResult; let conn: Connection; diff --git a/nodejs/__test__/s3_integration.test.ts b/nodejs/__test__/s3_integration.test.ts index e4bc46806..35ce478a8 100644 --- a/nodejs/__test__/s3_integration.test.ts +++ b/nodejs/__test__/s3_integration.test.ts @@ -282,7 +282,7 @@ maybeDescribe("DynamoDB Lock", () => { }); it("can be used to configure a DynamoDB table for commit log", async () => { - const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`; + const uri = `s3+ddb://${bucket.name}/concurrent-appends?ddbTableName=${commitTable.name}`; const db = await connect(uri, { storageOptions: CONFIG, readConsistencyInterval: 0, @@ -307,7 +307,7 @@ maybeDescribe("DynamoDB Lock", () => { }); it("clears dynamodb state after dropping all tables", async () => { - const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`; + const uri = `s3+ddb://${bucket.name}/drop-all-tables?ddbTableName=${commitTable.name}`; const db = await connect(uri, { storageOptions: CONFIG, readConsistencyInterval: 0, diff --git a/nodejs/__test__/sql_parameters.test.ts b/nodejs/__test__/sql_parameters.test.ts new file mode 100644 index 000000000..2e8c979df --- /dev/null +++ b/nodejs/__test__/sql_parameters.test.ts @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { Int32, Table, tableFromIPC, vectorFromArray } from "../lancedb/arrow"; +import { toParameterBuffer } from "../lancedb/sql"; +import { LocalTable } from "../lancedb/table"; + +describe("SQL parameter encoding", () => { + test.each([false, true])( + "prewarm submission and preview forward typed bindings (named: %s)", + async (named) => { + const attack = "training' OR TRUE; DROP TABLE items; --"; + const parameters = named ? { minimum: 42n, tag: attack } : [42n, attack]; + const filter = named + ? "id >= $minimum AND tag = $tag" + : "id >= $1 AND tag = $2"; + const submission = jest.fn().mockResolvedValue({}); + const preview = jest.fn().mockResolvedValue( + JSON.parse(`{ + "table_version": 42, + "plan": "metadata preview", + "pruning": { + "mode": "zonemap_ranges", + "input_fragments": 3, + "selected_fragments": 1, + "pruned_fragments": 2, + "selected_row_ranges": 2 + } + }`), + ); + const table = new LocalTable({ + prewarmDataAsync: submission, + explainPrewarmData: preview, + } as never); + await table.prewarmDataAsync({ filter, parameters }); + const plan = await table.explainPrewarmData({ filter, parameters }); + expect(plan.tableVersion).toBe(42); + expect(plan.pruning.selectedFragments).toBe(1); + for (const call of [submission, preview]) { + expect(call).toHaveBeenCalledTimes(1); + const options = call.mock.calls[0][0]; + expect(options.filter).toBe(filter); + expect(options.filter).not.toContain(attack); + expect(Buffer.isBuffer(options.parameters)).toBe(true); + const batch = tableFromIPC(options.parameters); + expect(batch.schema.fields.map((field) => field.name)).toEqual( + named ? ["minimum", "tag"] : ["1", "2"], + ); + expect(batch.getChildAt(0)?.get(0)).toBe(42n); + expect(batch.getChildAt(1)?.get(0)).toBe(attack); + } + }, + ); + + test("positional and named bindings preserve values without SQL interpolation", async () => { + const attack = "training' OR TRUE; DROP TABLE items; --"; + const date = new Date("2026-01-02T00:00:00Z"); + const batch = tableFromIPC( + await toParameterBuffer([ + 42n, + attack, + null, + true, + date, + 0.7, + new Uint8Array([1, 2]), + ]), + ); + expect(batch.schema.fields.map((field) => field.name)).toEqual([ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + ]); + expect(batch.getChildAt(0)?.get(0)).toBe(42n); + expect(batch.getChildAt(1)?.get(0)).toBe(attack); + expect(batch.getChildAt(2)?.get(0)).toBeNull(); + expect(batch.getChildAt(4)?.get(0)).toBe(date.getTime()); + const named = tableFromIPC( + await toParameterBuffer({ minimum: 42n, tag: attack }), + ); + expect(named.schema.fields.map((field) => field.name)).toEqual([ + "minimum", + "tag", + ]); + expect(named.getChild("tag")?.get(0)).toBe(attack); + }); + + test("explicit Arrow input preserves its types", async () => { + const input = new Table({ minimum: vectorFromArray([42], new Int32()) }); + for (const parameters of [input, input.batches[0]]) { + const decoded = tableFromIPC(await toParameterBuffer(parameters)); + expect(decoded.schema.fields[0].type.toString()).toBe("Int32"); + expect(decoded.getChildAt(0)?.get(0)).toBe(42); + } + }); + + test.each([ + [], + { value: undefined }, + { value: 2 ** 53 }, + { value: 1n << 63n }, + { value: {} }, + { value: new Date("invalid") }, + ])("invalid parameters fail before submission: %p", async (parameters) => { + await expect(toParameterBuffer(parameters as never)).rejects.toThrow(); + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index bbe1d6a71..0971d66f9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -11,11 +11,14 @@ import { AutoQuery, type BlobInput, type BlobMode, + type CompactionOptions, Connection, MatchQuery, PhraseQuery, Query, Table, + TableDelta, + TableDeltaReader, VectorQuery, blob, connect, @@ -937,7 +940,8 @@ describe("merge insert", () => { .mergeInsert("a") .whenMatchedUpdateAll() .whenNotMatchedInsertAll() - .execute(newData, { timeoutMs: 10_000 }); + .useIndex(false) + .execute(newData, { timeoutMs: 10_000, retries: 0 }); expect(mergeInsertRes).toHaveProperty("version"); expect(mergeInsertRes.version).toBe(2); expect(mergeInsertRes.numInsertedRows).toBe(1); @@ -1831,6 +1835,172 @@ describe("When creating an index", () => { expect(fs.readdirSync(indexDir)).toHaveLength(1); }); + describe("on a GeoArrow column", () => { + // Row `10 * y + x` sits at (x, y). The triangle's bounding box covers the + // 25 points with x <= 4 and y <= 4, but only the 15 with x + y <= 4 + // intersect the triangle itself. + const inTriangle = + "ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))"; + const triangleIds = [0, 1, 2, 3, 4, 10, 11, 12, 13, 20, 21, 22, 30, 31, 40]; + let geoTbl: Table; + + beforeEach(async () => { + const point = new Struct([ + new Field("x", new Float64(), false), + new Field("y", new Float64(), false), + ]); + const geoSchema = new Schema([ + new Field("id", new Int32(), false), + new Field( + "geom", + point, + true, + new Map([ + ["ARROW:extension:name", "geoarrow.point"], + ["ARROW:extension:metadata", "{}"], + ]), + ), + new Field( + "vec", + new FixedSizeList(2, new Field("item", new Float32())), + ), + ]); + const data = makeArrowTable( + Array.from({ length: 100 }, (_, i) => ({ + id: i, + geom: { x: i % 10, y: Math.floor(i / 10) }, + vec: [i, i], + })), + { schema: geoSchema }, + ); + const db = await connect(tmpDir.name); + geoTbl = await db.createTable("points", data); + }); + + const ids = (rows: { id: number }[]) => rows.map((row) => row.id); + + test("create an RTree index and filter with it", async () => { + await geoTbl.createIndex("geom", { config: Index.rtree() }); + expect(await geoTbl.listIndices()).toEqual([ + expect.objectContaining({ + name: "geom_idx", + indexType: "RTree", + columns: ["geom"], + }), + ]); + const stats = await geoTbl.indexStats("geom_idx"); + expect(stats?.indexType).toEqual("RTREE"); + expect(stats?.numIndexedRows).toEqual(100); + + const query = geoTbl.query().where(inTriangle); + expect(await query.explainPlan(true)).toContain("ScalarIndexQuery"); + expect(ids(await query.toArray()).sort((a, b) => a - b)).toEqual( + triangleIds, + ); + }); + + test("prefilter a vector search with an RTree index", async () => { + await geoTbl.createIndex("geom", { + config: Index.rtree({ pageSize: 16 }), + }); + // Row 99 sits outside the triangle; its nearest vectors are 98, 97, ... + const prefiltered = geoTbl + .query() + .nearestTo([99, 99]) + .where(inTriangle) + .limit(5); + expect(await prefiltered.explainPlan(true)).toContain("ScalarIndexQuery"); + expect(ids(await prefiltered.toArray())).toEqual([40, 31, 30, 22, 21]); + + const postfiltered = geoTbl + .query() + .nearestTo([99, 99]) + .where(inTriangle) + .postfilter() + .limit(5); + expect(await postfiltered.toArray()).toEqual([]); + }); + + test("reject invalid RTree options", async () => { + for (const pageSize of [1, 0, -1, 2.5, Number.NaN, 2 ** 32]) { + expect(() => Index.rtree({ pageSize })).toThrow( + "page_size must be at least 2", + ); + } + await expect( + geoTbl.createIndex("id", { config: Index.rtree() }), + ).rejects.toThrow("GeoArrow"); + }); + }); + + test.each([ + ["ZoneMap", undefined, "ZoneMap"], + ["BTREE", undefined, "BTree"], + [ + "bloomfilter", + // biome-ignore lint/style/useNamingConvention: plugin param name + { number_of_items: 64, probability: 0.01 }, + "BloomFilter", + ], + ["bloomfilter", '{"number_of_items": 64}', "BloomFilter"], + ])( + "create a scalar plugin index by name (%s, %p)", + async (indexType, params, expectedType) => { + await tbl.createIndex("id", { + config: Index.plugin(indexType, params), + name: "id_plugin", + }); + + const indices = await tbl.listIndices(); + expect(indices).toHaveLength(1); + expect(indices[0].name).toBe("id_plugin"); + expect(indices[0].indexType).toBe(expectedType); + expect(indices[0].columns).toEqual(["id"]); + + const query = tbl.query().where("id = 42"); + expect(await query.explainPlan()).toContain("ScalarIndexQuery"); + expect(await query.toArray()).toHaveLength(1); + }, + ); + + test("lists a scalar plugin without a LanceDB type by its own name", async () => { + const db = await connect(tmpDir.name); + const textTbl = await db.createTable("minhash", [ + { text: "alpha beta" }, + { text: "beta gamma" }, + ]); + await textTbl.createIndex("text", { config: Index.plugin("minhashlsh") }); + + const indices = await textTbl.listIndices(); + expect(indices).toHaveLength(1); + expect(indices[0].indexType).toBe("MinHashLsh"); + }); + + test("rejects invalid scalar plugin configs", async () => { + expect(() => Index.plugin("")).toThrow("must not be empty"); + expect(() => Index.plugin(" ")).toThrow("must not be empty"); + expect(() => Index.plugin("zonemap", "[1]")).toThrow( + "must be a JSON object, got an array", + ); + expect(() => Index.plugin("zonemap", "null")).toThrow( + "must be a JSON object, got null", + ); + expect(() => Index.plugin("zonemap", "{not json")).toThrow( + "not valid JSON", + ); + expect(() => + Index.plugin("zonemap", [1] as unknown as Record), + ).toThrow("must be a JSON object, got an array"); + + await expect( + tbl.createIndex("id", { config: Index.plugin("NoSuchPlugin") }), + ).rejects.toThrow("No scalar index plugin found for name 'nosuchplugin'"); + await expect( + tbl.createIndex("id", { config: Index.plugin("ngram") }), + ).rejects.toThrow(/ngram/i); + expect(await tbl.listIndices()).toHaveLength(0); + }); + test("should be able to get index stats", async () => { await tbl.createIndex("id"); @@ -3018,6 +3188,43 @@ describe("when dealing with blob columns", () => { expect(bytes.map((b) => b?.toString())).toEqual(["new", "hi"]); }); + it("fetchBlobRanges reads local ranges with order, duplicates, nulls and validation", async () => { + const { table, rowIds } = await openBlobTable(); + const [alphaId, betaId, nullId] = rowIds; + const requests = [ + { rowId: betaId, offset: 1n, length: 3n }, + { rowId: alphaId, offset: 0n, length: 2n }, + { rowId: nullId, offset: 0n, length: 1n }, + { rowId: alphaId, offset: 5n, length: 0n }, + { rowId: betaId, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("eta"), + Buffer.from("al"), + null, + Buffer.alloc(0), + Buffer.from("eta"), + ]); + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + await expect( + table.fetchBlobRanges("image", [ + { rowId: alphaId, offset: 4n, length: 2n }, + ]), + ).rejects.toThrow(); + await expect( + table.fetchBlobRanges("image", [ + { rowId: (1n << 63n) - 1n, offset: 0n, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + expect( + await table.fetchBlobRanges("image", requests, { + signal: controller.signal, + }), + ).toHaveLength(5); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + }); + it("discovers blob columns", async () => { const { table } = await openBlobTable(); expect(await table.blobColumns()).toEqual(["image"]); @@ -3233,29 +3440,6 @@ describe("when dealing with blob columns", () => { expect(await handle!.read()).toEqual(alpha); }); - it("cancels an in-flight read", async () => { - const db = await connect(tmpDir.name); - const schema = new Schema([ - new Field("id", new Int64(), true), - blob("payload", { inlineSizeThreshold: 0, dedicatedSizeThreshold: 1 }), - ]); - const payload = Buffer.alloc(32 * 1024 * 1024, 7); - const table = await db.createTable("large_blobs", [{ id: 1n, payload }], { - schema, - }); - const [row] = await table.query().withRowId().toArray(); - const [handle] = await table.fetchBlobFiles("payload", [ - row._rowid as bigint, - ]); - const controller = new AbortController(); - const pending = handle!.readRange(0n, handle!.size(), { - signal: controller.signal, - }); - controller.abort(); - await expect(pending).rejects.toMatchObject({ name: "AbortError" }); - expect(await handle!.readRange(0n, 4n)).toEqual(payload.subarray(0, 4)); - }); - it("toArrow returns blob bytes with blobMode bytes", async () => { const { table, alpha, beta } = await openBlobTable(); const result = await table.query().toArrow({ blobMode: "bytes" }); @@ -3906,6 +4090,396 @@ describe("when dealing with tags", () => { await table.add([{ id: 3n, vector: [0.5, 0.6] }]); expect(await table.countRows()).toBe(2); }); + + it("defaults create version to the handle's visible version", async () => { + const conn = await connect(tmpDir.name, { + readConsistencyInterval: 0, + }); + const table = await conn.createTable("my_table", [{ id: 1 }]); + await table.add([{ id: 2 }]); + const tags = await table.tags(); + + await tags.create("live"); + expect(await tags.getVersion("live")).toBe(2); + + await table.checkout(1); + await tags.create("pinned"); + expect(await tags.getVersion("pinned")).toBe(1); + + // An explicit version is independent of the version this handle shows. + await tags.create("explicit", 2); + expect(await tags.getVersion("explicit")).toBe(2); + + // A tag checkout is still a visible version, not "latest". + await table.checkoutLatest(); + await table.add([{ id: 3 }]); + expect(await table.version()).toBe(3); + await table.checkout("live"); + await tags.create("tag-checkout"); + expect(await tags.getVersion("tag-checkout")).toBe(2); + }); +}); + +describe("when dealing with branches", () => { + let tmpDir: tmp.DirResult; + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + + it("forks from a tag on a branch with the same version as main", async () => { + const conn = await connect(tmpDir.name, { + readConsistencyInterval: 0, + }); + const table = await conn.createTable("my_table", [{ i: 0 }]); + const branches = await table.branches(); + + const exp = await branches.create("exp"); + await exp.add([{ i: 10 }]); + const expVersion = await exp.version(); + await (await exp.tags()).create("exp-v2", expVersion); + + // main reaches the same numeric version with different rows. + await table.add([{ i: 100 }]); + expect(await table.version()).toBe(expVersion); + + const fromTag = await branches.create("from-tag", { + fromTag: "exp-v2", + }); + expect(fromTag.currentBranch()).toBe("from-tag"); + expect(await fromTag.countRows("i = 10")).toBe(1); + expect(await fromTag.countRows("i = 100")).toBe(0); + + // The existing positional branch/version path keeps its ordering. + const positional = await branches.create("from-exp", "exp", expVersion); + expect(positional.currentBranch()).toBe("from-exp"); + expect(await positional.countRows("i = 10")).toBe(1); + expect(await positional.countRows("i = 100")).toBe(0); + }); + + it("rejects fromTag combined with another source before main normalization", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("my_table", [{ i: 0 }]); + await (await table.tags()).create("baseline"); + const branches = await table.branches(); + + // fromRef="main" must not normalize the conflict away. + const mixedSources = { fromTag: "baseline", fromRef: "main" }; + await expect(branches.create("conflict", mixedSources)).rejects.toThrow( + "fromTag cannot be combined", + ); + + // JavaScript callers can still pass the legacy version position. + const createWithLegacyVersion = branches.create.bind(branches) as ( + name: string, + options: { fromTag: string }, + fromVersion: number, + ) => Promise
      ; + await expect( + createWithLegacyVersion("conflict", { fromTag: "baseline" }, 1), + ).rejects.toThrow("fromTag cannot be combined"); + expect(await branches.list()).not.toHaveProperty("conflict"); + }); + + it("hints at fromTag only for a missing Embedded branch", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("my_table", [{ i: 0 }]); + const branches = await table.branches(); + const base = await branches.create("base"); + await base.add([{ i: 1 }]); + await (await table.tags()).create("baseline"); + + // A tag passed through fromRef keeps the original failure and gains a + // static hint without probing the ref again. + await expect(branches.create("missing", "baseline")).rejects.toThrow( + 'branches.create("missing", { fromTag: "baseline" })', + ); + + // A missing version is not an unresolved branch, so it gets no hint. + const missingVersion = await branches + .create("missing-version", "base", 9999) + .then( + () => undefined, + (error: Error) => error, + ); + expect(missingVersion?.message).toContain("9999"); + expect(missingVersion?.message).not.toContain("fromTag"); + }); +}); + +describe("when dealing with table delta", () => { + let tmpDir: tmp.DirResult; + // biome-ignore lint/style/useNamingConvention: storage option wire format + const stableRowIds = { new_table_enable_stable_row_ids: "true" }; + + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + + async function readDelta( + reader: TableDeltaReader, + ): Promise { + const batches: arrow.RecordBatch[] = []; + for await (const batch of reader) { + batches.push(batch); + } + return batches; + } + + function deltaColumn(batches: arrow.RecordBatch[], name: string): unknown[] { + return batches.flatMap((batch) => batch.getChild(name)?.toJSON() ?? []); + } + + it("streams rows, transactions, and empty schemas", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable( + "delta_rows", + [ + { id: 1, value: 0 }, + { id: 2, value: 0 }, + ], + { mode: "overwrite", storageOptions: stableRowIds }, + ); + const tags = await table.tags(); + await tags.create("baseline", await table.version()); + await table.add([{ id: 3, value: 0 }]); + await table.update({ where: "id = 1", values: { value: 10 } }); + await table.delete("id = 2"); + + const delta = await table.delta("baseline", 4n); + expect(delta.beginVersion).toBe(1n); + expect(delta.endVersion).toBe(4n); + + const insertedReader = delta.insertedRows(); + expect( + (await insertedReader.schema()).fields.map((field) => field.name), + ).toEqual([ + "id", + "value", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + const inserted = await readDelta(insertedReader); + expect(deltaColumn(inserted, "id")).toEqual([3]); + + const updated = await readDelta(delta.updatedRows()); + expect(deltaColumn(updated, "id")).toEqual([1]); + const upserted = await readDelta(delta.upsertedRows()); + expect((deltaColumn(upserted, "id") as number[]).sort()).toEqual([1, 3]); + + const deleted = await readDelta(delta.deletedRowIds()); + expect(deleted).toHaveLength(1); + expect(deleted[0].schema.fields.map((field) => field.name)).toEqual([ + "_rowid", + ]); + const deletedIds = deltaColumn(deleted, "_rowid"); + expect(deletedIds).toHaveLength(1); + expect(typeof deletedIds[0]).toBe("bigint"); + + const transactions = await delta.listTransactions(); + expect(transactions.map((tx) => tx.operation)).toEqual([ + "Append", + "Update", + "Delete", + ]); + expect(transactions.map((tx) => tx.readVersion)).toEqual([1n, 2n, 3n]); + expect(transactions.every((tx) => typeof tx.readVersion === "bigint")).toBe( + true, + ); + + // Early drop after the first batch must not throw or force the rest of the + // stream to materialize. + let batchesSeen = 0; + for await (const _batch of delta.upsertedRows()) { + batchesSeen += 1; + break; + } + expect(batchesSeen).toBe(1); + + const equal = await table.delta(2, 2); + const equalReader = equal.insertedRows(); + expect( + (await equalReader.schema()).fields.map((field) => field.name), + ).toEqual([ + "id", + "value", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + expect(await readDelta(equalReader)).toEqual([]); + expect( + (await equal.deletedRowIds().schema()).fields.map((field) => field.name), + ).toEqual(["_rowid"]); + expect(await equal.listTransactions()).toEqual([]); + }); + + it("pins the visible target without moving checkout state", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_pinned", [{ id: 1 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 2 }]); + await table.update({ where: "id = 1", values: { id: 10 } }); + + await table.checkout(2); + const pinned = await table.delta(1n); + expect(pinned.beginVersion).toBe(1n); + expect(pinned.endVersion).toBe(2n); + expect(deltaColumn(await readDelta(pinned.insertedRows()), "id")).toEqual([ + 2, + ]); + expect(await table.version()).toBe(2); + + const explicit = await table.delta(1n, 3n); + expect(deltaColumn(await readDelta(explicit.updatedRows()), "id")).toEqual([ + 10, + ]); + expect(await table.version()).toBe(2); + await table.checkoutLatest(); + }); + + it("does not start a rejected reader until it is used", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_lazy", [{ id: 1 }]); + await table.add([{ id: 2 }]); + + const delta = await table.delta(1); + const reader = delta.insertedRows(); + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + await new Promise((resolve) => setTimeout(resolve, 25)); + expect(unhandled).toEqual([]); + await expect(reader.schema()).rejects.toThrow(/stable row ids/); + await expect(reader.next()).rejects.toThrow(/stable row ids/); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); + + it("routes schema and Arrow decode failures through terminal cleanup", async () => { + let schemaOpens = 0; + const schemaFailure = new TableDelta({ + insertedRows: async () => { + schemaOpens += 1; + return { + schema: async () => { + throw new Error("schema export failed"); + }, + next: async () => { + throw new Error("reader must not poll after schema failure"); + }, + }; + }, + } as never); + + const schemaReader = schemaFailure.insertedRows(); + await expect(schemaReader.schema()).rejects.toThrow("schema export failed"); + await expect(schemaReader.next()).rejects.toThrow("schema export failed"); + expect(schemaOpens).toBe(1); + + const nextReader = schemaFailure.insertedRows(); + await expect(nextReader.next()).rejects.toThrow("schema export failed"); + expect(schemaOpens).toBe(2); + + let decodeOpens = 0; + const decodeFailure = new TableDelta({ + insertedRows: async () => { + decodeOpens += 1; + return { + schema: async () => Buffer.from("not an Arrow IPC schema"), + next: async () => { + throw new Error("reader must not poll after decode failure"); + }, + }; + }, + } as never); + + const decodeReader = decodeFailure.insertedRows(); + await expect(decodeReader.schema()).rejects.toThrow(); + await expect(decodeReader.next()).rejects.toThrow(); + expect(decodeOpens).toBe(1); + }); + + it("uses one reader cursor and releases it on early drop", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_reader", [{ id: 1 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 2 }]); + const delta = await table.delta(1); + + const reader = delta.insertedRows(); + expect(reader[Symbol.asyncIterator]()).toBe(reader); + const first = await reader.next(); + expect(first.done).toBe(false); + const [second, third] = await Promise.all([reader.next(), reader.next()]); + expect(second.done).toBe(true); + expect(third.done).toBe(true); + expect((await reader.schema()).fields.map((field) => field.name)).toEqual([ + "id", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + + const dropped = delta.insertedRows(); + for await (const _batch of dropped) { + break; + } + expect(await dropped.next()).toEqual({ done: true, value: undefined }); + expect((await dropped.schema()).fields.map((field) => field.name)).toEqual([ + "id", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + }); + + it("rejects invalid endpoints and cross-branch tags", async () => { + const conn = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + const table = await conn.createTable("delta_errors", [{ id: 0 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 1 }]); + const forkVersion = await table.version(); + + await expect(table.delta(0)).rejects.toThrow(/positive/); + await expect(table.delta(0n)).rejects.toThrow(/positive u64/); + await expect(table.delta(1n << 64n)).rejects.toThrow(/u64 bigint/); + await expect(table.delta(-1)).rejects.toThrow(/positive/); + await expect(table.delta("")).rejects.toThrow(/non-empty/); + await expect(table.delta(1.5)).rejects.toThrow(/safe integer/); + await expect(table.delta(Number.MAX_SAFE_INTEGER + 1)).rejects.toThrow( + /safe integer/, + ); + await expect(table.delta(2, 1)).rejects.toThrow(/newer than/); + await expect(table.delta(999)).rejects.toThrow(/does not exist/); + await expect(table.delta("missing-tag")).rejects.toThrow(/does not exist/); + + const branch = await (await table.branches()).create("exp"); + await branch.add([{ id: 2 }]); + await table.add([{ id: 100 }]); + expect(await branch.version()).toBe(await table.version()); + await (await table.tags()).create("main-tag", await table.version()); + await (await branch.tags()).create("exp-tag", await branch.version()); + + const sameBranch = await branch.delta(BigInt(forkVersion), "exp-tag"); + expect(sameBranch.endVersion).toBe(3n); + expect( + deltaColumn(await readDelta(sameBranch.insertedRows()), "id"), + ).toEqual([2]); + await expect(branch.delta("main-tag")).rejects.toThrow(/branch/i); + await expect(table.delta("exp-tag")).rejects.toThrow(/branch/i); + }); }); /** Returns a Date strictly later than every instant observed before the call. */ @@ -3997,7 +4571,93 @@ it("passes cleanupOlderThan to the native binding as an absolute timestamp", asy await table.optimize({ cleanupOlderThan: cutoff, deleteUnverified: true }); - expect(optimize).toHaveBeenCalledWith(cutoff.getTime(), true); + expect(optimize).toHaveBeenCalledWith(cutoff.getTime(), true, undefined); +}); + +it("forwards per-job compaction options to the native binding", async () => { + const optimize = jest.fn().mockResolvedValue({}); + const table = new LocalTable({ optimize } as never); + const compactionOptions = { + targetRowsPerFragment: 20, + maxSourceRows: 25, + ioBufferSize: 0, + batchSize: 8, + }; + await table.optimize({ compactionOptions }); + expect(optimize).toHaveBeenCalledWith( + undefined, + undefined, + compactionOptions, + ); +}); + +it("rejects unsupported JavaScript compaction options before native submission", async () => { + const optimize = jest.fn(); + const table = new LocalTable({ optimize } as never); + await expect( + table.optimize({ + compactionOptions: { + maxSourceBytes: 1024, + } as unknown as CompactionOptions, + }), + ).rejects.toThrow("Unsupported compaction option: maxSourceBytes"); + expect(optimize).not.toHaveBeenCalled(); +}); + +describe("per-job compaction options", () => { + let tmpDir: tmp.DirResult; + let table: Table; + beforeEach(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + table = await db.createTable( + "bounded", + Array.from({ length: 10 }, (_, id) => ({ id })), + ); + for (let f = 1; f < 8; f++) { + await table.add( + Array.from({ length: 10 }, (_, id) => ({ id: f * 10 + id })), + ); + } + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + it("bounds source work and preserves zero I/O buffering", async () => { + const stats = await table.optimize({ + compactionOptions: { + targetRowsPerFragment: 20, + maxSourceRows: 25, + ioBufferSize: 0, + batchSize: 8, + }, + }); + expect(stats.compaction.fragmentsRemoved).toBe(2); + expect(stats.compaction.fragmentsAdded).toBe(1); + expect(await table.countRows()).toBe(80); + const defaults = await table.optimize(); + expect(defaults.compaction.fragmentsRemoved).toBe(7); + expect(defaults.compaction.fragmentsAdded).toBe(1); + expect(await table.countRows()).toBe(80); + }); + const invalid: CompactionOptions[] = [ + { targetRowsPerFragment: 0 }, + { maxSourceRows: 0 }, + { batchSize: 0 }, + { ioBufferSize: -1 }, + { batchSize: 1.5 }, + { maxSourceRows: Number.NaN }, + { ioBufferSize: Number.POSITIVE_INFINITY }, + { maxSourceRows: Number.MAX_SAFE_INTEGER + 1 }, + { targetRowsPerFragment: 2 ** 32 }, + { batchSize: 2 ** 32 }, + ]; + it.each(invalid)("rejects invalid settings %p", async (compactionOptions) => { + await expect(table.optimize({ compactionOptions })).rejects.toThrow( + /safe integer/, + ); + expect(await table.countRows()).toBe(80); + }); }); describe.each(arrowVersions)( @@ -4576,15 +5236,121 @@ describe.each(arrowVersions)( ]; const table = await db.createTable("prewarm_data_test", data); - // prewarmData is only supported in LanceDB Enterprise. We verify the call - // is wired through napi and surfaces the expected error for both - // arg shapes (undefined and string[]). await expect(table.prewarmData()).rejects.toThrow( - "prewarm_data is currently only supported in LanceDB Enterprise", + "only supported on remote tables", ); await expect(table.prewarmData(["text"])).rejects.toThrow( - "prewarm_data is currently only supported in LanceDB Enterprise", + "only supported on remote tables", ); + await expect( + table.prewarmData({ + columns: ["text"], + filter: "text = 'alpha'", + concurrency: 2, + }), + ).rejects.toThrow("only supported on remote tables"); + }); + + test("prewarmData preserves argument forms and returns after submission", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_submission", [{ id: 1 }]); + const wait = jest.fn(); + const submit = jest + .spyOn(table, "prewarmDataAsync") + .mockResolvedValue({ wait } as unknown as Awaited< + ReturnType + >); + const options = { columns: ["id"], filter: "id > 0", concurrency: 2 }; + try { + await expect(table.prewarmData(options)).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith(options); + await expect(table.prewarmData(["id"])).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith({ columns: ["id"] }); + await expect(table.prewarmData([])).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith({ columns: [] }); + await expect(table.prewarmData()).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith(undefined); + expect(wait).not.toHaveBeenCalled(); + } finally { + submit.mockRestore(); + } + }); + + test("prewarmData validates options before submission", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_options", [{ id: 1 }]); + await expect( + table.prewarmData({ unsupported: 1 } as never), + ).rejects.toThrow("Unsupported data prewarm option: unsupported"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 4294967296, + ]) { + await expect(table.prewarmData({ concurrency })).rejects.toThrow( + "concurrency must be an integer", + ); + } + }); + + test("explainPrewarmData validates options and rejects Embedded tables", async () => { + const db = await connect(tmp.dirSync().name); + const table = await db.createTable("preview", [{ id: 1 }]); + await expect(table.explainPrewarmData()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.explainPrewarmData({ filter: "id > $1", parameters: [1] }), + ).rejects.toThrow("only supported on remote tables"); + await expect( + table.explainPrewarmData({ unsupported: true } as never), + ).rejects.toThrow("Unsupported data prewarm option"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 2 ** 32, + ]) { + await expect(table.explainPrewarmData({ concurrency })).rejects.toThrow( + "concurrency", + ); + } + }); + + test("prewarmDataAsync validates options and rejects local tables", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_job", [{ id: 1 }]); + await expect(table.prewarmDataAsync()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.prewarmDataAsync({ + columns: ["id"], + filter: "id > $1", + concurrency: 2, + parameters: [1], + }), + ).rejects.toThrow("only supported on remote tables"); + await expect( + table.prewarmDataAsync({ unsupported: 1 } as never), + ).rejects.toThrow("Unsupported data prewarm option: unsupported"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 4294967296, + ]) { + await expect(table.prewarmDataAsync({ concurrency })).rejects.toThrow( + "concurrency must be an integer", + ); + } }); test("full text index on list", async () => { @@ -5590,6 +6356,59 @@ describe("computed columns", () => { expect(rows.map((r) => r.doubled).sort()).toEqual([2, 4]); }); + it("rejects Enterprise refresh options on local tables", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("refresh_options_local", [{ x: 1 }]); + await expect(table.refreshColumn("x", { where: "x > 0" })).rejects.toThrow( + "where requires a LanceDB Enterprise refresh", + ); + await expect( + table.refreshColumnAsync("x", { errorPolicy: "skip" }), + ).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh"); + for (const refresh of [ + () => table.refreshColumn("x", { publicationIntervalRows: 60 }), + () => table.refreshColumnAsync("x", { publicationIntervalRows: 60 }), + ]) { + await expect(refresh()).rejects.toThrow( + "publication_interval_rows requires a LanceDB Enterprise refresh", + ); + } + await expect( + table.refreshColumnAsync("x", { maxConcurrency: 4 }), + ).rejects.toThrow("max_concurrency requires a LanceDB Enterprise refresh"); + await expect( + table.refreshColumnAsync("x", { + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, + }), + ).rejects.toThrow("total_cpu_millis requires a LanceDB Enterprise refresh"); + await expect( + table.refreshColumn("x", { + supervisorResources: { + cpuMillis: 1_000, + memoryBytes: 1_024, + ephemeralStorageBytes: 2_048, + }, + }), + ).rejects.toThrow( + "supervisor_resources requires a LanceDB Enterprise refresh", + ); + await expect( + table.refreshColumnAsync("x", { + planningWorkers: { + resources: { + cpuMillis: 1_000, + memoryBytes: 1_024, + ephemeralStorageBytes: 2_048, + }, + maxWorkers: 2, + rowsPerWorker: 100, + fragmentsPerWorker: 1, + }, + }), + ).rejects.toThrow("planning_workers requires a LanceDB Enterprise refresh"); + }); + it("records Function errors only on remote tables", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("errors_local", [{ x: 1 }]); @@ -5637,3 +6456,85 @@ describe("computed columns", () => { expect(rows.map((r) => r.doubled).sort()).toEqual([10, 2]); }); }); + +describe("durable compaction validation", () => { + test("rejects local tables and unknown options", async () => { + const db = await connect(`memory://compaction-job-${Date.now()}`); + const table = await db.createTable("test", [{ id: 1 }]); + await expect(table.compactAsync()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.compactAsync({ unrecognizedLimit: 1 } as never), + ).rejects.toThrow("Unsupported compaction option"); + await expect( + table.compactAsync({ targetRowsPerFragment: 0 }), + ).rejects.toThrow("safe integer"); + }); +}); + +describe("Enterprise table overrides", () => { + it("keeps added operations optional for existing custom Table subclasses", async () => { + // Declare the old Table surface; the new methods must be inherited. + // biome-ignore lint/correctness/noUnusedVariables: declaration merging supplies the legacy members + interface LegacyTable + extends Omit< + Table, + | "getTableOverrides" + | "updateTableOverrides" + | "resetTableOverrides" + | "functionErrors" + | "functionErrorRows" + | "retryFailed" + | "upgradeColumn" + | "quarantineFailed" + | "functionProvenance" + > {} + class LegacyTable extends Table { + async functionErrors() { + return { records: [], fragments: [], truncated: false }; + } + } + + const table = new LegacyTable(); + await expect(table.functionErrorRows()).rejects.toThrow( + "Function row-failure workflow", + ); + await expect(table.retryFailed("embedding")).rejects.toThrow( + "retryFailed is not supported on this table type", + ); + await expect(table.delta(1)).rejects.toThrow( + "table.delta is only supported on LanceDB Embedded tables", + ); + await expect(table.getTableOverrides()).rejects.toThrow( + "getTableOverrides is not supported on this table type", + ); + await expect(table.updateTableOverrides({ custom: true })).rejects.toThrow( + "updateTableOverrides is not supported on this table type", + ); + await expect(table.resetTableOverrides()).rejects.toThrow( + "resetTableOverrides is not supported on this table type", + ); + }); + + it("rejects get, update, and reset on local tables", async () => { + const tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + const table = await db.createTable("items", [{ id: 1 }]); + try { + await expect(table.getTableOverrides()).rejects.toThrow( + /only on remote Enterprise tables/, + ); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/only on remote Enterprise tables/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /only on remote Enterprise tables/, + ); + } finally { + table.close(); + db.close(); + tmpDir.removeCallback(); + } + }); +}); diff --git a/nodejs/__test__/table_overrides_integration.test.ts b/nodejs/__test__/table_overrides_integration.test.ts new file mode 100644 index 000000000..ee6e0c493 --- /dev/null +++ b/nodejs/__test__/table_overrides_integration.test.ts @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { randomUUID } from "node:crypto"; +import { Connection, Table, connect } from "../lancedb"; + +// Run against an isolated Enterprise deployment: +// LANCEDB_TABLE_OVERRIDES_E2E=1 LANCEDB_URI=db://test \ +// LANCEDB_HOST_OVERRIDE=http://localhost:10024 LANCEDB_API_KEY=... \ +// pnpm test __test__/table_overrides_integration.test.ts --runInBand +const maybeDescribe = process.env.LANCEDB_TABLE_OVERRIDES_E2E + ? describe + : describe.skip; + +maybeDescribe("table overrides live integration", () => { + let db: Connection; + const namespace = [`overrides_${randomUUID().replaceAll("-", "_")}`]; + const nested = [...namespace, "nested"]; + const uri = process.env.LANCEDB_URI ?? "db://test"; + const host = process.env.LANCEDB_HOST_OVERRIDE; + const apiKey = process.env.LANCEDB_API_KEY; + + beforeAll(async () => { + if (!host || !apiKey) { + throw new Error( + "Set LANCEDB_HOST_OVERRIDE and LANCEDB_API_KEY for live tests", + ); + } + db = await connect(uri, { apiKey, hostOverride: host }); + await db.createNamespace(namespace); + await db.createNamespace(nested); + }); + + afterAll(async () => { + if (db) { + try { + await db.dropNamespace(nested); + await db.dropNamespace(namespace); + } finally { + db.close(); + } + } + }); + + async function withTable( + namespacePath: string[], + run: (table: Table, name: string) => Promise, + ) { + const name = `items_${randomUUID().replaceAll("-", "_")}`; + const table = await db.createTable(name, [{ id: 1 }], namespacePath); + try { + await run(table, name); + } finally { + table.close(); + await db.dropTable(name, namespacePath); + } + } + + it.each([ + { label: "root", path: [] }, + { label: "nested", path: nested }, + ])( + "merges, replaces via REST, and resets in $label namespace", + async ({ path }) => { + await withTable(path, async (table, name) => { + await expect(table.getTableOverrides()).resolves.toEqual({}); + await expect(table.updateTableOverrides({})).resolves.toEqual({}); + const initial = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { enabled: false }, + cleanup: { enabled: false }, + }, + custom: { keep: "測試", values: [1, 2], nullable: "old" }, + }; + await expect(table.updateTableOverrides(initial)).resolves.toEqual( + initial, + ); + const patch = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { compaction: { enabled: true } }, + custom: { values: [3], nullable: null }, + }; + const expected = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { enabled: true }, + cleanup: { enabled: false }, + }, + custom: { keep: "測試", values: [3], nullable: null }, + }; + await expect(table.updateTableOverrides(patch)).resolves.toEqual( + expected, + ); + await expect(table.getTableOverrides()).resolves.toEqual(expected); + await expect(table.updateTableOverrides({})).resolves.toEqual(expected); + + const replacement = { custom: { replacement: true } }; + const response = await fetch(`${host}/admin/table/overrides`, { + method: "PUT", + headers: { "x-api-key": apiKey!, "Content-Type": "application/json" }, + body: JSON.stringify({ + db: new URL(uri).hostname, + namespace: path, + table: name, + overrides: replacement, + }), + }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual(replacement); + await expect(table.getTableOverrides()).resolves.toEqual(replacement); + await expect(table.resetTableOverrides()).resolves.toEqual({}); + await expect(table.getTableOverrides()).resolves.toEqual({}); + await expect(table.countRows()).resolves.toBe(1); + }); + }, + ); + + it("isolates branch updates and resets from main", async () => { + await withTable(nested, async (table) => { + const initial = { custom: { main: true } }; + await table.updateTableOverrides(initial); + const branch = await (await table.branches()).create("experiment"); + try { + const expected = { custom: { main: true, branch: true } }; + await expect( + branch.updateTableOverrides({ custom: { branch: true } }), + ).resolves.toEqual(expected); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + await expect(branch.resetTableOverrides()).resolves.toEqual({}); + await expect(branch.getTableOverrides()).resolves.toEqual({}); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + } finally { + branch.close(); + } + }); + }); + + it("propagates server validation errors without changing stored overrides", async () => { + await withTable(nested, async (table) => { + const initial = { custom: { keep: true } }; + await table.updateTableOverrides(initial); + await expect( + table.updateTableOverrides({ + // biome-ignore lint/style/useNamingConvention: server wire format + auto_refresh_interval_seconds: -1, + }), + ).rejects.toThrow(); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + }); + }); + + it("rejects writes at a fixed version", async () => { + await withTable(nested, async (table) => { + await table.checkout(1); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/fixed at version/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /fixed at version/, + ); + await table.checkoutLatest(); + await expect(table.getTableOverrides()).resolves.toEqual({}); + }); + }); +}); diff --git a/nodejs/examples/package.json b/nodejs/examples/package.json index c3f962b79..5b514aaf8 100644 --- a/nodejs/examples/package.json +++ b/nodejs/examples/package.json @@ -19,10 +19,10 @@ "license": "Apache-2.0", "packageManager": "pnpm@11.1.1", "dependencies": { - "@huggingface/transformers": "3.0.2", + "@huggingface/transformers": "4.3.2", "@lancedb/lancedb": "file:../dist", "openai": "4.29.2", - "sharp": "0.33.5" + "sharp": "0.35.5" }, "devDependencies": { "@biomejs/biome": "^1.7.3", diff --git a/nodejs/examples/pnpm-lock.yaml b/nodejs/examples/pnpm-lock.yaml index 6adbd99d1..408cf7ebb 100644 --- a/nodejs/examples/pnpm-lock.yaml +++ b/nodejs/examples/pnpm-lock.yaml @@ -9,8 +9,8 @@ importers: .: dependencies: '@huggingface/transformers': - specifier: 3.0.2 - version: 3.0.2 + specifier: 4.3.2 + version: 4.3.2(@types/node@25.7.0) '@lancedb/lancedb': specifier: file:../dist version: file:../dist @@ -18,8 +18,8 @@ importers: specifier: 4.29.2 version: 4.29.2 sharp: - specifier: 0.33.5 - version: 0.33.5 + specifier: 0.35.5 + version: 0.35.5(@types/node@25.7.0) devDependencies: '@biomejs/biome': specifier: ^1.7.3 @@ -264,137 +264,181 @@ packages: cpu: [x64] os: [win32] - '@emnapi/runtime@1.10.0': - resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} - '@huggingface/jinja@0.3.4': - resolution: {integrity: sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==} + '@huggingface/jinja@0.5.11': + resolution: {integrity: sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ==} engines: {node: '>=18'} - '@huggingface/transformers@3.0.2': - resolution: {integrity: sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==} + '@huggingface/tokenizers@0.2.0': + resolution: {integrity: sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==} - '@img/sharp-darwin-arm64@0.33.5': - resolution: {integrity: sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@huggingface/transformers@4.3.2': + resolution: {integrity: sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==} + + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.33.5': - resolution: {integrity: sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-libvips-darwin-arm64@1.0.4': - resolution: {integrity: sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.0.4': - resolution: {integrity: sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.0.4': - resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm@1.0.5': - resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-s390x@1.0.4': - resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.0.4': - resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linuxmusl-arm64@1.0.4': - resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-x64@1.0.4': - resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-linux-arm64@0.33.5': - resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-linux-arm@0.33.5': - resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} + engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-linux-s390x@0.33.5': - resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} + engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-linux-x64@0.33.5': - resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-linuxmusl-arm64@0.33.5': - resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-linuxmusl-x64@0.33.5': - resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-wasm32@0.33.5': - resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} + engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-ia32@0.33.5': - resolution: {integrity: sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} + engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.33.5': - resolution: {integrity: sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] - '@isaacs/fs-minipass@4.0.1': - resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} - engines: {node: '>=18.0.0'} - '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} engines: {node: '>=8'} @@ -573,6 +617,10 @@ packages: resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} engines: {node: '>=6.5'} + adm-zip@0.6.1: + resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==} + engines: {node: '>=14.0'} + agentkeepalive@4.6.0: resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==} engines: {node: '>= 8.0.0'} @@ -691,10 +739,6 @@ packages: charenc@0.0.2: resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==} - chownr@3.0.0: - resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} - engines: {node: '>=18'} - ci-info@3.9.0: resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} engines: {node: '>=8'} @@ -720,13 +764,6 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - color-string@1.9.1: - resolution: {integrity: sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==} - - color@4.2.3: - resolution: {integrity: sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==} - engines: {node: '>=12.5.0'} - combined-stream@1.0.8: resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} engines: {node: '>= 0.8'} @@ -770,6 +807,14 @@ packages: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -830,6 +875,10 @@ packages: resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==} engines: {node: '>=8'} + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + esprima@4.0.1: resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} engines: {node: '>=4'} @@ -865,8 +914,8 @@ packages: resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} engines: {node: '>=8'} - flatbuffers@1.12.0: - resolution: {integrity: sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==} + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} form-data-encoder@1.7.2: resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==} @@ -918,6 +967,14 @@ packages: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + global-agent@4.1.6: + resolution: {integrity: sha512-V9u791atI/bS7RryfRTK2oixDWo6/RCrIikjwuQ4kADPRZZml1C6LUJXc7y6qRhaAF8geo3bIvE/siAGJCw38A==} + engines: {node: '>=10.0'} + + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + gopd@1.2.0: resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} engines: {node: '>= 0.4'} @@ -937,6 +994,9 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -978,9 +1038,6 @@ packages: is-arrayish@0.2.1: resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} - is-arrayish@0.3.4: - resolution: {integrity: sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==} - is-buffer@1.1.6: resolution: {integrity: sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==} @@ -1218,6 +1275,10 @@ packages: makeerror@1.0.12: resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} + matcher@4.0.0: + resolution: {integrity: sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==} + engines: {node: '>=10'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -1250,14 +1311,6 @@ packages: minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - minipass@7.1.3: - resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} - engines: {node: '>=16 || 14 >=14.17'} - - minizlib@3.1.0: - resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} - engines: {node: '>= 18'} - ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -1295,6 +1348,10 @@ packages: resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} engines: {node: '>=8'} + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} @@ -1302,18 +1359,18 @@ packages: resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} engines: {node: '>=6'} - onnxruntime-common@1.19.2: - resolution: {integrity: sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==} + onnxruntime-common@1.30.0: + resolution: {integrity: sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: - resolution: {integrity: sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: + resolution: {integrity: sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==} - onnxruntime-node@1.19.2: - resolution: {integrity: sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==} + onnxruntime-node@1.30.0: + resolution: {integrity: sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==} os: [win32, darwin, linux] - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: - resolution: {integrity: sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==} + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: + resolution: {integrity: sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==} openai@4.29.2: resolution: {integrity: sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==} @@ -1415,14 +1472,23 @@ packages: resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} hasBin: true - semver@7.8.0: - resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==} + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} hasBin: true - sharp@0.33.5: - resolution: {integrity: sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + serialize-error@8.1.0: + resolution: {integrity: sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==} + engines: {node: '>=10'} + + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} + engines: {node: '>=20.9.0'} + peerDependencies: + '@types/node': '*' + peerDependenciesMeta: + '@types/node': + optional: true shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} @@ -1435,9 +1501,6 @@ packages: signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} - simple-swizzle@0.2.4: - resolution: {integrity: sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==} - sisteransi@1.0.5: resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} @@ -1495,10 +1558,6 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} - tar@7.5.15: - resolution: {integrity: sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ==} - engines: {node: '>=18'} - test-exclude@6.0.0: resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} engines: {node: '>=8'} @@ -1547,6 +1606,10 @@ packages: resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==} engines: {node: '>=4'} + type-fest@0.20.2: + resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} + engines: {node: '>=10'} + type-fest@0.21.3: resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==} engines: {node: '>=10'} @@ -1624,10 +1687,6 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} - yallist@5.0.0: - resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} - engines: {node: '>=18'} - yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -1866,98 +1925,130 @@ snapshots: '@biomejs/cli-win32-x64@1.9.4': optional: true - '@emnapi/runtime@1.10.0': + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 optional: true - '@huggingface/jinja@0.3.4': {} + '@huggingface/jinja@0.5.11': {} - '@huggingface/transformers@3.0.2': + '@huggingface/tokenizers@0.2.0': {} + + '@huggingface/transformers@4.3.2(@types/node@25.7.0)': dependencies: - '@huggingface/jinja': 0.3.4 - onnxruntime-node: 1.19.2 - onnxruntime-web: 1.21.0-dev.20241024-d9ca84ef96 - sharp: 0.33.5 + '@huggingface/jinja': 0.5.11 + '@huggingface/tokenizers': 0.2.0 + onnxruntime-node: 1.30.0 + onnxruntime-web: 1.31.0-dev.20260914-8d85527a0 + sharp: 0.35.5(@types/node@25.7.0) + transitivePeerDependencies: + - '@types/node' - '@img/sharp-darwin-arm64@0.33.5': + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.0.4 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.33.5': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.0.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-libvips-darwin-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-darwin-x64@1.0.4': - optional: true - - '@img/sharp-libvips-linux-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-linux-arm@1.0.5': - optional: true - - '@img/sharp-libvips-linux-s390x@1.0.4': - optional: true - - '@img/sharp-libvips-linux-x64@1.0.4': - optional: true - - '@img/sharp-libvips-linuxmusl-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-linuxmusl-x64@1.0.4': - optional: true - - '@img/sharp-linux-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.0.4 - optional: true - - '@img/sharp-linux-arm@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.0.5 - optional: true - - '@img/sharp-linux-s390x@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.0.4 - optional: true - - '@img/sharp-linux-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.0.4 - optional: true - - '@img/sharp-linuxmusl-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.0.4 - optional: true - - '@img/sharp-linuxmusl-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.0.4 - optional: true - - '@img/sharp-wasm32@0.33.5': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@emnapi/runtime': 1.10.0 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-ia32@0.33.5': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-win32-x64@0.33.5': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@isaacs/fs-minipass@4.0.1': + '@img/sharp-libvips-linux-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.4': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.4': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + optional: true + + '@img/sharp-linux-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.4 + optional: true + + '@img/sharp-linux-arm@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.4 + optional: true + + '@img/sharp-linux-ppc64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.4 + optional: true + + '@img/sharp-linux-riscv64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.4 + optional: true + + '@img/sharp-linux-s390x@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.4 + optional: true + + '@img/sharp-linux-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + optional: true + + '@img/sharp-wasm32@0.35.5': dependencies: - minipass: 7.1.3 + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.5': + dependencies: + '@img/sharp-wasm32': 0.35.5 + optional: true + + '@img/sharp-win32-arm64@0.35.5': + optional: true + + '@img/sharp-win32-ia32@0.35.5': + optional: true + + '@img/sharp-win32-x64@0.35.5': + optional: true '@istanbuljs/load-nyc-config@1.1.0': dependencies: @@ -2222,7 +2313,7 @@ snapshots: '@types/node-fetch@2.6.13': dependencies: - '@types/node': 18.19.130 + '@types/node': 25.7.0 form-data: 4.0.5 '@types/node@18.19.130': @@ -2245,6 +2336,8 @@ snapshots: dependencies: event-target-shim: 5.0.1 + adm-zip@0.6.1: {} + agentkeepalive@4.6.0: dependencies: humanize-ms: 1.2.1 @@ -2382,8 +2475,6 @@ snapshots: charenc@0.0.2: {} - chownr@3.0.0: {} - ci-info@3.9.0: {} cjs-module-lexer@1.4.3: {} @@ -2404,16 +2495,6 @@ snapshots: color-name@1.1.4: {} - color-string@1.9.1: - dependencies: - color-name: 1.1.4 - simple-swizzle: 0.2.4 - - color@4.2.3: - dependencies: - color-convert: 2.0.1 - color-string: 1.9.1 - combined-stream@1.0.8: dependencies: delayed-stream: 1.0.0 @@ -2453,6 +2534,18 @@ snapshots: deepmerge@4.3.1: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + delayed-stream@1.0.0: {} detect-libc@2.1.2: {} @@ -2501,6 +2594,8 @@ snapshots: escape-string-regexp@2.0.0: {} + escape-string-regexp@4.0.0: {} + esprima@4.0.1: {} event-target-shim@5.0.1: {} @@ -2542,7 +2637,7 @@ snapshots: locate-path: 5.0.0 path-exists: 4.0.0 - flatbuffers@1.12.0: {} + flatbuffers@25.9.23: {} form-data-encoder@1.7.2: {} @@ -2601,6 +2696,18 @@ snapshots: once: 1.4.0 path-is-absolute: 1.0.1 + global-agent@4.1.6: + dependencies: + globalthis: 1.0.4 + matcher: 4.0.0 + semver: 7.8.6 + serialize-error: 8.1.0 + + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + gopd@1.2.0: {} graceful-fs@4.2.11: {} @@ -2618,6 +2725,10 @@ snapshots: has-flag@4.0.0: {} + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -2652,8 +2763,6 @@ snapshots: is-arrayish@0.2.1: {} - is-arrayish@0.3.4: {} - is-buffer@1.1.6: {} is-core-module@2.16.2: @@ -2688,7 +2797,7 @@ snapshots: '@babel/parser': 7.29.3 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 - semver: 7.8.0 + semver: 7.8.6 transitivePeerDependencies: - supports-color @@ -2971,7 +3080,7 @@ snapshots: jest-util: 29.7.0 natural-compare: 1.4.0 pretty-format: 29.7.0 - semver: 7.8.0 + semver: 7.8.6 transitivePeerDependencies: - supports-color @@ -3056,7 +3165,7 @@ snapshots: make-dir@4.0.0: dependencies: - semver: 7.8.0 + semver: 7.8.6 make-error@1.3.6: {} @@ -3064,6 +3173,10 @@ snapshots: dependencies: tmpl: 1.0.5 + matcher@4.0.0: + dependencies: + escape-string-regexp: 4.0.0 + math-intrinsics@1.1.0: {} md5@2.3.0: @@ -3093,12 +3206,6 @@ snapshots: minimist@1.2.8: {} - minipass@7.1.3: {} - - minizlib@3.1.0: - dependencies: - minipass: 7.1.3 - ms@2.1.3: {} natural-compare@1.4.0: {} @@ -3121,6 +3228,8 @@ snapshots: dependencies: path-key: 3.1.1 + object-keys@1.1.1: {} + once@1.4.0: dependencies: wrappy: 1.0.2 @@ -3129,21 +3238,22 @@ snapshots: dependencies: mimic-fn: 2.1.0 - onnxruntime-common@1.19.2: {} + onnxruntime-common@1.30.0: {} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: {} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: {} - onnxruntime-node@1.19.2: + onnxruntime-node@1.30.0: dependencies: - onnxruntime-common: 1.19.2 - tar: 7.5.15 + adm-zip: 0.6.1 + global-agent: 4.1.6 + onnxruntime-common: 1.30.0 - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: dependencies: - flatbuffers: 1.12.0 + flatbuffers: 25.9.23 guid-typescript: 1.0.9 long: 5.3.2 - onnxruntime-common: 1.20.0-dev.20241016-2b8fc5529b + onnxruntime-common: 1.31.0-dev.20260911-2a43ec07e platform: 1.3.6 protobufjs: 7.5.7 @@ -3251,33 +3361,44 @@ snapshots: semver@6.3.1: {} - semver@7.8.0: {} + semver@7.8.6: {} - sharp@0.33.5: + serialize-error@8.1.0: dependencies: - color: 4.2.3 + type-fest: 0.20.2 + + sharp@0.35.5(@types/node@25.7.0): + dependencies: + '@img/colour': 1.1.0 detect-libc: 2.1.2 - semver: 7.8.0 + semver: 7.8.6 optionalDependencies: - '@img/sharp-darwin-arm64': 0.33.5 - '@img/sharp-darwin-x64': 0.33.5 - '@img/sharp-libvips-darwin-arm64': 1.0.4 - '@img/sharp-libvips-darwin-x64': 1.0.4 - '@img/sharp-libvips-linux-arm': 1.0.5 - '@img/sharp-libvips-linux-arm64': 1.0.4 - '@img/sharp-libvips-linux-s390x': 1.0.4 - '@img/sharp-libvips-linux-x64': 1.0.4 - '@img/sharp-libvips-linuxmusl-arm64': 1.0.4 - '@img/sharp-libvips-linuxmusl-x64': 1.0.4 - '@img/sharp-linux-arm': 0.33.5 - '@img/sharp-linux-arm64': 0.33.5 - '@img/sharp-linux-s390x': 0.33.5 - '@img/sharp-linux-x64': 0.33.5 - '@img/sharp-linuxmusl-arm64': 0.33.5 - '@img/sharp-linuxmusl-x64': 0.33.5 - '@img/sharp-wasm32': 0.33.5 - '@img/sharp-win32-ia32': 0.33.5 - '@img/sharp-win32-x64': 0.33.5 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 + '@types/node': 25.7.0 shebang-command@2.0.0: dependencies: @@ -3287,10 +3408,6 @@ snapshots: signal-exit@3.0.7: {} - simple-swizzle@0.2.4: - dependencies: - is-arrayish: 0.3.4 - sisteransi@1.0.5: {} slash@3.0.0: {} @@ -3339,14 +3456,6 @@ snapshots: supports-preserve-symlinks-flag@1.0.0: {} - tar@7.5.15: - dependencies: - '@isaacs/fs-minipass': 4.0.1 - chownr: 3.0.0 - minipass: 7.1.3 - minizlib: 3.1.0 - yallist: 5.0.0 - test-exclude@6.0.0: dependencies: '@istanbuljs/schema': 0.1.6 @@ -3370,7 +3479,7 @@ snapshots: json5: 2.2.3 lodash.memoize: 4.1.2 make-error: 1.3.6 - semver: 7.8.0 + semver: 7.8.6 type-fest: 4.41.0 typescript: 5.9.3 yargs-parser: 21.1.1 @@ -3386,6 +3495,8 @@ snapshots: type-detect@4.0.8: {} + type-fest@0.20.2: {} + type-fest@0.21.3: {} type-fest@4.41.0: {} @@ -3449,8 +3560,6 @@ snapshots: yallist@3.1.1: {} - yallist@5.0.0: {} - yargs-parser@21.1.1: {} yargs@17.7.2: diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 56c8e1897..f920eecb8 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -1386,7 +1386,9 @@ export async function fromBufferToRecordBatch( export async function fromRecordBatchToBuffer( batch: RecordBatch, ): Promise { - const writer = new RecordBatchFileWriter().writeAll([batch]); + // Arrow writers require data types from their own library instance. + const table = sanitizeTable({ schema: batch.schema, batches: [batch] }); + const writer = new RecordBatchFileWriter().writeAll(table); return Buffer.from(await writer.toUint8Array()); } diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 67e662175..0a67165b1 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -1,7 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -import { Field, LargeBinary, Struct, Uint64, Utf8 } from "apache-arrow"; +import { + DataType, + Field, + LargeBinary, + Struct, + Uint64, + Utf8, +} from "apache-arrow"; import { BlobFile as NativeBlobFile } from "./native"; const BLOB_V2_EXTENSION_NAME = "lance.blob.v2"; @@ -178,6 +185,39 @@ export function isBlobField(field: Field): boolean { return field.metadata?.get("ARROW:extension:name") === BLOB_V2_EXTENSION_NAME; } +/** @ignore */ +export function isBlobDescriptorField(field: Field): boolean { + // Native descriptor scans replace the logical extension metadata. Require + // both the encoding marker and the v2 layout to exclude v1 and plain structs. + if ( + field.metadata?.get("lance-encoding:blob") !== "true" || + !DataType.isStruct(field.type) + ) { + return false; + } + const children = field.type.children; + const integers = [ + ["kind", 8], + ["position", 64], + ["size", 64], + ["blob_id", 32], + ] as const; + return ( + children.length === 5 && + integers.every(([name, width], index) => { + const child = children[index]; + return ( + child.name === name && + DataType.isInt(child.type) && + !child.type.isSigned && + child.type.bitWidth === width + ); + }) && + children[4].name === "blob_uri" && + DataType.isUtf8(children[4].type) + ); +} + /** * A lazy handle to blob bytes. Create one with {@link Table.fetchBlobFiles}. * @@ -270,6 +310,80 @@ export class BlobFile { } } +/** + * A source-bearing Blob V2 descriptor returned by the SQL `blob_descriptor` + * function. Field names match the descriptor object/Arrow struct shape. + */ +export interface BlobDescriptorSource { + uri: string; + version: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + committed_at_micros: bigint | number; + branch?: string | null; + column: string; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + row_reference: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + row_is_address: boolean; +} + +/** + * A source-bearing Blob V2 descriptor accepted by {@link Table.openBlobFile}. + * Query results expose these fields as an Arrow struct. The source pins the + * table version, branch, column and row identity used to open the handle. + */ +export interface BlobDescriptor { + kind: number; + position: bigint | number; + size: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + blob_id: number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + blob_uri: string; + source: BlobDescriptorSource; +} + +function descriptorBigInt(value: bigint | number, field: string): bigint { + if (typeof value === "bigint") { + if (value < 0n) { + throw new TypeError(`blob descriptor ${field} cannot be negative`); + } + return value; + } + if (!Number.isSafeInteger(value) || value < 0) { + throw new TypeError( + `blob descriptor ${field} must be a non-negative safe integer or bigint`, + ); + } + return BigInt(value); +} + +/** @ignore */ +export function toNativeBlobDescriptor(descriptor: BlobDescriptor) { + return { + kind: descriptor.kind, + position: descriptorBigInt(descriptor.position, "position"), + size: descriptorBigInt(descriptor.size, "size"), + blobId: descriptor.blob_id, + blobUri: descriptor.blob_uri, + source: { + uri: descriptor.source.uri, + version: descriptorBigInt(descriptor.source.version, "source.version"), + committedAtMicros: descriptorBigInt( + descriptor.source.committed_at_micros, + "source.committed_at_micros", + ), + branch: descriptor.source.branch ?? undefined, + column: descriptor.source.column, + rowReference: descriptorBigInt( + descriptor.source.row_reference, + "source.row_reference", + ), + rowIsAddress: descriptor.source.row_is_address, + }, + }; +} + /** Options for blob reads. */ export type BlobReadOptions = { /** @@ -305,6 +419,16 @@ export async function runWithSignal( } } +/** One row-specific range for {@link Table.fetchBlobRanges}. */ +export type BlobRangeRequest = { + /** A row ID from a query with row IDs enabled. */ + rowId: bigint | number; + /** Byte offset from the beginning of the logical blob, as a uint64. */ + offset: bigint; + /** Number of bytes to read, as a uint64. Zero returns an empty non-null value. */ + length: bigint; +}; + /** A half-open byte range `[start, end)` for {@link BlobFile.readRanges}. */ export type BlobRange = { start: bigint; diff --git a/nodejs/lancedb/cleanup.ts b/nodejs/lancedb/cleanup.ts new file mode 100644 index 000000000..dfcc04564 --- /dev/null +++ b/nodejs/lancedb/cleanup.ts @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Per-run retention; omission inherits selected table/branch then deployment policy. */ +export interface CleanupOptions { + /** Minimum old-version age in seconds. Zero is explicit, not omitted. */ + minAgeSeconds?: number; +} + +/** Version-deletion outcome. Best-effort auxiliary sweeps are excluded. */ +export interface CleanupResult { + formatVersion: number; + minAgeSeconds: number; + /** False after uncertain retry/recovery; both counts are then null. */ + statisticsComplete: boolean; + oldVersions: number | null; + bytesRemoved: number | null; + /** Failed object deletions, if measured. Successful removals are retained. */ + failedDeletes: number | null; +} + +/** Read-only deletion estimates; no job or deletion snapshot is reserved. */ +export interface CleanupPlan { + formatVersion: number; + sourceVersion: number; + minAgeSeconds: number; + cutoffMillis: number; + versionsToRemove: number; + bytesToRemove: number; +} + +/** @internal */ +export function decodeCleanupPlan(value: unknown): CleanupPlan { + if (typeof value !== "object" || value === null) + throw new Error("invalid cleanup preview"); + const plan = value as Record; + if ( + plan.format_version !== 1 || + [ + "source_version", + "min_age_seconds", + "cutoff_millis", + "versions_to_remove", + "bytes_to_remove", + ].some( + (key) => + !Number.isSafeInteger(plan[key]) || + (key !== "cutoff_millis" && (plan[key] as number) < 0), + ) + ) { + throw new Error("unsupported or invalid cleanup preview"); + } + return { + formatVersion: 1, + sourceVersion: plan.source_version as number, + minAgeSeconds: plan.min_age_seconds as number, + cutoffMillis: plan.cutoff_millis as number, + versionsToRemove: plan.versions_to_remove as number, + bytesToRemove: plan.bytes_to_remove as number, + }; +} + +/** @internal */ +export function validateCleanupOptions(options?: CleanupOptions): void { + if ( + options !== undefined && + (typeof options !== "object" || options === null || Array.isArray(options)) + ) { + throw new Error("cleanup options must be an object"); + } + for (const key of Object.keys(options ?? {})) { + if (key !== "minAgeSeconds") + throw new Error(`Unknown cleanup option: ${key}`); + } + const age = options?.minAgeSeconds; + if (age !== undefined && (!Number.isSafeInteger(age) || age < 0)) { + throw new Error("minAgeSeconds must be a nonnegative safe integer"); + } +} + +/** @internal */ +export function decodeCleanupResult(value: unknown): CleanupResult { + if (typeof value !== "object" || value === null) + throw new Error("invalid cleanup result"); + const result = value as Record; + const counts = [result.old_versions ?? null, result.bytes_removed ?? null]; + const failed = result.failed_deletes ?? null; + if ( + failed !== null && + (!Number.isSafeInteger(failed) || + (failed as number) < 0 || + result.statistics_complete !== true) + ) { + throw new Error("invalid cleanup failed-deletion measurement"); + } + if ( + result.format_version !== 1 || + typeof result.statistics_complete !== "boolean" || + !Number.isSafeInteger(result.min_age_seconds) || + (result.min_age_seconds as number) < 0 || + counts.some( + (count) => + count !== null && + (!Number.isSafeInteger(count) || (count as number) < 0), + ) || + (result.statistics_complete + ? counts.some((count) => count === null) + : counts.some((count) => count !== null)) + ) { + throw new Error("unsupported or inconsistent cleanup result"); + } + return { + formatVersion: 1, + minAgeSeconds: result.min_age_seconds as number, + statisticsComplete: result.statistics_complete, + oldVersions: counts[0] as number | null, + bytesRemoved: counts[1] as number | null, + failedDeletes: (result.failed_deletes as number | null) ?? null, + }; +} diff --git a/nodejs/lancedb/compaction.ts b/nodejs/lancedb/compaction.ts new file mode 100644 index 000000000..3aaf3907c --- /dev/null +++ b/nodejs/lancedb/compaction.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Actual committed outcome of one remote compaction job. */ +export interface CompactionResult { + /** A bounded run left eligible work for another invocation. */ + moreWork: boolean; + /** Some planned groups were not committed. */ + partialCommit: boolean; + /** Live source rows in committed rewrite groups. */ + rowsSucceeded: number; + /** Planned live rows not committed by this job. */ + rowsFailed: number; + /** Percentage of planned live rows committed, from 0 to 100. */ + completionPercentage: number; + /** Files added, including deletion files; null if an older worker omitted it. */ + filesAdded: number | null; + /** Files removed, including deletion files; null if an older worker omitted it. */ + filesRemoved: number | null; + /** Fragments added by committed rewrites; null if an older worker omitted it. */ + fragmentsAdded: number | null; + /** Fragments removed by committed rewrites; null if an older worker omitted it. */ + fragmentsRemoved: number | null; +} + +/** @internal */ +export function decodeCompactionResult(value: unknown): CompactionResult { + // The Rust typed-job decoder validates the wire payload before it reaches JS. + const result = value as Record; + return { + moreWork: result.more_work as boolean, + partialCommit: result.partial_commit as boolean, + rowsSucceeded: result.rows_succeeded as number, + rowsFailed: result.rows_failed as number, + completionPercentage: result.completion_percentage as number, + filesAdded: (result.files_added as number | null) ?? null, + filesRemoved: (result.files_removed as number | null) ?? null, + fragmentsAdded: (result.fragments_added as number | null) ?? null, + fragmentsRemoved: (result.fragments_removed as number | null) ?? null, + }; +} diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 9c83d833f..8a818b682 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -286,6 +286,11 @@ export abstract class Connection { where?: string; limit?: number; withNoData?: boolean; + totalCpuMillis?: number; + totalMemoryBytes?: number; + totalGpuCount?: number; + gpuClass?: string; + gpuCount?: number; }, ): Promise; @@ -583,7 +588,7 @@ export abstract class Connection { * result, failure and event history, so there is no separate * connection-level call for any of them. */ - abstract openJob(jobId: string): Promise; + abstract openJob(jobId: string): Promise>; /** * Iterate lazily over server-side jobs across the database's tables. @@ -674,9 +679,34 @@ export class LocalConnection extends Connection { where?: string; limit?: number; withNoData?: boolean; + totalCpuMillis?: number; + totalMemoryBytes?: number; + totalGpuCount?: number; + gpuClass?: string; + gpuCount?: number; }, ): Promise { validateNonNegativeInteger(options?.limit, "limit"); + for (const [name, value] of [ + ["totalCpuMillis", options?.totalCpuMillis], + ["totalMemoryBytes", options?.totalMemoryBytes], + ["totalGpuCount", options?.totalGpuCount], + ["gpuCount", options?.gpuCount], + ] as const) { + validateNonNegativeInteger(value, name); + if (value === 0 && name !== "totalGpuCount") { + throw new Error(`${name} must be positive`); + } + } + if ( + options?.totalGpuCount !== undefined && + options.totalGpuCount > 4294967295 + ) { + throw new Error("totalGpuCount exceeds 4294967295"); + } + if (options?.gpuCount !== undefined && options.gpuCount > 4294967295) { + throw new Error("gpuCount exceeds 4294967295"); + } const innerTable = await this.inner.createMaterializedView( name, source, @@ -684,6 +714,11 @@ export class LocalConnection extends Connection { options?.where, options?.limit, options?.withNoData ?? false, + options?.totalCpuMillis, + options?.totalMemoryBytes, + options?.totalGpuCount, + options?.gpuClass, + options?.gpuCount, ); return new MaterializedView(new LocalTable(innerTable)); } @@ -1017,8 +1052,8 @@ export class LocalConnection extends Connection { ); } - async openJob(jobId: string): Promise { - return new Job(await this.inner.openJob(jobId)); + async openJob(jobId: string): Promise> { + return new Job(await this.inner.openJob(jobId)); } listJobs(options: ListingOptions = {}): Listing { diff --git a/nodejs/lancedb/function_recovery.ts b/nodejs/lancedb/function_recovery.ts new file mode 100644 index 000000000..54bf86600 --- /dev/null +++ b/nodejs/lancedb/function_recovery.ts @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import type { + FunctionErrorGroup, + FunctionErrorRecord, + FunctionErrors, + FunctionErrorsOptions, + RefreshColumnOptions, +} from "./native"; +import type { Table } from "./table"; + +/** Options for retrying exactly the current failures of one Function column. */ +export interface RetryFailedOptions + extends Omit { + /** Only retry failures with this exception class. */ + errorType?: string; + /** Only retry current failures recorded by this job. */ + jobId?: string; + /** Explicitly release and retry matching quarantined failures. */ + includeQuarantined?: boolean; + /** Upgrade to this immutable Function version while retrying failures. */ + functionVersion?: string; +} + +/** + * Which existing values to recompute during a Function version upgrade. + * `"failed"` selects current failures. `"all"` refreshes every eligible live + * row. `"none"` preserves existing values and only changes the binding. + */ +export type FunctionRecompute = "failed" | "all" | "none"; + +/** Options for assigning a new immutable Function version to a column. */ +export interface UpgradeColumnOptions + extends Omit { + /** An existing immutable version of the bound Function. */ + version: string; + /** Defaults to `"all"`. Quarantined failures are excluded. */ + recompute?: FunctionRecompute; +} + +/** The terminal outcome of a Function retry or upgrade job. */ +export interface RefreshColumnJobResult { + /** Logical rows successfully assigned a value. */ + rowsAssigned: bigint; + /** Logical rows whose computation failed. */ + rowsFailed: bigint; + /** Logical rows still needing a value, excluding rows counted in `rowsFailed`. */ + rowsRemaining: bigint; + /** The exact table version read by the job. */ + sourceVersion: bigint; + /** The table version made visible by the job, if it published one. */ + publishedVersion?: bigint; + /** Grouped causes reported by the completed job. */ + errorGroups: FunctionErrorGroup[]; + /** Whether the reported cause counts omit any failures. */ + errorGroupsTruncated: boolean; +} + +/** @internal */ +export function decodeRefreshColumnJobResult( + value: unknown, +): RefreshColumnJobResult { + // The Rust typed job validates the terminal result and preserves u64 values. + const result = value as { + ["rows_assigned"]: number | bigint; + ["rows_failed"]: number | bigint; + ["rows_remaining"]: number | bigint; + ["source_version"]: number | bigint; + ["published_version"]?: number | bigint; + ["error_groups"]?: { + column: string; + ["error_type"]: string; + ["error_message"]: string; + ["rows_failed"]: number | bigint; + }[]; + ["error_groups_truncated"]?: boolean; + }; + return { + rowsAssigned: BigInt(result.rows_assigned), + rowsFailed: BigInt(result.rows_failed), + rowsRemaining: BigInt(result.rows_remaining), + sourceVersion: BigInt(result.source_version), + publishedVersion: + result.published_version === undefined + ? undefined + : BigInt(result.published_version), + errorGroups: (result.error_groups ?? []).map((group) => ({ + column: group.column, + errorType: group.error_type, + errorMessage: group.error_message, + rowsFailed: BigInt(group.rows_failed), + })), + errorGroupsTruncated: result.error_groups_truncated ?? false, + }; +} + +/** A failed Function-column row and its source data at the table's read snapshot. */ +export interface FunctionFailedRow { + /** Values of the requested source columns. */ + input: Record; + /** The failure for this row and Function column. */ + error: FunctionErrorRecord; +} + +/** Filters and projection for current failing inputs. */ +export interface FunctionErrorRowsOptions + extends Pick { + /** Source columns to return. Defaults to all source columns. */ + columns?: string[]; +} + +/** @internal */ +export async function readFailedRows( + table: Table, + errors: FunctionErrors, + columns?: string[], +): Promise { + if ((errors.workflowVersion ?? 0) < 1) { + throw new Error( + "The server does not support the Function row-failure workflow", + ); + } + if ( + errors.truncated || + errors.fragments.length > 0 || + errors.records.some( + (record) => record.rowOffset == null && record.input == null, + ) + ) { + throw new Error( + "Function errors are incomplete; narrow the request or raise limit", + ); + } + const { records } = errors; + if (records.length === 0) return []; + + const stableIds = new Set(); + const addresses = new Set(); + const keys = records.map((record) => { + if (record.input != null) { + throw new Error( + "Inspect the input source identities for a materialized-view Function error", + ); + } + if (typeof record.rowId === "bigint") { + stableIds.add(record.rowId); + return `_rowid:${record.rowId}`; + } + if (typeof record.rowAddress === "bigint") { + addresses.add(record.rowAddress); + return `_rowaddr:${record.rowAddress}`; + } + throw new Error("This Function error has no source row identity"); + }); + const identities = ( + [ + ["_rowid", stableIds], + ["_rowaddr", addresses], + ] as const + ).filter(([, values]) => values.size > 0); + const identityColumns = identities.map(([column]) => column); + const selected = + columns ?? (await table.schema()).fields.map((field) => field.name); + const projection = [...new Set([...selected, ...identityColumns])]; + const filter = identities + .map(([column, values]) => `${column} IN (${[...values].join(",")})`) + .join(" OR "); + const source = await table + .query() + .select(projection) + .where(filter) + .limit(stableIds.size + addresses.size) + .toArrow(); + const selectedNames = new Set(selected); + const inputColumns = source.schema.fields + .map((field) => field.name) + .filter( + (name) => + (name !== "_rowid" && name !== "_rowaddr") || selectedNames.has(name), + ); + const byIdentity = new Map>(); + for (const row of source) { + if (row === null) continue; + const input = Object.fromEntries( + inputColumns.map((name) => [name, row[name]]), + ); + for (const column of identityColumns) { + const identity: unknown = row[column]; + if (typeof identity === "bigint") { + byIdentity.set(`${column}:${identity}`, input); + } + } + } + return records.map((error, index) => { + const input = byIdentity.get(keys[index]); + if (input === undefined) { + throw new Error( + "Some failed inputs are no longer addressable in this snapshot; refresh the error listing", + ); + } + return { input, error }; + }); +} diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 58f687e1a..58e1f0cde 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -2,21 +2,21 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { - Connection, + type Connection, LocalConnection, cleanseStorageOptions, } from "./connection"; import { - ConnectNamespaceOptions, - ConnectionOptions, + type ConnectNamespaceOptions, + type ConnectionOptions, Connection as LanceDbConnection, JsHeaderProvider as NativeJsHeaderProvider, - Session, + type Session, tokenize as nativeTokenize, } from "./native.js"; -import { HeaderProvider } from "./header"; +import type { HeaderProvider } from "./header"; import type { BaseTokenizer } from "./indices"; import type { FtsToken } from "./table"; @@ -56,11 +56,20 @@ export { MergeResult, AddResult, AddColumnsResult, + RefreshColumnOptions, + FunctionRefreshPlanningConfig, + FunctionRefreshPodResources, + FunctionRetryPolicy, RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, + FunctionErrorGroup, FunctionErrorRecord, FunctionErrorFragment, + FunctionProvenance, + FunctionProvenanceOptions, + FunctionQuarantineOptions, + FunctionValueProvenance, RefreshMaterializedViewResult, AlterColumnsResult, UpdateFieldMetadataResult, @@ -84,11 +93,13 @@ export { } from "./arrow"; export { blob, isBlobField, BlobFile } from "./blob"; +export type { BlobDescriptor, BlobDescriptorSource } from "./blob"; export type { BlobData, BlobInput, BlobOptions, BlobRange, + BlobRangeRequest, BlobReadOptions, BlobUri, } from "./blob"; @@ -106,13 +117,34 @@ export { RenameTableOptions, } from "./connection"; +export type { + FunctionErrorRowsOptions, + FunctionFailedRow, + FunctionRecompute, + RefreshColumnJobResult, + RetryFailedOptions, + UpgradeColumnOptions, +} from "./function_recovery"; + export { JobFailureInfo, JobInfo, Session } from "./native.js"; export { Job, JobEventsOptions, } from "./job"; -export type { JobProgress, JobProgressCallback } from "./job"; +export type { + JobProgress, + JobProgressCallback, + JobState, + JobWaitOptions, +} from "./job"; +export type { + FunctionProfile, + FunctionProfileKind, + FunctionProfileOptions, + FunctionProfileStatus, + FunctionProfileWaitOptions, +} from "./profiling"; export { AutoQuery, @@ -147,12 +179,22 @@ export { HnswPqOptions, HnswSqOptions, FtsOptions, + RTreeOptions, BaseTokenizer, } from "./indices"; export { Table, + TableDelta, + TableDeltaReader, + TableDeltaTransaction, + DeltaVersion, + FunctionColumnAutoRefreshStatus, + FunctionColumnLastRefreshJob, + FunctionColumnStatus, + FunctionColumnVersionStatus, Branches, + CreateBranchOptions, BranchColumnSummary, BranchColumnChange, BranchIndexSummary, @@ -164,6 +206,8 @@ export { AddDataOptions, UpdateOptions, OptimizeOptions, + CompactionOptions, + PrewarmDataOptions, Version, WriteProgress, FtsToken, @@ -653,3 +697,14 @@ export { } from "./catalog"; export { Listing, ListingOptions } from "./listing"; + +export type { CompactionResult } from "./compaction"; +export type { CleanupOptions, CleanupPlan, CleanupResult } from "./cleanup"; + +export type { + PrewarmDataPlan, + PrewarmDataResult, + PrewarmPruningSummary, +} from "./prewarm"; + +export type { QueryParameters, QueryParameterValue } from "./sql"; diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index 53cbf8a4d..23536bb07 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -678,6 +678,18 @@ export interface FtsOptions { blockSize?: 128 | 256; } +/** + * Options to create an `RTREE` index + */ +export interface RTreeOptions { + /** + * The maximum number of entries in each R-tree page. + * + * Must be at least 2. The default is 4096. + */ + pageSize?: number; +} + export class Index { private readonly inner: LanceDbIndex; private constructor(inner: LanceDbIndex) { @@ -834,6 +846,84 @@ export class Index { return new Index(LanceDbIndex.fm()); } + /** + * Create an RTree index. + * + * An RTree index is a scalar index on a GeoArrow geometry column, that is, a + * column whose Arrow field metadata sets `ARROW:extension:name` to a GeoArrow + * type such as `geoarrow.point`, `geoarrow.polygon` or `geoarrow.wkb`. It + * stores the bounding box of each geometry and accelerates spatial filters. + * + * The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`, + * `ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` + * between the indexed column and a constant geometry, in either argument + * order, for example + * `ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))`, as well as + * `geom IS NULL`. These filters can be combined with other conditions using + * `AND`. + * + * See the R-tree section of https://docs.lancedb.com/indexing/scalar-index + * for storing geometry, the other spatial functions, and spatial filters on + * vector search. + * + * Remote tables send the `RTREE` index type to the server, which must + * support it. + * + * @example + * ```ts + * await table.createIndex("geom", { config: Index.rtree() }); + * await table + * .query() + * .where("ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))") + * .toArray(); + * ``` + */ + static rtree(options?: Partial) { + const pageSize = options?.pageSize; + // napi converts a number to u32 by wrapping, so -1 would arrive as + // 4294967295; reject anything that is not a valid page size first. + if ( + pageSize !== undefined && + !(Number.isInteger(pageSize) && pageSize >= 2 && pageSize <= 0xffffffff) + ) { + throw new Error( + `RTree page_size must be at least 2, at most 4294967295, and an integer, got ${pageSize}`, + ); + } + return new Index(LanceDbIndex.rtree(pageSize)); + } + + /** + * Create a scalar index of a type recognized by a registered database plugin. + * + * Use this for index types without a dedicated factory on `Index`. + * Prefer a dedicated factory when one is available. + * + * An unknown plugin name or invalid parameters cause `createIndex` to fail. + * + * @param indexType - The index type, case-insensitive. + * Surrounding whitespace is ignored. Must not be empty. + * @param params - The index parameters, as an object or as a string + * holding a JSON object. They are passed as given. Each plugin defines + * its parameters and defaults; refer to the plugin's documentation + * for guidance. + * @throws If `indexType` is empty, or `params` is not a JSON object. + * + * @example + * ```ts + * await table.createIndex("id", { + * config: Index.plugin("bloomfilter", { number_of_items: 4096 }), + * }); + * ``` + */ + static plugin(indexType: string, params?: Record | string) { + const paramsJson = + params === undefined || typeof params === "string" + ? params + : JSON.stringify(params); + return new Index(LanceDbIndex.plugin(indexType, paramsJson)); + } + /** * Create a full text search index * diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index f38d8d7fa..a8298c8b9 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -1,8 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { writeFile } from "node:fs/promises"; import { Table as ArrowTable, tableFromIPC } from "apache-arrow"; -import { JobFailureInfo, Job as NativeJob } from "./native"; +import { decodeCleanupResult } from "./cleanup"; +import { decodeCompactionResult } from "./compaction"; +import type { JobFailureInfo, Job as NativeJob } from "./native"; +import { decodePrewarmDataResult } from "./prewarm"; +import { + type FunctionProfile, + type FunctionProfileOptions, + type FunctionProfileWaitOptions, + decodeFunctionProfile, + validateProfileOptions, +} from "./profiling"; /** Which of a job's events {@link Job.events} returns. */ export interface JobEventsOptions { @@ -10,6 +21,8 @@ export interface JobEventsOptions { limit?: number; /** SQL-like filter over the event columns. */ filter?: string; + /** Opaque continuation from the preceding page's schema metadata. */ + pageToken?: string; } /** @@ -39,6 +52,31 @@ export interface JobProgress { rows_remaining?: number | null; // biome-ignore lint/style/useNamingConvention: server wire format rows_failed?: number | null; + /** Maintenance work observations; rewritten rows are not committed rows. */ + // biome-ignore lint/style/useNamingConvention: server wire format + groups_planned?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + groups_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + rows_rewritten?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_targeted?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_partial?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_active?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_failed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + fragments_selected?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + ranges_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + ranges_planned?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + bytes_read?: number | null; /** Execution identity and sample time used for client-side ETA derivation. */ // biome-ignore lint/style/useNamingConvention: server wire format execution_epoch?: number | null; @@ -54,6 +92,28 @@ export interface JobProgress { /** Callback for progress snapshots observed while waiting for a job. */ export type JobProgressCallback = (progress: JobProgress) => void; +/** Client-side controls for waiting without cancelling the underlying job. */ +export interface JobWaitOptions { + /** + * Maximum wait in milliseconds, including status requests and polling backoff. + * Must be a nonnegative safe integer. Omit to wait indefinitely; zero allows + * only an immediately ready result. + */ + timeoutMs?: number; + /** Observe progress using the same poller that waits for completion. */ + onProgress?: JobProgressCallback; +} +/** Detailed lifecycle state. Unrecognized future values remain strings. */ +export type JobState = + | "created" + | "queued" + | "in_progress" + | "succeeded" + | "failed" + | "canceled" + | "timed_out" + | (string & {}); + /** * A handle to an operation that may still be running. * @@ -71,11 +131,22 @@ export type JobProgressCallback = (progress: JobProgress) => void; * * @hideconstructor */ -export class Job { +export class Job { private readonly inner: NativeJob; - constructor(inner: NativeJob) { + private readonly resultDecoder?: (value: unknown) => T; + + constructor(inner: NativeJob, resultDecoder?: (value: unknown) => T) { this.inner = inner; + this.resultDecoder = + resultDecoder ?? + (inner.jobType === "prewarm_page_cache" + ? (decodePrewarmDataResult as (value: unknown) => T) + : inner.jobType === "compact" + ? (decodeCompactionResult as (value: unknown) => T) + : inner.jobType === "cleanup" + ? (decodeCleanupResult as (value: unknown) => T) + : undefined); } /** @@ -90,6 +161,56 @@ export class Job { return this.inner.id ?? null; } + /** + * Identity of the selected attempt last observed by this handle. + * For operation handles, `refresh()` or `status()` can select a different + * attempt while `id` stays unchanged. Save this value after refreshing and + * use it throughout paged diagnostics. Local IDs cannot be reopened on a server. + */ + get jobId(): string | null { + return this.inner.jobId ?? null; + } + + /** Root of the explicit retry lineage, when reported. */ + get operationId(): string | null { + return this.inner.operationId ?? null; + } + + /** One-based attempt ordinal. Worker replacement does not increment it. */ + get attempt(): number | null { + return this.inner.attempt ?? null; + } + + /** Immediate predecessor attempt, when reported. */ + get retryOf(): string | null { + return this.inner.retryOf ?? null; + } + + /** Detailed state last observed; unknown values never establish success. */ + get lifecycleState(): JobState | null { + return this.inner.lifecycleState ?? null; + } + + /** Source snapshot pinned for this attempt, when reported. */ + get sourceTableVersion(): number | null { + return this.inner.sourceTableVersion ?? null; + } + + /** Most recent execution's fencing token, when reported. */ + get executionEpoch(): number | null { + return this.inner.executionEpoch ?? null; + } + + /** Refresh and return the detailed lifecycle state. */ + async statusTyped(): Promise { + const state = await this.status(); + if (this.lifecycleState !== null) return this.lifecycleState; + if (state === "running") return "in_progress"; + if (state === "finished") return "succeeded"; + if (state === "cancelled") return "canceled"; + return state; + } + /** The last observed lifecycle state, without contacting the backend. */ get state(): string | null { return this.inner.state ?? null; @@ -130,8 +251,8 @@ export class Job { } /** - * The operation's current lifecycle state: "running", "finished", "failed", - * or "cancelled". + * The current status, usually "running", "finished", "failed", or "cancelled". + * A Function refresh waiting for execution workers reports "waiting_for_capacity". * * A point snapshot; unlike {@link Job.wait} it does not block or reject on a * terminal failure state. Also refreshes the getters above. @@ -161,18 +282,64 @@ export class Job { * synchronous observer: its return value is ignored and not awaited. If it * throws, the error is logged with `console.warn` and waiting continues; a * callback exception does not reject `wait`. + * + * Pass an options object to set a client-side timeout. Expiry rejects with an + * error and stops this wait, including pending status requests and backoff. + * The operation continues; use the same handle to wait again. Registry jobs + * can also be reopened with `Connection.openJob`; query IDs cannot. + * + * @example + * ```ts + * const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log }); + * ``` */ - async wait(progressCallback?: JobProgressCallback): Promise { - if (progressCallback === undefined) { - return this.inner.wait(); + async wait( + optionsOrProgress?: JobWaitOptions | JobProgressCallback, + ): Promise { + const options: JobWaitOptions = + typeof optionsOrProgress === "function" + ? { onProgress: optionsOrProgress } + : (optionsOrProgress ?? {}); + if (typeof options !== "object" || Array.isArray(options)) { + throw new TypeError( + "wait expects an options object or a progress callback", + ); } - return this.inner.wait((progress) => { - try { - progressCallback(this.enrichProgress(progress)); - } catch (error) { - console.warn("Job progress callback threw:", error); + for (const key of Object.keys(options)) { + if (key !== "timeoutMs" && key !== "onProgress") { + throw new TypeError(`Unknown job wait option: ${key}`); } - }); + } + const { timeoutMs, onProgress: progressCallback } = options; + if ( + timeoutMs !== undefined && + (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) + ) { + throw new RangeError("timeoutMs must be a nonnegative safe integer"); + } + if ( + progressCallback !== undefined && + typeof progressCallback !== "function" + ) { + throw new TypeError("onProgress must be a function"); + } + const callback = + progressCallback === undefined + ? undefined + : (progress: Record) => { + try { + progressCallback(this.enrichProgress(progress)); + } catch (error) { + console.warn("Job progress callback threw:", error); + } + }; + if (this.resultDecoder !== undefined) { + return this.resultDecoder( + await this.inner.waitResult(callback, timeoutMs), + ); + } + await this.inner.wait(callback, timeoutMs); + return undefined as T; } /** Request cancellation. Cancelling a finished operation is a no-op. */ @@ -180,6 +347,11 @@ export class Job { return this.inner.cancel(); } + /** Select this exact attempt's pinned successor. Requires backend support. */ + async retry(): Promise> { + return new Job(await this.inner.retry(), this.resultDecoder); + } + /** * Ask the backend for this job's current state, and for a server-side job * its full record, then cache it for the getters above. @@ -203,13 +375,122 @@ export class Job { * `updated_by`, `emitted_from`, `emitted_by`, and `claim_entity` columns. */ async events(options?: JobEventsOptions): Promise { - const buf = await this.inner.events(options?.limit, options?.filter); + const buf = await this.inner.events( + options?.limit, + options?.filter, + options?.pageToken, + ); if (buf.length === 0) { return new ArrowTable(); } return tableFromIPC(buf); } + /** Walk retained history one page at a time using the server's continuation. */ + async *history(options?: JobEventsOptions): AsyncGenerator { + let pageToken = options?.pageToken; + for (;;) { + const page = await this.events({ ...options, pageToken }); + yield page; + const next = page.schema.metadata.get( + "lancedb.job_coordinator.page_token", + ); + if (next === undefined) return; + if (next === pageToken) + throw new Error("Job history repeated its page token"); + pageToken = next; + } + } + + /** + * Request a profile of a running Enterprise Function worker session. + * Returns the accepted identity without waiting for recording to finish. + * Requires System Operate permission and server profiling support. The server + * pins the worker, Python session and execution epoch. One capture per job + * can be active. Captures add workload-dependent overhead. + * + * GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU sampling requires + * readable per-thread procfs and is unavailable in dedicated sandboxes. + * + * @example + * ```ts + * const profile = await job.captureProfile("worker-id", { + * kind: "gpu", durationSeconds: 2, + * }); + * await job.waitForProfile(profile.profileId, { timeoutMs: 60_000 }); + * await job.exportProfile(profile.profileId, "gpu.trace.json"); + * ``` + */ + async captureProfile( + workerId: string, + options: FunctionProfileOptions = {}, + ): Promise { + validateProfileOptions(options, ["kind", "durationSeconds", "sessionSlot"]); + const kind = options.kind ?? "cpu"; + if (!["cpu", "gpu", "memory"].includes(kind)) { + throw new TypeError("kind must be cpu, memory or gpu"); + } + return decodeFunctionProfile( + await this.inner.captureProfile( + workerId, + kind, + options.durationSeconds, + options.sessionSlot, + ), + ); + } + + /** + * Fetch capture identity and status, including retained lookup after refresh. + * Failed captures return status "failed" with the server's error reason. + * This never changes the parent job's cached state. + */ + async profileStatus(profileId: string): Promise { + return decodeFunctionProfile(await this.inner.profileStatus(profileId)); + } + + /** + * Wait for a capture with a configurable timeout and polling cadence. + * Defaults to 60 seconds with two seconds between requests. A timeout stops + * only this wait; the capture and Function refresh continue. A failed capture + * rejects with its server-reported reason. Keep its ID to wait again. + */ + async waitForProfile( + profileId: string, + options: FunctionProfileWaitOptions = {}, + ): Promise { + validateProfileOptions(options, ["timeoutMs", "pollIntervalMs"]); + return decodeFunctionProfile( + await this.inner.waitForProfile( + profileId, + options.timeoutMs, + options.pollIntervalMs, + ), + ); + } + + /** + * Retrieve a completed capture's actual JSON: speedscope for CPU, + * tracemalloc for Python allocations, or Chrome Trace Event JSON for GPU. + * Truncation flags are preserved. Retention is at most one hour and eight + * captures per job, until earlier scratch reclamation or archival. + * Permission, expired-artifact and unsupported-server errors propagate. + */ + async profileArtifact(profileId: string): Promise> { + return JSON.parse(await this.inner.profileArtifact(profileId)); + } + + /** + * Write a completed capture's JSON after successful retrieval. Open CPU + * exports in speedscope and GPU exports in Perfetto. GPU activity durations + * can overlap and are not utilization; Python operator attribution and GPU + * allocation stacks are excluded. Filesystem errors propagate to the caller. + */ + async exportProfile(profileId: string, path: string): Promise { + const artifact = await this.inner.profileArtifact(profileId); + await writeFile(path, artifact, "utf8"); + } + private lastProgress: JobProgress | null = null; private enrichProgress(progress: Record): JobProgress { diff --git a/nodejs/lancedb/materialized_view.ts b/nodejs/lancedb/materialized_view.ts index afb61b9ab..d6c101b67 100644 --- a/nodejs/lancedb/materialized_view.ts +++ b/nodejs/lancedb/materialized_view.ts @@ -197,11 +197,39 @@ export class MaterializedView { async refresh(options?: { full?: boolean; sourceVersion?: number; + totalCpuMillis?: number; + totalMemoryBytes?: number; + totalGpuCount?: number; + gpuClass?: string; + gpuCount?: number; }): Promise { validateNonNegativeInteger(options?.sourceVersion, "sourceVersion"); + for (const [name, value] of [ + ["totalCpuMillis", options?.totalCpuMillis], + ["totalMemoryBytes", options?.totalMemoryBytes], + ["totalGpuCount", options?.totalGpuCount], + ["gpuCount", options?.gpuCount], + ] as const) { + validateNonNegativeInteger(value, name); + if (value === 0 && name !== "totalGpuCount") { + throw new Error(`${name} must be positive`); + } + if ( + (name === "gpuCount" || name === "totalGpuCount") && + value !== undefined && + value > 4294967295 + ) { + throw new Error(`${name} exceeds 4294967295`); + } + } return await this.inner.refreshMaterializedView( options?.sourceVersion, options?.full, + options?.totalCpuMillis, + options?.totalMemoryBytes, + options?.totalGpuCount, + options?.gpuClass, + options?.gpuCount, ); } } diff --git a/nodejs/lancedb/merge.ts b/nodejs/lancedb/merge.ts index 7bb36e678..7d95d4a36 100644 --- a/nodejs/lancedb/merge.ts +++ b/nodejs/lancedb/merge.ts @@ -127,6 +127,14 @@ export class MergeInsertBuilder { data: Data, execOptions?: Partial, ): Promise { + if ( + execOptions?.retries !== undefined && + (!Number.isInteger(execOptions.retries) || + execOptions.retries < 0 || + execOptions.retries > 255) + ) { + throw new Error("retries must be an integer between 0 and 255"); + } let schema: Schema; if (this.#schema instanceof Promise) { schema = await this.#schema; @@ -140,7 +148,7 @@ export class MergeInsertBuilder { } const buffer = await fromDataToBuffer(data, undefined, schema); - return await this.#native.execute(buffer); + return await this.#native.execute(buffer, execOptions?.retries); } } @@ -156,6 +164,24 @@ export interface WriteExecutionOptions { * first attempt will not be cancelled. * * When this is set, the timeout is enforced on all attempts, including the first. + * For remote tables this is sent as a server execution timeout. It does not + * extend HTTP read or proxy idle timeouts, or prove that a failed request did + * not commit. */ timeoutMs?: number; + + /** + * Override the remote retry budget for this execution only (an integer from + * 0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after + * precommit conflicts (409) or rate limits (429). This does not change + * connection-wide/read budgets or local transaction conflict retries. + * + * By default, remote calls use the connection's `clientConfig.retryConfig` + * ({@link RetryConfig}). Its `statuses` (also set through + * `LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget; + * it never permits replay of ambiguous merge outcomes. In particular, 502, + * ordinary 503, and 504 are never replayed, even if configured. Reconcile table + * contents before manually repeating a merge whose commit outcome is unknown. + */ + retries?: number; } diff --git a/nodejs/lancedb/prewarm.ts b/nodejs/lancedb/prewarm.ts new file mode 100644 index 000000000..3d40cd5c9 --- /dev/null +++ b/nodejs/lancedb/prewarm.ts @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Reported executor work for a pinned snapshot; unavailable measurements stay null. */ +export interface PrewarmDataResult { + /** The source snapshot captured by submission. */ + tableVersion: number; + /** Reported executors targeted, or null when unavailable. */ + executorsTargeted: number | null; + /** Executors that finished successfully or partially, or null when unavailable. */ + executorsCompleted: number | null; + /** Subset of completed executors reporting partial warming, or null when unavailable. */ + executorsPartial: number | null; + /** Reported fragments selected, or null when unavailable. */ + fragmentsSelected: number | null; + /** Reported ranges completed, or null when unavailable. */ + rangesCompleted: number | null; + /** Reported bytes read, or null when unavailable. */ + bytesRead: number | null; +} + +/** @internal */ +export function decodePrewarmDataResult(value: unknown): PrewarmDataResult { + // Rust validates the typed wire result before handing it to JavaScript. + const result = value as Record; + return { + tableVersion: result.table_version as number, + executorsTargeted: result.executors_targeted ?? null, + executorsCompleted: result.executors_completed ?? null, + executorsPartial: result.executors_partial ?? null, + fragmentsSelected: result.fragments_selected ?? null, + rangesCompleted: result.ranges_completed ?? null, + bytesRead: result.bytes_read ?? null, + }; +} + +/** Metadata-only snapshot preview; no warming job is submitted. */ +export interface PrewarmDataPlan { + /** Snapshot used for this preview. A later submission plans its own snapshot. */ + tableVersion: number; + /** Readable display text. Use pruning for structured facts. */ + plan: string; + pruning: PrewarmPruningSummary; +} + +/** Conservative metadata proof, rather than exact matching rows. */ +export interface PrewarmPruningSummary { + /** Server-reported proof mode; future servers may add modes. */ + mode: string; + inputFragments: number; + selectedFragments: number; + prunedFragments: number; + /** Candidate physical intervals, or null when unknown. */ + selectedRowRanges: number | null; + fallbackReason: string | null; +} + +/** @internal */ +export function decodePrewarmDataPlan(value: unknown): PrewarmDataPlan { + // Rust validates the versioned response before handing it to JavaScript. + const result = value as { + [key: string]: unknown; + pruning: Record; + }; + return { + tableVersion: result.table_version as number, + plan: result.plan as string, + pruning: { + mode: result.pruning.mode as string, + inputFragments: result.pruning.input_fragments as number, + selectedFragments: result.pruning.selected_fragments as number, + prunedFragments: result.pruning.pruned_fragments as number, + selectedRowRanges: + (result.pruning.selected_row_ranges as number | null) ?? null, + fallbackReason: (result.pruning.fallback_reason as string | null) ?? null, + }, + }; +} diff --git a/nodejs/lancedb/profiling.ts b/nodejs/lancedb/profiling.ts new file mode 100644 index 000000000..772c84d9d --- /dev/null +++ b/nodejs/lancedb/profiling.ts @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Evidence collected from one Function worker's Python execution session. */ +export type FunctionProfileKind = "cpu" | "gpu" | "memory"; + +/** A capture's lifecycle, independent of its parent refresh job. */ +export type FunctionProfileStatus = + | "pending" + | "capturing" + | "complete" + | "failed"; + +/** Options for requesting a Function worker capture. */ +export interface FunctionProfileOptions { + /** CPU samples, retained Python allocations, or PyTorch CUDA activities. */ + kind?: FunctionProfileKind; + /** 1–30 seconds for CPU/memory, default 10; 1–5 for GPU, default 5. */ + durationSeconds?: number; + /** Python execution session within the worker; default zero. */ + sessionSlot?: number; +} + +/** Client-side controls while waiting for a Function worker capture. */ +export interface FunctionProfileWaitOptions { + /** Maximum wait including HTTP requests and sleeps; defaults to 60,000 ms. */ + timeoutMs?: number; + /** Delay between status requests; defaults to 2,000 ms and must be positive. */ + pollIntervalMs?: number; +} + +/** + * A capture identity and status snapshot. Keep profileId for retained lookup + * after the Function refresh completes. Timestamp fields are epoch milliseconds. + */ +export interface FunctionProfile { + readonly profileId: string; + readonly jobId: string; + readonly workerId: string; + readonly executionEpoch: number; + readonly sessionSlot: number; + readonly kind: FunctionProfileKind; + readonly durationSeconds: number; + readonly status: FunctionProfileStatus; + readonly requestedAtMillis: number; + readonly deadlineAtMillis: number; + /** Upper retention bound; job scratch reclamation can remove artifacts sooner. */ + readonly expiresAtMillis: number; + readonly completedAtMillis: number | null; + /** The server's capture failure reason; this is not a refresh job failure. */ + readonly error: string | null; + readonly artifactId: string | null; +} + +export function decodeFunctionProfile(value: string): FunctionProfile { + const data = JSON.parse(value); + return { + profileId: data.profile_id, + jobId: data.job_id, + workerId: data.worker_id, + executionEpoch: data.execution_epoch, + sessionSlot: data.session_slot, + kind: data.kind, + durationSeconds: data.duration_seconds, + status: data.status, + requestedAtMillis: data.requested_at_millis, + deadlineAtMillis: data.deadline_at_millis, + expiresAtMillis: data.expires_at_millis, + completedAtMillis: data.completed_at_millis, + error: data.error, + artifactId: data.artifact_id, + }; +} + +export function validateProfileOptions(options: object, names: string[]): void { + if ( + typeof options !== "object" || + options === null || + Array.isArray(options) + ) { + throw new TypeError("profiling expects an options object"); + } + for (const key of Object.keys(options)) { + if (!names.includes(key)) { + throw new TypeError(`Unknown profiling option: ${key}`); + } + } +} diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 8f16defbf..6b72f19fd 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -17,6 +17,7 @@ import { tableFromIPC, vectorFromArray, } from "./arrow"; +import { isBlobDescriptorField, isBlobField } from "./blob"; import { Expr } from "./expr"; import { type IvfPqOptions } from "./indices"; import { @@ -148,6 +149,34 @@ async function readBlobBytes( ); } +// Discover descriptors from the executed query, not the live table's cached +// schema. Projection names are literal aliases; only source paths use dots. +function projectedBlobSources( + schema: Schema, + projection: [string, string][] | undefined, +): BlobSource[] { + const sources: BlobSource[] = []; + for (const field of schema.fields) { + const source = + projection?.find(([output]) => output === field.name)?.[1] ?? field.name; + const visit = (child: Field, path: string[]) => { + if (isBlobField(child) || isBlobDescriptorField(child)) { + sources.push({ + output: field.name, + path, + source: [source, ...path].join("."), + }); + } else if (DataType.isStruct(child.type)) { + for (const nested of child.type.children) { + visit(nested, [...path, nested.name]); + } + } + }; + visit(field, []); + } + return sources; +} + function withBinaryColumns( table: ArrowTable, replacements: Map, @@ -237,6 +266,9 @@ export interface QueryExecutionOptions { /** * Timeout for query execution in milliseconds + * + * The timeout also covers reading the results, so consuming them slowly can + * exceed it. */ timeoutMs?: number; @@ -254,8 +286,10 @@ export interface QueryExecutionOptions { * bytes. Blobs inside lists keep their descriptors. Arbitrary projection * expressions are not materialized as bytes. * - * The rows and the bytes come from the same table version. If the table - * changes while the query runs, the query runs again, up to three times. + * The rows and bytes come from the same snapshot. Remote queries require + * authoritative query version and snapshot identity headers, verified again + * by the blob response. Older servers can still return `"descriptions"`. + * Local queries retry up to three times if the table changes while they run. * * @example * ```ts @@ -496,6 +530,34 @@ export class QueryBase< if (context === undefined) { return this.collect(options, false); } + if (!context.table.isNative()) { + // Request row IDs in the same query so newly added Blob columns can be + // fetched without rerunning the query against a different snapshot. + const addRowId = !context.withRowId; + const table = await this.collect(options, addRowId); + const sources = projectedBlobSources(table.schema, context.projection); + if (sources.length === 0) { + return addRowId + ? table.select( + table.schema.fields + .map((field) => field.name) + .filter((name) => name !== "_rowid"), + ) + : table; + } + const version = table.schema.metadata.get("lancedb:query_version"); + const identity = table.schema.metadata.get("lancedb:query_snapshot"); + if (version === undefined || identity === undefined) { + throw new Error( + 'blobMode "bytes" requires a trustworthy query snapshot: missing, invalid, or inconsistent x-lancedb-query-version or x-lancedb-query-snapshot. Upgrade every serving node, or use blobMode "descriptions".', + ); + } + const snapshot = await context.table.querySnapshotWithIdentity( + version, + identity, + ); + return readBlobBytes(table, sources, snapshot, addRowId); + } for (let attempt = 1; ; attempt++) { // The snapshot pins the bytes. The query runs on the live table, so an // unchanged version afterwards proves it read the snapshot's version. @@ -530,10 +592,10 @@ export class QueryBase< for await (const batch of RecordBatchIterator(iterator)) { batches.push(batch); } - if (batches.length === 0) { - return tableFromIPC((await iterator).schema()); - } - return new ArrowTable(batches); + // Read metadata from the executed stream, including empty results and + // query types whose individual batches do not carry the stream metadata. + const schema = tableFromIPC((await iterator).schema()).schema; + return new ArrowTable(schema, batches); } private blobBytesContext( @@ -854,6 +916,11 @@ export class VectorQuery extends StandardQueryBase { /** * Set the initial IVF search effort to a finite value in [0, 1]. * + * Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + * 80% and 90% for L2, cosine and dot through k=100000. The probe budget + * adapts to the metric and k. Hamming and larger k remain uncalibrated; + * 100000 is not an API limit. Remote queries also require server support. + * * The default, null, uses Auto (internally 0.5). Zero starts at the caller * minimum; one searches all partitions within the caller maximum. Later * probing may continue when too few candidates are found. diff --git a/nodejs/lancedb/sql.ts b/nodejs/lancedb/sql.ts new file mode 100644 index 000000000..e7cb4de6f --- /dev/null +++ b/nodejs/lancedb/sql.ts @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + Binary, + Bool, + type DataType, + Float64, + Int64, + Null, + RecordBatchFileWriter, + type RecordBatchLike, + Table, + type TableLike, + TimestampMillisecond, + Utf8, + vectorFromArray, +} from "./arrow"; +import { sanitizeTable } from "./sanitize"; + +/** Scalar SQL values. Use a one-row Arrow table for explicit Arrow types. */ +export type QueryParameterValue = + | string + | number + | bigint + | boolean + | Date + | Uint8Array + | null; + +/** Values for `$1`/`$name` placeholders, sent separately from SQL text. + * Arrays bind by position; objects bind by name. Arrow columns bind both ways. + * Safe integers and bigint use Int64; fractional numbers use Float64. + * Arrow input preserves explicit types. + */ +export type QueryParameters = + | readonly QueryParameterValue[] + | Readonly> + | TableLike + | RecordBatchLike; + +/** @internal */ +export async function toParameterBuffer( + parameters: QueryParameters, +): Promise { + let table: Table; + if ( + "schema" in parameters && + parameters.schema !== null && + typeof parameters.schema === "object" && + "fields" in parameters.schema + ) { + const arrow = parameters as TableLike | RecordBatchLike; + table = sanitizeTable( + "batches" in arrow ? arrow : { schema: arrow.schema, batches: [arrow] }, + ); + } else { + const entries = Array.isArray(parameters) + ? parameters.map((value, index) => [String(index + 1), value] as const) + : Object.entries(parameters); + const columns = Object.fromEntries( + entries.map(([name, input]) => { + let value = input; + let type: DataType; + if (value === null) type = new Null(); + else if (typeof value === "string") type = new Utf8(); + else if (typeof value === "boolean") type = new Bool(); + else if (typeof value === "number") { + if ( + !Number.isFinite(value) || + (Number.isInteger(value) && !Number.isSafeInteger(value)) + ) { + throw new Error( + "Numeric parameters must be finite and integers must be safe; use bigint for Int64", + ); + } + type = Number.isInteger(value) ? new Int64() : new Float64(); + if (Number.isInteger(value)) value = BigInt(value); + } else if (typeof value === "bigint") { + if (value < -(1n << 63n) || value >= 1n << 63n) { + throw new Error("bigint parameters must fit Int64"); + } + type = new Int64(); + } else if (value instanceof Date && Number.isFinite(value.getTime())) { + type = new TimestampMillisecond(); + } else if (value instanceof Uint8Array) type = new Binary(); + else + throw new Error( + "Query parameters must be scalar values or a one-row Arrow table", + ); + return [name, vectorFromArray([value], type)]; + }), + ); + table = new Table(columns); + } + if (table.numRows !== 1) { + throw new Error( + `Query parameters must contain exactly one row, got ${table.numRows}`, + ); + } + return Buffer.from( + await RecordBatchFileWriter.writeAll(table).toUint8Array(), + ); +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 29707c5ae..9888a5e2b 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1,6 +1,22 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { + CleanupOptions, + CleanupPlan, + CleanupResult, + decodeCleanupPlan, + decodeCleanupResult, + validateCleanupOptions, +} from "./cleanup"; +import { CompactionResult, decodeCompactionResult } from "./compaction"; +import { + PrewarmDataPlan, + PrewarmDataResult, + decodePrewarmDataPlan, + decodePrewarmDataResult, +} from "./prewarm"; + import { Table as ArrowTable, Data, @@ -8,6 +24,7 @@ import { Field, IntoVector, MultiVector, + RecordBatch, Schema, dataTypeToJson, fromDataToBuffer, @@ -17,8 +34,24 @@ import { tableFromIPC, } from "./arrow"; -import { BlobFile, BlobReadOptions, runWithSignal } from "./blob"; +import { + BlobDescriptor, + BlobFile, + BlobRangeRequest, + BlobReadOptions, + runWithSignal, + toNativeBlobDescriptor, +} from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; +import { + type FunctionErrorRowsOptions, + type FunctionFailedRow, + type RefreshColumnJobResult, + type RetryFailedOptions, + type UpgradeColumnOptions, + decodeRefreshColumnJobResult, + readFailedRows, +} from "./function_recovery"; import { IndexOptions } from "./indices"; import { Job } from "./job"; import { validateNonNegativeInteger } from "./materialized_view"; @@ -33,11 +66,19 @@ import { DropColumnsResult, FunctionErrors, FunctionErrorsOptions, + FunctionProvenance, + FunctionProvenanceOptions, + FunctionQuarantineOptions, IndexConfig, IndexStatistics, + JobFailureInfo, + RecordBatchIterator as NativeBatchIterator, Branches as NativeBranches, + DeltaRef as NativeDeltaRef, + TableDelta as NativeTableDelta, OptimizeStats, RTEStats, + RefreshColumnOptions, RefreshColumnResult, RefreshMaterializedViewResult, TableStatistics, @@ -50,12 +91,14 @@ import { AutoQuery, FullTextQuery, Query, + RecordBatchIterator, TakeQuery, VectorQuery, createAutoQuery, instanceOfFullTextQuery, } from "./query"; import { sanitizeType } from "./sanitize"; +import { QueryParameters, toParameterBuffer } from "./sql"; import { IntoSql, toSQL } from "./util"; export { IndexConfig } from "./native"; export { @@ -135,6 +178,13 @@ export interface AddDataOptions { * when the blob is read later. */ allowExternalBlobOutsideBases?: boolean; + + /** + * Override the remote retry budget for this call (0 to 255). Zero disables + * retries, including multipart parts. Ambiguous commits are never replayed. + * Ignored by LanceDB Embedded. + */ + retries?: number; } export interface UpdateOptions { @@ -151,7 +201,43 @@ export interface UpdateOptions { where: string; } +/** Settings for data-cache prewarm submissions and metadata previews. */ +export interface PrewarmDataOptions { + /** Lance field paths to warm; omitted or empty means every column. */ + columns?: string[]; + /** A single SQL predicate for conservative metadata pruning. */ + filter?: string; + /** Typed positional or named filter values, sent separately from SQL. */ + parameters?: QueryParameters; + /** Positive per-executor concurrency, at most 4294967295. */ + concurrency?: number; +} + +/** Per-invocation compaction settings. Values must be safe integers. */ +export interface CompactionOptions { + /** Positive target rows per output fragment; also affects candidate selection. */ + targetRowsPerFragment?: number; + /** Positive live-source-row budget across whole tasks; an oversized first task can produce no work. */ + maxSourceRows?: number; + /** Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure. */ + ioBufferSize?: number; + /** Positive scanner batch size in rows. */ + batchSize?: number; +} + export interface OptimizeOptions { + /** + * Compaction settings for this invocation. Omitted remote values inherit table + * tuning, then deployment/built-in defaults. + * Remote tables require a server supporting these SQL options; settings do + * not change table policy. This is not a runtime or total-memory limit. + * @example + * await tbl.optimize({ compactionOptions: { + * targetRowsPerFragment: 1000, maxSourceRows: 5000, + * ioBufferSize: 64 * 1024 * 1024, batchSize: 128, + * } }); + */ + compactionOptions?: CompactionOptions; /** * If set then all versions older than the given date * be removed. The current version will never be removed. @@ -186,6 +272,42 @@ export interface Version { metadata: Record; } +/** + * One endpoint of a table delta: a positive version number/bigint or a tag on + * the table handle's current branch. + * + * Use a `bigint` when the version may exceed `Number.MAX_SAFE_INTEGER`. + * Strings are always tags. + */ +export type DeltaVersion = number | bigint | string; + +/** A committed transaction in a table delta range. */ +export interface TableDeltaTransaction { + /** The version the transaction was based on. Exact u64 value. */ + readVersion: bigint; + uuid: string; + operation: string; + tag?: string; + transactionProperties?: Record; +} + +/** + * A streaming table-delta reader. + * + * `schema()` is available before consuming the stream, including when the + * range is empty. The stream yields Arrow record batches without + * materializing the full result. + * + * A reader owns one native cursor. It is single-use: + * `[Symbol.asyncIterator]()` returns the same iterator, concurrent pulls are + * serialized, and `return()` releases the native stream on early drop. + */ +export interface TableDeltaReader + extends AsyncIterable, + AsyncIterator { + schema(): Promise; +} + /** Token produced by the tokenizer configured on a full-text search index. */ export interface FtsToken { /** Token text after tokenizer filters have been applied. */ @@ -233,6 +355,76 @@ export interface RTEWriteSpec { writerConfigDefaults?: Record; } +/** Exact immutable Function revision attached to a table output. */ +export interface FunctionColumnVersionStatus { + name: string; + namespacePath: string[]; + objectId: string; + location: string; + version: string; + manifestDigest: string; +} + +/** Latest matching refresh Job projected for a Function output. */ +export interface FunctionColumnLastRefreshJob { + jobId: string; + state: string; + automatic?: boolean; + completedAtMillis?: bigint; + /** Structured failure details for a failed Job. */ + failure?: JobFailureInfo; +} + +/** Automatic-refresh projection for a Function output. */ +export interface FunctionColumnAutoRefreshStatus { + enabled: boolean; + intervalSeconds?: bigint; + activeJobId?: string; + state: + | "disabled" + | "running" + | "queued" + | "ready" + | "up_to_date" + | "waiting_interval" + | "waiting_backoff" + | "blocked" + | "unobservable"; + failureStreak: number; + effectiveCooldownMillis?: bigint; + blockedReason?: + | "table_has_mem_wal" + | "inputs_not_settled" + | "dependency_in_flight" + | "table_capacity" + | "cancelled" + | "preparation_backoff" + | "failure_threshold_reached" + | "binding_revision_missing"; + nextRunAtMillis: bigint | null; + nextRunAtReason?: string; +} + +/** Exact four-way status of one Function output at one table version. */ +export interface FunctionColumnStatus { + column: string; + bindingId: string; + function: FunctionColumnVersionStatus; + tableVersion: bigint; + rows: bigint; + fresh: bigint; + stale: bigint; + neverComputed: bigint; + failed: bigint; + lastRefreshJob?: FunctionColumnLastRefreshJob; + /** + * Newest failed refresh Job. This remains present when `lastRefreshJob` + * is a later cancellation. + */ + lastFailureJob?: FunctionColumnLastRefreshJob; + autoRefresh: FunctionColumnAutoRefreshStatus; +} + /** * A Table is a collection of Records in a LanceDB Database. * @@ -454,22 +646,83 @@ export abstract class Table { /** * Prewarm one or more columns of data in the table. * - * @param columns The columns to prewarm. If undefined, all columns are prewarmed. - * * This will load the column data into the page cache so that future queries that * read those columns avoid the initial cold-start latency. This call initiates * prewarming and returns once the request is accepted; the warming itself may - * continue in the background. Calling it on already-prewarmed columns is a - * no-op on the server. + * continue in the background. Submission uses SQL PREWARM and needs Flight + * SQL connectivity. Use {@link prewarmDataAsync} to retain the job handle. * * Prewarming is generally useful for columns used in filters or projections. * Large columns (e.g. high-dimensional vectors or binary data) may not be * practical to prewarm. * * This feature is currently only supported in LanceDB Enterprise. + * + * @param options Columns, a metadata-pruning filter, and per-executor concurrency. + * Omitted or empty columns warm every column. + * + * @example + * await table.prewarmData({ + * columns: ["payload"], filter: "quality > 0.7", concurrency: 4, + * }); + */ + abstract prewarmData(options?: PrewarmDataOptions): Promise; + + /** + * Submit data prewarm using the columns-array form and return after acceptance. + * @param columns Columns to warm; omitted or empty means every column. */ abstract prewarmData(columns?: string[]): Promise; + /** + * Submit data prewarm through SQL and return its durable warming-job handle. + * + * The table handle supplies the branch and namespace. Requires a compatible + * SQL PREWARM server and Flight SQL connectivity. Standard authorization + * requires table Select and database/namespace Usage. Status/wait use generic + * HTTP job APIs; events and cancellation retain their own privileges. + * No REST fallback or option-dropping retry is performed. Historical-version + * handles are unsupported; call `checkoutLatest()` first. + * + * Submission returns after acceptance. Use `job.wait()` for completion, or + * save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel + * the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. + * + * @example + * const job = await table.prewarmDataAsync({ + * columns: ["video"], filter: "quality > $minimum", + * parameters: { minimum: 0.7 }, concurrency: 4, + * }); + * await job.wait(); + */ + abstract prewarmDataAsync( + options?: PrewarmDataOptions, + ): Promise>; + + /** + * Preview prewarm with the same options as {@link prewarmDataAsync}, without + * submitting a warming job. Requires LanceDB Enterprise with structured SQL + * previews, table Select and database/namespace Usage. Reads metadata and + * returns the source version, readable plan, and conservative pruning summary. + * A later submission plans its own snapshot. Historical and Embedded handles + * are unsupported. Unknown measurements remain null. + * Custom table implementations can override this method; its default rejects + * with an unsupported-operation error. + * + * @example + * const plan = await table.explainPrewarmData({ + * columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7}, + * }); + * console.log(plan.pruning.selectedFragments); + */ + async explainPrewarmData( + _options?: PrewarmDataOptions, + ): Promise { + throw new Error( + "data prewarm previews are not supported by this table implementation", + ); + } + /** * Waits for asynchronous indexing to complete on the table. * @@ -580,6 +833,31 @@ export abstract class Table { options?: BlobReadOptions, ): Promise<(Buffer | null)[]>; + /** + * Materializes row-specific byte ranges at the table's current checkout. + * Preserves request order, duplicates, and nulls. Zero length returns an empty + * buffer for a non-null blob. Invalid ranges or missing rows reject the entire + * call. See {@link Table.fetchBlobs} for row-ID validity across versions. + * + * Remote tables use the batched endpoint when the server advertises support, + * splitting at 1024 ranges and 64 MiB, including individual larger ranges. + * Older servers use descriptor queries and BlobFile range reads. Both protocols + * use one exact branch and version. Errors from an advertised endpoint propagate + * without switching protocols. All output bytes occupy memory. + * + * @example + * ```ts + * const bytes = await table.fetchBlobRanges("image", [ + * { rowId: 10n, offset: 0n, length: 1024n }, + * ]); + * ``` + */ + abstract fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]>; + /** * Opens lazy blob handles for `column` at the given row IDs using the * table's current checkout. @@ -595,6 +873,48 @@ export abstract class Table { options?: BlobReadOptions, ): Promise<(BlobFile | null)[]>; + /** + * Opens a lazy handle from a source-bearing SQL `blob_descriptor` result. + * + * The descriptor's source pins the table version, branch, column and row + * identity, so opening does not change this table's checkout. Null + * descriptors return `null`. Payload bytes load only when the returned + * handle is read. Pass {@link BlobReadOptions.signal} to cancel the open. + * + * @example + * ```ts + * const rows = await table + * .query() + * .select({ video: "blob_descriptor(video)" }) + * .toArray(); + * const handle = await table.openBlobFile(rows[0].video); + * if (handle) { + * const header = await handle.readRange(0n, 16n); + * await handle.close(); + * } + * ``` + */ + async openBlobFile( + _descriptor: BlobDescriptor | null, + _options?: BlobReadOptions, + ): Promise { + throw new Error("openBlobFile is not supported on this table type"); + } + + /** + * Opens source-bearing descriptors in iteration order, preserving nulls. + * Handles open lazily as the iterable advances. Close each non-null handle + * after use. + */ + async *openBlobFiles( + descriptors: Iterable, + options?: BlobReadOptions, + ): AsyncGenerator { + for (const descriptor of descriptors) { + yield await this.openBlobFile(descriptor, options); + } + } + /** * Create a search query to find the nearest neighbors * of the given query @@ -671,10 +991,15 @@ export abstract class Table { * everything else is left as it is. LanceDB Embedded only: in LanceDB * Enterprise a refresh runs as a server job, through {@link Table#refreshColumnAsync}. * @param {string} column The name of the computed column to fill. + * @param {RefreshColumnOptions} options Refresh options, all LanceDB + * Enterprise only; see {@link Table#refreshColumnAsync}. * @returns {Promise} A promise that resolves to the * number of rows filled and the new version number of the table. */ - abstract refreshColumn(column: string): Promise; + abstract refreshColumn( + column: string, + options?: RefreshColumnOptions, + ): Promise; /** * Like {@link Table#refreshColumn}, but returns a handle to the refresh @@ -689,36 +1014,156 @@ export abstract class Table { * than failing the job. In LanceDB Embedded the job runs in-process; in * LanceDB Enterprise it is the server's backfill job. * @param {string} column The name of the computed column to fill. + * @param {RefreshColumnOptions} options Refresh options, mirroring the SQL + * `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, + * `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` + * and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, + * `maxConcurrency`, `totalCpuMillis`, `totalMemoryBytes`, `supervisorResources`, + * `planningWorkers` and `maxExecutorProcessesPerWorker` size registered + * Function refreshes. `retryPolicy` overrides user-code retries only when + * repeating partial work is safe; set `maxAttempts: 1` to disable retries. + * `maxConcurrency` overrides the registered default for this logical + * execution only and is a positive integer; it is not an account-wide + * quota. `totalCpuMillis`, `totalMemoryBytes`, and `totalGpuCount` override + * their corresponding execution-wide resource limits independently. Unset + * values inherit column defaults, then Function defaults, then deployment + * defaults. A zero GPU limit is valid for CPU-only Functions. + * `supervisorResources` and `planningWorkers.resources` are per-pod sizes. + * `numWorkers` applies only to expression columns. + * `publicationIntervalRows` opts into publishing completed Function split + * ranges once their accumulated unpublished rows reach the threshold. + * It must be a positive safe integer and requires non-Blob Function outputs. + * Omit it for whole-fragment publication. Publications can exceed the + * threshold, and remaining rows publish at completion. * @example * ```ts - * const job = await table.refreshColumnAsync("doubled"); + * const job = await table.refreshColumnAsync("embedding", { + * where: "published_at > '2026-01-01'", + * totalCpuMillis: 8000, + * totalMemoryBytes: 16 * 1024 ** 3, + * maxConcurrency: 4, + * publicationIntervalRows: 10000, + * errorPolicy: "skip", + * maxFailedFraction: 0.01, + * rowTimeoutSeconds: 30, + * }); * await job.wait(); * console.log(await job.status()); // "finished" * ``` */ - abstract refreshColumnAsync(column: string): Promise; + abstract refreshColumnAsync( + column: string, + options?: RefreshColumnOptions, + ): Promise; /** - * The per-row errors Function refreshes recorded on this table. + * List the per-row errors recorded by Function refreshes on this table. + * + * On LanceDB Enterprise with workflow version 1 or later, the default + * lists current failures. Set `history: true` to include retained attempts + * for repaired rows. Older deployments keep their existing default listing. + * Reading errors requires table read access because messages can include the + * input that failed. `errorGroups` describes the returned records. * - * A refresh running under a skip policy records each row it skipped with - * the input that failed and the error. This lists those records, newest - * job first, plus a summary for any fragment whose per-row detail was - * capped. LanceDB Enterprise only; reading errors needs read - * access to the table, since a message carries the value that failed. - * @param {FunctionErrorsOptions} options Optional filters: `jobId`, - * `column`, and `limit` (server default 10000, cap 100000). - * @returns {Promise} The records, the capped fragments, - * and whether the listing stopped at its limit. * @example * ```ts - * const { records, truncated } = await table.functionErrors({ column: "embedding" }); + * const errors = await table.functionErrors({ column: "embedding" }); + * console.log(errors.records, errors.errorGroups); * ``` */ abstract functionErrors( options?: FunctionErrorsOptions, ): Promise; + /** + * Read current failing inputs, one result per error record. + * Requires a complete LanceDB Enterprise workflow version 1 listing with + * row identities. Throws if a failed row is no longer addressable in the + * table's read snapshot. For materialized views, see the source identities + * on each error record returned by {@link Table#functionErrors}. + */ + async functionErrorRows( + options?: FunctionErrorRowsOptions, + ): Promise { + const { columns, column, jobId, limit } = options ?? {}; + const errors = await this.functionErrors({ column, jobId, limit }); + return readFailedRows(this, errors, columns); + } + + /** + * Start a job to retry exactly the current failures of one Function column. + * Filters apply on the server. Quarantined rows are excluded by default. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async retryFailed( + _column: string, + _options?: RetryFailedOptions, + ): Promise> { + throw new Error("retryFailed is not supported on this table type"); + } + + /** + * Start an upgrade to an existing immutable Function version and choose + * which rows to recompute. New and changed inputs use the new version. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async upgradeColumn( + _column: string, + _options: UpgradeColumnOptions, + ): Promise> { + throw new Error("upgradeColumn is not supported on this table type"); + } + + /** + * Quarantine current failures and return the number of affected rows. + * Set `quarantined: false` to release them for future refreshes. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async quarantineFailed( + _column: string, + _options?: FunctionQuarantineOptions, + ): Promise { + throw new Error("quarantineFailed is not supported on this table type"); + } + + /** + * Read the producing Function version and job for each returned value. + * Check `truncated` before treating the result as a complete listing. + * Requires LanceDB Enterprise Function failure workflow version 1 or later. + */ + async functionProvenance( + _column: string, + _options?: FunctionProvenanceOptions, + ): Promise { + throw new Error("functionProvenance is not supported on this table type"); + } + + /** + * Return exact freshness status for Function-backed output columns. + * + * All results describe one server table version. Omit `column` for every + * Function output. Rows already failed remain visible and do not prevent + * `waitFresh` from completing. A handle pinned to an exact version requests + * that version; a latest handle retains normal read-freshness behavior. + */ + abstract functionColumnStatuses( + column?: string, + ): Promise; + + /** Return exact freshness status for one Function-backed output column. */ + abstract functionColumnStatus(column: string): Promise; + + /** + * Poll until no stale or never-computed rows remain. + * + * Only HTTP 503 with the exact finalization-pending error code is retried; + * every other error propagates. Failed rows do not block completion. + */ + abstract waitFresh( + column: string, + timeoutSeconds?: number, + ): Promise; + /** * Recompute this table's contents from its materialized-view definition. * @@ -729,6 +1174,11 @@ export abstract class Table { abstract refreshMaterializedView( sourceVersion?: number, full?: boolean, + totalCpuMillis?: number, + totalMemoryBytes?: number, + totalGpuCount?: number, + gpuClass?: string, + gpuCount?: number, ): Promise; /** @ignore */ @@ -850,6 +1300,56 @@ export abstract class Table { * @returns {Promise} */ abstract getRTESpec(): Promise; + /** + * Read the stored overrides for a remote Enterprise table. + * + * Overrides configure background behavior such as automatic compaction, + * cleanup, and reindex execution. Keys use the server's snake_case names. + * Returns an empty object when no overrides are set. Local tables are unsupported. + * Custom table implementations inherit a default rejection unless they override + * this method. + */ + async getTableOverrides(): Promise> { + throw new Error("getTableOverrides is not supported on this table type"); + } + + /** + * Recursively merge overrides into a remote Enterprise table's stored overrides. + * + * Fetches the current overrides, merges nested objects locally, then sends the + * complete replacement using REST PUT. Other values replace existing values; + * unrelated fields from the read snapshot are preserved. This read-modify-write + * is not atomic: concurrent edits can be overwritten, even to unrelated fields. + * Coordinate writers when concurrent edits must be preserved. An empty update + * only reads and returns the current overrides. + * + * Unlike this SDK method, CLI `set` and REST PUT replace the overrides object + * without merging. Use {@link Table.resetTableOverrides} to clear all overrides. + * Local tables and custom table implementations without override support reject + * this operation. + * + * @example + * ```ts + * await table.updateTableOverrides({ + * job_types: { compaction: { enabled: false } }, + * }); + * ``` + */ + async updateTableOverrides( + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + overrides: Record, + ): Promise> { + throw new Error("updateTableOverrides is not supported on this table type"); + } + + /** + * Clear a remote Enterprise table's overrides and return an empty object. + * Local tables and custom table implementations without override support reject + * this operation. + */ + async resetTableOverrides(): Promise> { + throw new Error("resetTableOverrides is not supported on this table type"); + } /** * Drain and close any cached RTE shard writers held for this table. * @@ -1007,6 +1507,87 @@ export abstract class Table { * out state and the read_consistency_interval, if any, will apply. */ abstract restore(): Promise; + + /** + * Compare two persisted versions or same-branch tags on an Embedded table. + * + * `fromVersion` is exclusive and `toVersion` is inclusive. Omitting + * `toVersion` uses the version currently visible through this handle, + * including a checked-out version. The endpoints are fixed when the delta is + * created. + * + * Row readers require stable row IDs at both endpoints. Create the table with + * `storageOptions: { new_table_enable_stable_row_ids: "true" }` to enable + * them. `listTransactions()` works without stable row IDs. + * + * Row readers reject ranges containing a Restore, or ranges whose transaction + * history cannot prove they are restore-free. Recompute the checkpoint with a + * full rescan and reinitialize it at the range end version. + * + * LanceDB Enterprise tables reject this operation. + * + * @example + * const delta = await table.delta("baseline"); + * const reader = delta.insertedRows(); + * console.log((await reader.schema()).fields.map((field) => field.name)); + * for await (const batch of reader) { + * console.log(batch.getChild("id")?.toJSON()); + * } + * console.log(await delta.listTransactions()); + */ + async delta( + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + fromVersion: DeltaVersion, + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + toVersion?: DeltaVersion, + ): Promise { + throw new Error("table.delta is only supported on LanceDB Embedded tables"); + } + + /** + * Submit durable remote cleanup through SQL VACUUM and return after acceptance. + * Requires table Ownership and parent Usage. Retention inherits from the table + * then deployment when omitted. Local/historical handles are unsupported. + * Before submission, disable/drain automatic cleanup and prevent other cleanup, + * tag/branch publication and restore until completion, including direct clients. + * Coordination is not enforced by the server. Cancellation cannot undo deletion + * or prove storage I/O stopped. Preview is available without deletion. + * Wait timeout leaves work running; save the ID and reopen with db.openJob(). + * @example + * const job = await table.cleanupAsync({ minAgeSeconds: 604800 }); + * const result = await job.wait({ timeoutMs: 600000 }); + */ + async cleanupAsync(_options?: CleanupOptions): Promise> { + throw new Error("durable cleanup jobs are only supported on remote tables"); + } + + /** Preview version deletion without creating a job. Execution re-evaluates current state. */ + async explainCleanup(_options?: CleanupOptions): Promise { + throw new Error("cleanup previews require LanceDB Enterprise"); + } + + /** + * Submit remote compaction and return its durable job after acceptance. + * + * Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires + * a compatible remote server and table Ownership plus parent Usage. Local and + * historical-version handles are unsupported. Existing optimize() behavior is unchanged. + * Waiting tracks the rewrite itself and returns actual row/file statistics. + * Missing result payloads are errors; older workers can omit file counts. + * Status, progress, events and cancellation reuse the generic HTTP job APIs. + * Reopen with db.openJob(job.id!). A wait timeout does not cancel work. + * + * @example + * const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); + * const result = await job.wait(); + * console.log(result.rowsSucceeded, result.fragmentsRemoved); + */ + async compactAsync( + _options?: CompactionOptions, + ): Promise> { + throw new Error("compaction jobs are only supported on remote tables"); + } + /** * Optimize the on-disk data and indices for better performance. * @@ -1030,6 +1611,9 @@ export abstract class Table { * skipped there instead of being attempted, so this call resolves * successfully, with zeroed pruning statistics, once the compaction job * has been submitted; it does not wait for that job to finish. + * `compactionOptions` can tune the four per-job settings documented in + * {@link CompactionOptions}. Older-server errors are propagated without + * retrying with the settings removed. */ abstract optimize(options?: Partial): Promise; /** @@ -1158,6 +1742,14 @@ export class LocalTable extends Table { } async add(data: Data, options?: Partial): Promise { + if ( + options?.retries !== undefined && + (!Number.isInteger(options.retries) || + options.retries < 0 || + options.retries > 255) + ) { + throw new Error("retries must be an integer between 0 and 255"); + } const mode = options?.mode ?? "append"; const schema = await this.schema(); @@ -1180,6 +1772,7 @@ export class LocalTable extends Table { mode, progress, options?.allowExternalBlobOutsideBases, + options?.retries, ); } @@ -1291,8 +1884,37 @@ export class LocalTable extends Table { await this.inner.prewarmIndex(name); } - async prewarmData(columns?: string[]): Promise { - await this.inner.prewarmData(columns); + async prewarmData(options?: PrewarmDataOptions): Promise; + async prewarmData(columns?: string[]): Promise; + async prewarmData( + columnsOrOptions?: string[] | PrewarmDataOptions, + ): Promise { + await this.prewarmDataAsync( + Array.isArray(columnsOrOptions) + ? { columns: columnsOrOptions } + : columnsOrOptions, + ); + } + + async prewarmDataAsync( + options?: PrewarmDataOptions, + ): Promise> { + return new Job( + await this.inner.prewarmDataAsync( + await toNativePrewarmDataOptions(options), + ), + decodePrewarmDataResult, + ); + } + + async explainPrewarmData( + options?: PrewarmDataOptions, + ): Promise { + return decodePrewarmDataPlan( + await this.inner.explainPrewarmData( + await toNativePrewarmDataOptions(options), + ), + ); } async waitForIndex( @@ -1332,6 +1954,23 @@ export class LocalTable extends Table { return values.map((value) => value ?? null); } + async fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]> { + const rowIds = rowIdsToBigInts(requests.map((request) => request.rowId)); + const ranges = requests.map((request, i) => ({ + rowId: rowIds[i], + offset: request.offset, + length: request.length, + })); + const values = await runWithSignal(options?.signal, (signal) => + this.inner.fetchBlobRanges(column, ranges, signal), + ); + return values.map((value) => value ?? null); + } + async fetchBlobFiles( column: string, rowIds: readonly (bigint | number)[], @@ -1346,6 +1985,19 @@ export class LocalTable extends Table { ); } + async openBlobFile( + descriptor: BlobDescriptor | null, + options?: BlobReadOptions, + ): Promise { + if (descriptor == null) { + return null; + } + const file = await runWithSignal(options?.signal, (signal) => + this.inner.openBlobFile(toNativeBlobDescriptor(descriptor), signal), + ); + return BlobFile.fromNative(file); + } + query(): Query { return new Query(this.inner); } @@ -1477,26 +2129,119 @@ export class LocalTable extends Table { throw new Error("Invalid input type for addColumns"); } - async refreshColumn(column: string): Promise { - return await this.inner.refreshColumn(column); + async refreshColumn( + column: string, + options?: RefreshColumnOptions, + ): Promise { + return await this.inner.refreshColumn(column, options); } - async refreshColumnAsync(column: string): Promise { - return new Job(await this.inner.refreshColumnAsync(column)); + async refreshColumnAsync( + column: string, + options?: RefreshColumnOptions, + ): Promise { + return new Job(await this.inner.refreshColumnAsync(column, options)); } async functionErrors( options?: FunctionErrorsOptions, ): Promise { validateNonNegativeInteger(options?.limit, "limit"); - return await this.inner.functionErrors(options); + return this.inner.functionErrors(options); + } + + override async retryFailed( + column: string, + options?: RetryFailedOptions, + ): Promise> { + const { + errorType, + jobId, + includeQuarantined, + functionVersion, + ...refresh + } = options ?? {}; + const job = await this.inner.refreshColumnAsync(column, refresh, { + retryErrors: true, + retryErrorType: errorType, + retryJobId: jobId, + includeQuarantined, + functionVersion, + recompute: functionVersion === undefined ? undefined : "failed", + }); + return new Job(job, decodeRefreshColumnJobResult); + } + + override async upgradeColumn( + column: string, + options: UpgradeColumnOptions, + ): Promise> { + const { version, recompute = "all", ...refresh } = options; + const job = await this.inner.refreshColumnAsync(column, refresh, { + functionVersion: version, + recompute, + }); + return new Job(job, decodeRefreshColumnJobResult); + } + + override async quarantineFailed( + column: string, + options?: FunctionQuarantineOptions, + ): Promise { + return this.inner.quarantineFunctionErrors(column, options); + } + + override async functionProvenance( + column: string, + options?: FunctionProvenanceOptions, + ): Promise { + validateNonNegativeInteger(options?.limit, "limit"); + return this.inner.functionProvenance(column, options); + } + + async functionColumnStatuses( + column?: string, + ): Promise { + return (await this.inner.functionColumnStatuses( + column, + )) as FunctionColumnStatus[]; + } + + async functionColumnStatus(column: string): Promise { + return (await this.inner.functionColumnStatus( + column, + )) as FunctionColumnStatus; + } + + async waitFresh( + column: string, + timeoutSeconds?: number, + ): Promise { + validateNonNegativeInteger(timeoutSeconds, "timeoutSeconds"); + return (await this.inner.waitForFunctionColumn( + column, + timeoutSeconds, + )) as FunctionColumnStatus; } async refreshMaterializedView( sourceVersion?: number, full?: boolean, + totalCpuMillis?: number, + totalMemoryBytes?: number, + totalGpuCount?: number, + gpuClass?: string, + gpuCount?: number, ): Promise { - return await this.inner.refreshMaterializedView(sourceVersion, full); + return await this.inner.refreshMaterializedView( + sourceVersion, + full, + totalCpuMillis, + totalMemoryBytes, + totalGpuCount, + gpuClass, + gpuCount, + ); } async materializedViewDefinition(): Promise { @@ -1561,6 +2306,20 @@ export class LocalTable extends Table { | undefined; } + async getTableOverrides(): Promise> { + return await this.inner.getTableOverrides(); + } + + async updateTableOverrides( + overrides: Record, + ): Promise> { + return await this.inner.updateTableOverrides(overrides); + } + + async resetTableOverrides(): Promise> { + return await this.inner.resetTableOverrides(); + } + async closeRTEWriters(): Promise { return await this.inner.closeRTEWriters(); } @@ -1598,6 +2357,18 @@ export class LocalTable extends Table { await this.inner.checkoutLatest(); } + async delta( + fromVersion: DeltaVersion, + toVersion?: DeltaVersion, + ): Promise { + return new TableDelta( + await this.inner.delta( + toNativeDeltaRef(fromVersion), + toVersion === undefined ? undefined : toNativeDeltaRef(toVersion), + ), + ); + } + async listVersions(): Promise { return (await this.inner.listVersions()).map((version) => ({ version: version.version, @@ -1622,10 +2393,37 @@ export class LocalTable extends Table { return this.inner.currentBranch() ?? null; } + async compactAsync( + options?: CompactionOptions, + ): Promise> { + validateCompactionOptions(options); + return new Job( + await this.inner.compactAsync(options), + decodeCompactionResult, + ); + } + + async cleanupAsync(options?: CleanupOptions): Promise> { + validateCleanupOptions(options); + return new Job( + await this.inner.cleanupAsync(options?.minAgeSeconds), + decodeCleanupResult, + ); + } + + async explainCleanup(options?: CleanupOptions): Promise { + validateCleanupOptions(options); + return decodeCleanupPlan( + await this.inner.explainCleanup(options?.minAgeSeconds), + ); + } + async optimize(options?: Partial): Promise { + validateCompactionOptions(options?.compactionOptions); return await this.inner.optimize( options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, + options?.compactionOptions, ); } @@ -1826,6 +2624,251 @@ export interface CherryPickResult { mainVersionAfter?: number; } +/** + * Options for creating a branch from a named source. + */ +export interface CreateBranchOptions { + /** + * Tag to fork from. The tag keeps the branch and version it points to. + * Cannot be combined with `fromRef` or `fromVersion`. + */ + fromTag: string; +} + +/** + * A handle for reading changes between two pinned table versions. + * + * Created by {@link Table.delta}. Endpoints are fixed at creation; later writes + * or tag moves do not change this delta. + */ +export class TableDelta { + readonly #inner: NativeTableDelta; + + /** + * Construct a table-delta handle. Internal use only. + * @hidden + */ + constructor(inner: NativeTableDelta) { + this.#inner = inner; + } + + /** The exclusive start version, as an exact u64 bigint. */ + get beginVersion(): bigint { + return this.#inner.beginVersion(); + } + + /** The inclusive end version, as an exact u64 bigint. */ + get endVersion(): bigint { + return this.#inner.endVersion(); + } + + /** Stream rows inserted in `(beginVersion, endVersion]`. */ + insertedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.insertedRows()); + } + + /** Stream rows updated in `(beginVersion, endVersion]`. */ + updatedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.updatedRows()); + } + + /** Stream inserted and updated rows in `(beginVersion, endVersion]`. */ + upsertedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.upsertedRows()); + } + + /** Stream deleted row IDs. Each batch has one `_rowid: uint64` column. */ + deletedRowIds(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.deletedRowIds()); + } + + /** List readable transactions committed in `(beginVersion, endVersion]`. */ + async listTransactions(): Promise { + const transactions = await this.#inner.listTransactions(); + return transactions.map((transaction) => ({ + readVersion: transaction.readVersion, + uuid: transaction.uuid, + operation: transaction.operation, + tag: transaction.tag ?? undefined, + transactionProperties: transaction.transactionProperties ?? undefined, + })); + } +} + +function toNativeDeltaRef(value: DeltaVersion): NativeDeltaRef { + if (typeof value === "string") { + if (value.length === 0) { + throw new Error("delta tag must be a non-empty string"); + } + return { tag: value }; + } + if (typeof value === "bigint") { + if (value <= 0n) { + throw new Error("delta version must be a positive u64 bigint"); + } + return { version: value }; + } + if (!Number.isSafeInteger(value) || value <= 0) { + throw new Error( + "delta version must be a positive safe integer; use bigint for larger versions", + ); + } + return { version: BigInt(value) }; +} + +function tableDeltaReader( + open: () => Promise, +): TableDeltaReader { + return new TableDeltaReaderImpl(open); +} + +class TableDeltaReaderImpl implements TableDeltaReader { + readonly #open: () => Promise; + #setup?: Promise; + #schema?: Schema; + #schemaSetup?: Promise; + #iterator?: AsyncIterator; + #error?: unknown; + #done = false; + #pullQueue: Promise = Promise.resolve(); + + constructor(open: () => Promise) { + this.#open = open; + } + + [Symbol.asyncIterator](): AsyncIterator { + return this; + } + + async schema(): Promise { + if (this.#schema !== undefined) { + return this.#schema; + } + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#schemaSetup === undefined) { + this.#schemaSetup = this.#loadSchema(); + } + return this.#schemaSetup; + } + + async #loadSchema(): Promise { + try { + const native = await this.#getNative(); + const schema = tableFromIPC(await native.schema()).schema; + this.#schema = schema; + return schema; + } catch (error) { + return this.#fail(error); + } + } + + next(): Promise> { + return this.#serialize(() => this.#pull()); + } + + async return(): Promise> { + await this.#serialize(async () => { + this.#done = true; + await this.#release(); + }); + return { done: true, value: undefined }; + } + + async throw(error?: unknown): Promise> { + await this.#serialize(async () => { + this.#done = true; + await this.#release(); + }); + throw error; + } + + async #pull(): Promise> { + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#done) { + return { done: true, value: undefined }; + } + + // Capture the schema before polling the reader's shared native iterator. + await this.schema(); + try { + const result = await this.#getIterator().next(); + if (result.done) { + this.#done = true; + await this.#release(); + } + return result; + } catch (error) { + return this.#fail(error); + } + } + + #getIterator(): AsyncIterator { + if (this.#iterator === undefined) { + this.#iterator = RecordBatchIterator(this.#getNative())[ + Symbol.asyncIterator + ](); + } + return this.#iterator; + } + + async #getNative(): Promise { + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#done) { + throw new Error("table delta reader is already consumed"); + } + if (this.#setup === undefined) { + try { + this.#setup = this.#open(); + } catch (error) { + return this.#fail(error); + } + } + try { + return await this.#setup; + } catch (error) { + return this.#fail(error); + } + } + + async #fail(error: unknown): Promise { + if (this.#error === undefined) { + this.#done = true; + this.#error = error; + await this.#release(); + } + throw this.#error; + } + + async #release(): Promise { + const iterator = this.#iterator; + this.#iterator = undefined; + this.#setup = undefined; + if (iterator?.return !== undefined) { + try { + await iterator.return(); + } catch { + // The native stream already failed or completed; releasing the + // reference is enough. + } + } + } + + #serialize(operation: () => Promise): Promise { + const next = this.#pullQueue.then(operation, operation); + this.#pullQueue = next.then( + () => undefined, + () => undefined, + ); + return next; + } +} + /** * Branch manager for a {@link Table}. * @@ -1848,6 +2891,18 @@ export class Branches { return await this.#inner.list(); } + /** + * Create a branch from a tag and return a handle scoped to it. + * + * @param name Name of the new branch. + * @param options Named source. `fromTag` keeps the tag's branch and version. + * @example + * ```typescript + * const branches = await table.branches(); + * const branch = await branches.create("exp", { fromTag: "baseline" }); + * ``` + */ + async create(name: string, options: CreateBranchOptions): Promise
      ; /** * Create a branch and return a handle scoped to it. * @@ -1859,8 +2914,35 @@ export class Branches { name: string, fromRef?: string, fromVersion?: number, + ): Promise
      ; + async create( + name: string, + fromRefOrOptions?: string | CreateBranchOptions, + fromVersion?: number, ): Promise
      { - return new LocalTable(await this.#inner.create(name, fromRef, fromVersion)); + if (typeof fromRefOrOptions === "object" && fromRefOrOptions !== null) { + // The public options shape only adds `fromTag`. Forward any runtime + // `fromRef`/`fromVersion` fields so the native check remains the single + // authority for rejecting mixed sources before `main` normalization. + const options = fromRefOrOptions as CreateBranchOptions & { + fromRef?: string; + fromVersion?: number; + }; + if (typeof options.fromTag !== "string") { + throw new Error("branch source options must include fromTag"); + } + return new LocalTable( + await this.#inner.create( + name, + options.fromRef, + fromVersion ?? options.fromVersion, + options.fromTag, + ), + ); + } + return new LocalTable( + await this.#inner.create(name, fromRefOrOptions, fromVersion), + ); } /** @@ -1921,3 +3003,40 @@ function rowIdsToBigInts(rowIds: readonly (bigint | number)[]): bigint[] { return BigInt(id); }); } + +function validateCompactionOptions(options?: CompactionOptions): void { + // JavaScript callers can supply extra keys that TypeScript would reject. + // Refuse them before the native binding can silently discard a work limit. + const supported = new Set([ + "targetRowsPerFragment", + "maxSourceRows", + "ioBufferSize", + "batchSize", + ]); + for (const key of Object.keys(options ?? {})) { + if (!supported.has(key)) { + throw new Error(`Unsupported compaction option: ${key}`); + } + } +} + +async function toNativePrewarmDataOptions(options?: PrewarmDataOptions) { + validatePrewarmDataOptions(options); + return options === undefined + ? undefined + : { + ...options, + parameters: + options.parameters === undefined + ? undefined + : await toParameterBuffer(options.parameters), + }; +} + +function validatePrewarmDataOptions(options?: PrewarmDataOptions): void { + for (const key of Object.keys(options ?? {})) { + if (!["columns", "filter", "concurrency", "parameters"].includes(key)) { + throw new Error(`Unsupported data prewarm option: ${key}`); + } + } +} diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 0152622cf..fc6f1a7ea 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.37", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index a96e450c4..41aa1cf3a 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.37", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 606c8c23d..44b9dc419 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.37", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index a84d8f649..48940a19f 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.37", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index fd1223f69..456cc5d97 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.37", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index a1ec2e4b8..f2d77f108 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.37", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 3a1be4350..f7f192b6d 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.37", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 3005c769f..4f89a79e6 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.37", "main": "dist/index.js", "exports": { ".": "./dist/index.js", @@ -102,7 +102,7 @@ "reflect-metadata": "^0.2.2" }, "optionalDependencies": { - "@huggingface/transformers": "3.0.2", + "@huggingface/transformers": "4.3.2", "openai": "4.29.2" }, "peerDependencies": { diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index faf0ad428..df01d672a 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -4,9 +4,6 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false -overrides: - sharp: ^0.35.4 - importers: .: @@ -38,7 +35,7 @@ importers: version: 3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)(@types/node@22.7.4) '@opentelemetry/sdk-metrics': specifier: ^2.10.0 - version: 2.12.0(@opentelemetry/api@1.10.0) + version: 2.12.1(@opentelemetry/api@1.10.0) '@types/axios': specifier: ^0.14.0 version: 0.14.4 @@ -104,8 +101,8 @@ importers: version: 7.18.0(eslint@8.57.1)(typescript@5.5.4) optionalDependencies: '@huggingface/transformers': - specifier: 3.0.2 - version: 3.0.2(@types/node@22.7.4) + specifier: 4.3.2 + version: 4.3.2(@types/node@22.7.4) openai: specifier: 4.29.2 version: 4.29.2 @@ -569,12 +566,15 @@ packages: resolution: {integrity: sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - '@huggingface/jinja@0.3.4': - resolution: {integrity: sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==} + '@huggingface/jinja@0.5.11': + resolution: {integrity: sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ==} engines: {node: '>=18'} - '@huggingface/transformers@3.0.2': - resolution: {integrity: sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==} + '@huggingface/tokenizers@0.2.0': + resolution: {integrity: sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==} + + '@huggingface/transformers@4.3.2': + resolution: {integrity: sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==} '@humanwhocodes/config-array@0.13.0': resolution: {integrity: sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==} @@ -593,160 +593,160 @@ packages: resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} - '@img/sharp-darwin-arm64@0.35.4': - resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==} + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.35.4': - resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-freebsd-wasm32@0.35.4': - resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] - '@img/sharp-libvips-darwin-arm64@1.3.3': - resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==} + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.3.3': - resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.3.3': - resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm@1.3.3': - resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-ppc64@1.3.3': - resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-riscv64@1.3.3': - resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==} + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-s390x@1.3.3': - resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==} + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.3.3': - resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': - resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-x64@1.3.3': - resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-linux-arm64@0.35.4': - resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-linux-arm@0.35.4': - resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-linux-ppc64@0.35.4': - resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-linux-riscv64@0.35.4': - resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==} + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-linux-s390x@0.35.4': - resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==} + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-linux-x64@0.35.4': - resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-linuxmusl-arm64@0.35.4': - resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-linuxmusl-x64@0.35.4': - resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-wasm32@0.35.4': - resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} - '@img/sharp-webcontainers-wasm32@0.35.4': - resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==} + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-arm64@0.35.4': - resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] - '@img/sharp-win32-ia32@0.35.4': - resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==} + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.35.4': - resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] @@ -885,10 +885,6 @@ packages: '@types/node': optional: true - '@isaacs/fs-minipass@4.0.1': - resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} - engines: {node: '>=18.0.0'} - '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} engines: {node: '>=8'} @@ -1403,26 +1399,26 @@ packages: resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} engines: {node: '>=8.0.0'} - '@opentelemetry/core@2.12.0': - resolution: {integrity: sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==} + '@opentelemetry/core@2.12.1': + resolution: {integrity: sha512-3hr6Pj0/G0oVgIGb97IVcw9BjZ6eudonKjrmQxw7JquyU/XmVbJelkmyoU0sT/OvHGkv+r1tcrwv8MbSX7aKHw==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/resources@2.12.0': - resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==} + '@opentelemetry/resources@2.12.1': + resolution: {integrity: sha512-IwrNcuLCvnJAnNLkXxx0Uw+rjBkVW6VGQrhd7PanNf0LavOzkTk9sDAjdqegM7p/VdxefNRrii6d+wBRJfz35g==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-metrics@2.12.0': - resolution: {integrity: sha512-mVMaEHwCUJuY3S4Esn+nT0yQA3qCEGh+SOPJsXygU0Gl453WcsDNjtEa8EfdewMwoLyr1tlofB4fXytVpiXuow==} + '@opentelemetry/sdk-metrics@2.12.1': + resolution: {integrity: sha512-HeSblYhpds4QWliBE7ANCfoa2p3QH83uUxX4vO2qtk6BhIcqP7qDYYT36z3LOXftEBpdfbDStZxv+Cw5mqKX5g==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.9.0 <1.10.0' - '@opentelemetry/semantic-conventions@1.43.0': - resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} + '@opentelemetry/semantic-conventions@1.45.0': + resolution: {integrity: sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw==} engines: {node: '>=14'} '@protobufjs/aspromise@1.1.2': @@ -1489,7 +1485,9 @@ packages: '@smithy/core@3.24.1': resolution: {integrity: sha512-3mT7o4qQyUWttYnVK3A0Z/u3Xha3E81tXn32Tz6vjZiUXhBrkEivpw1hBYfh84iFF9CSzkBU9Y1DJ3Q6RQ231g==} engines: {node: '>=18.0.0'} - deprecated: Deprecated due to bug in browser bundling instructions https://github.com/smithy-lang/smithy-typescript/issues/2025 + deprecated: |- + Deprecated due to a bug in custom logger data redaction. Upgrade to the latest version. If you used a custom logger with this + version, review your logs and rotate any credentials or other secrets. See https://github.com/aws/aws-sdk-js-v3/issues/8393. '@smithy/credential-provider-imds@4.3.1': resolution: {integrity: sha512-0S/acwHnqX4WrjXzhdiDRxsG2s9SC0cpPIK9nZ1R6UOHd+j7uL28+4bHu22urbLk2TVw3fkp6na/+fkUt/pLNQ==} @@ -1805,6 +1803,10 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + adm-zip@0.6.1: + resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==} + engines: {node: '>=14.0'} + agent-base@6.0.2: resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} engines: {node: '>= 6.0.0'} @@ -2001,10 +2003,6 @@ packages: charenc@0.0.2: resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==} - chownr@3.0.0: - resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} - engines: {node: '>=18'} - ci-info@3.9.0: resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} engines: {node: '>=8'} @@ -2108,6 +2106,14 @@ packages: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -2331,9 +2337,6 @@ packages: resolution: {integrity: sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==} engines: {node: ^10.12.0 || >=12.0.0} - flatbuffers@1.12.0: - resolution: {integrity: sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==} - flatbuffers@23.5.26: resolution: {integrity: sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==} @@ -2413,10 +2416,18 @@ packages: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + global-agent@4.1.6: + resolution: {integrity: sha512-V9u791atI/bS7RryfRTK2oixDWo6/RCrIikjwuQ4kADPRZZml1C6LUJXc7y6qRhaAF8geo3bIvE/siAGJCw38A==} + engines: {node: '>=10.0'} + globals@13.24.0: resolution: {integrity: sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==} engines: {node: '>=8'} + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + globby@11.1.0: resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} engines: {node: '>=10'} @@ -2443,6 +2454,9 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -2809,6 +2823,10 @@ packages: resolution: {integrity: sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw==} hasBin: true + matcher@4.0.0: + resolution: {integrity: sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==} + engines: {node: '>=10'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -2870,14 +2888,6 @@ packages: minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - minipass@7.1.3: - resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} - engines: {node: '>=16 || 14 >=14.17'} - - minizlib@3.1.0: - resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} - engines: {node: '>= 18'} - mnemonist@0.38.3: resolution: {integrity: sha512-2K9QYubXx/NAjv4VLq1d1Ly8pWNC5L3BrixtdkyTegXWJIqY+zLNDhhX/A+ZwWt70tB1S8H4BE8FLYEFyNoOBw==} @@ -2923,6 +2933,10 @@ packages: resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} engines: {node: '>=8'} + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + obliterator@1.6.1: resolution: {integrity: sha512-9WXswnqINnnhOG/5SLimUlzuU1hFJUc8zkwyD59Sd+dPOMf05PmnYG/d6Q7HZ+KmgkZJa1PxRso6QdM3sTNHig==} @@ -2939,18 +2953,18 @@ packages: oniguruma-to-es@2.3.0: resolution: {integrity: sha512-bwALDxriqfKGfUufKGGepCzu9x7nJQuoRoAFp4AnwehhC2crqrDIAP/uN2qdlsAvSMpeRC3+Yzhqc7hLmle5+g==} - onnxruntime-common@1.19.2: - resolution: {integrity: sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==} + onnxruntime-common@1.30.0: + resolution: {integrity: sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: - resolution: {integrity: sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: + resolution: {integrity: sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==} - onnxruntime-node@1.19.2: - resolution: {integrity: sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==} + onnxruntime-node@1.30.0: + resolution: {integrity: sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==} os: [win32, darwin, linux] - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: - resolution: {integrity: sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==} + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: + resolution: {integrity: sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==} openai@4.29.2: resolution: {integrity: sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==} @@ -3139,8 +3153,12 @@ packages: engines: {node: '>=10'} hasBin: true - sharp@0.35.4: - resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==} + serialize-error@8.1.0: + resolution: {integrity: sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==} + engines: {node: '>=10'} + + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' @@ -3246,10 +3264,6 @@ packages: resolution: {integrity: sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==} engines: {node: '>=12.17'} - tar@7.5.22: - resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==} - engines: {node: '>=18'} - test-exclude@6.0.0: resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} engines: {node: '>=8'} @@ -3310,6 +3324,9 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tslib@2.9.1: + resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + typanion@3.14.0: resolution: {integrity: sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==} @@ -3481,10 +3498,6 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} - yallist@5.0.0: - resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} - engines: {node: '>=18'} - yaml@2.9.0: resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} engines: {node: '>= 14.6'} @@ -4327,17 +4340,17 @@ snapshots: '@emnapi/core@1.10.0': dependencies: '@emnapi/wasi-threads': 1.2.1 - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@emnapi/runtime@1.11.3': dependencies: - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@emnapi/wasi-threads@1.2.1': dependencies: - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@eslint-community/eslint-utils@4.9.1(eslint@8.57.1)': @@ -4363,15 +4376,19 @@ snapshots: '@eslint/js@8.57.1': {} - '@huggingface/jinja@0.3.4': + '@huggingface/jinja@0.5.11': optional: true - '@huggingface/transformers@3.0.2(@types/node@22.7.4)': + '@huggingface/tokenizers@0.2.0': + optional: true + + '@huggingface/transformers@4.3.2(@types/node@22.7.4)': dependencies: - '@huggingface/jinja': 0.3.4 - onnxruntime-node: 1.19.2 - onnxruntime-web: 1.21.0-dev.20241024-d9ca84ef96 - sharp: 0.35.4(@types/node@22.7.4) + '@huggingface/jinja': 0.5.11 + '@huggingface/tokenizers': 0.2.0 + onnxruntime-node: 1.30.0 + onnxruntime-web: 1.31.0-dev.20260914-8d85527a0 + sharp: 0.35.5(@types/node@22.7.4) transitivePeerDependencies: - '@types/node' optional: true @@ -4391,108 +4408,108 @@ snapshots: '@img/colour@1.1.0': optional: true - '@img/sharp-darwin-arm64@0.35.4': + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.3.3 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.35.4': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.3.3 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-freebsd-wasm32@0.35.4': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-libvips-darwin-arm64@1.3.3': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-libvips-darwin-x64@1.3.3': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm64@1.3.3': + '@img/sharp-libvips-linux-arm64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm@1.3.3': + '@img/sharp-libvips-linux-arm@1.3.4': optional: true - '@img/sharp-libvips-linux-ppc64@1.3.3': + '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true - '@img/sharp-libvips-linux-riscv64@1.3.3': + '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true - '@img/sharp-libvips-linux-s390x@1.3.3': + '@img/sharp-libvips-linux-s390x@1.3.4': optional: true - '@img/sharp-libvips-linux-x64@1.3.3': + '@img/sharp-libvips-linux-x64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-x64@1.3.3': + '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true - '@img/sharp-linux-arm64@0.35.4': + '@img/sharp-linux-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.3.3 + '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true - '@img/sharp-linux-arm@0.35.4': + '@img/sharp-linux-arm@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.3.3 + '@img/sharp-libvips-linux-arm': 1.3.4 optional: true - '@img/sharp-linux-ppc64@0.35.4': + '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.3.3 + '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true - '@img/sharp-linux-riscv64@0.35.4': + '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.3.3 + '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true - '@img/sharp-linux-s390x@0.35.4': + '@img/sharp-linux-s390x@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.3.3 + '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true - '@img/sharp-linux-x64@0.35.4': + '@img/sharp-linux-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.3.3 + '@img/sharp-libvips-linux-x64': 1.3.4 optional: true - '@img/sharp-linuxmusl-arm64@0.35.4': + '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true - '@img/sharp-linuxmusl-x64@0.35.4': + '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true - '@img/sharp-wasm32@0.35.4': + '@img/sharp-wasm32@0.35.5': dependencies: '@emnapi/runtime': 1.11.3 optional: true - '@img/sharp-webcontainers-wasm32@0.35.4': + '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-arm64@0.35.4': + '@img/sharp-win32-arm64@0.35.5': optional: true - '@img/sharp-win32-ia32@0.35.4': + '@img/sharp-win32-ia32@0.35.5': optional: true - '@img/sharp-win32-x64@0.35.4': + '@img/sharp-win32-x64@0.35.5': optional: true '@inquirer/ansi@2.0.5': {} @@ -4614,11 +4631,6 @@ snapshots: optionalDependencies: '@types/node': 22.7.4 - '@isaacs/fs-minipass@4.0.1': - dependencies: - minipass: 7.1.3 - optional: true - '@istanbuljs/load-nyc-config@1.1.0': dependencies: camelcase: 5.3.1 @@ -5155,24 +5167,24 @@ snapshots: '@opentelemetry/api@1.10.0': {} - '@opentelemetry/core@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/core@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/semantic-conventions': 1.45.0 - '@opentelemetry/resources@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/resources@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/core': 2.12.1(@opentelemetry/api@1.10.0) + '@opentelemetry/semantic-conventions': 1.45.0 - '@opentelemetry/sdk-metrics@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/sdk-metrics@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 2.12.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 2.12.1(@opentelemetry/api@1.10.0) - '@opentelemetry/semantic-conventions@1.43.0': {} + '@opentelemetry/semantic-conventions@1.45.0': {} '@protobufjs/aspromise@1.1.2': optional: true @@ -5659,6 +5671,9 @@ snapshots: acorn@8.16.0: {} + adm-zip@0.6.1: + optional: true + agent-base@6.0.2: dependencies: debug: 4.4.3 @@ -5933,9 +5948,6 @@ snapshots: charenc@0.0.2: optional: true - chownr@3.0.0: - optional: true - ci-info@3.9.0: {} cjs-module-lexer@1.4.3: {} @@ -6029,6 +6041,20 @@ snapshots: deepmerge@4.3.1: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + optional: true + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + optional: true + delayed-stream@1.0.0: {} dequal@2.0.3: {} @@ -6274,9 +6300,6 @@ snapshots: keyv: 4.5.4 rimraf: 3.0.2 - flatbuffers@1.12.0: - optional: true - flatbuffers@23.5.26: {} flatbuffers@24.12.23: {} @@ -6354,10 +6377,24 @@ snapshots: once: 1.4.0 path-is-absolute: 1.0.1 + global-agent@4.1.6: + dependencies: + globalthis: 1.0.4 + matcher: 4.0.0 + semver: 7.8.5 + serialize-error: 8.1.0 + optional: true + globals@13.24.0: dependencies: type-fest: 0.20.2 + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + optional: true + globby@11.1.0: dependencies: array-union: 2.1.0 @@ -6387,6 +6424,11 @@ snapshots: has-flag@4.0.0: {} + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + optional: true + has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -6928,6 +6970,11 @@ snapshots: punycode.js: 2.3.1 uc.micro: 2.1.0 + matcher@4.0.0: + dependencies: + escape-string-regexp: 4.0.0 + optional: true + math-intrinsics@1.1.0: {} md5@2.3.0: @@ -6995,14 +7042,6 @@ snapshots: minimist@1.2.8: {} - minipass@7.1.3: - optional: true - - minizlib@3.1.0: - dependencies: - minipass: 7.1.3 - optional: true - mnemonist@0.38.3: dependencies: obliterator: 1.6.1 @@ -7033,6 +7072,9 @@ snapshots: dependencies: path-key: 3.1.1 + object-keys@1.1.1: + optional: true + obliterator@1.6.1: {} obug@2.1.1: {} @@ -7051,24 +7093,25 @@ snapshots: regex: 5.1.1 regex-recursion: 5.1.1 - onnxruntime-common@1.19.2: + onnxruntime-common@1.30.0: optional: true - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: optional: true - onnxruntime-node@1.19.2: + onnxruntime-node@1.30.0: dependencies: - onnxruntime-common: 1.19.2 - tar: 7.5.22 + adm-zip: 0.6.1 + global-agent: 4.1.6 + onnxruntime-common: 1.30.0 optional: true - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: dependencies: - flatbuffers: 1.12.0 + flatbuffers: 25.9.23 guid-typescript: 1.0.9 long: 5.3.2 - onnxruntime-common: 1.20.0-dev.20241016-2b8fc5529b + onnxruntime-common: 1.31.0-dev.20260911-2a43ec07e platform: 1.3.6 protobufjs: 7.6.5 optional: true @@ -7247,37 +7290,42 @@ snapshots: semver@7.8.5: {} - sharp@0.35.4(@types/node@22.7.4): + serialize-error@8.1.0: + dependencies: + type-fest: 0.20.2 + optional: true + + sharp@0.35.5(@types/node@22.7.4): dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 semver: 7.8.5 optionalDependencies: - '@img/sharp-darwin-arm64': 0.35.4 - '@img/sharp-darwin-x64': 0.35.4 - '@img/sharp-freebsd-wasm32': 0.35.4 - '@img/sharp-libvips-darwin-arm64': 1.3.3 - '@img/sharp-libvips-darwin-x64': 1.3.3 - '@img/sharp-libvips-linux-arm': 1.3.3 - '@img/sharp-libvips-linux-arm64': 1.3.3 - '@img/sharp-libvips-linux-ppc64': 1.3.3 - '@img/sharp-libvips-linux-riscv64': 1.3.3 - '@img/sharp-libvips-linux-s390x': 1.3.3 - '@img/sharp-libvips-linux-x64': 1.3.3 - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 - '@img/sharp-linux-arm': 0.35.4 - '@img/sharp-linux-arm64': 0.35.4 - '@img/sharp-linux-ppc64': 0.35.4 - '@img/sharp-linux-riscv64': 0.35.4 - '@img/sharp-linux-s390x': 0.35.4 - '@img/sharp-linux-x64': 0.35.4 - '@img/sharp-linuxmusl-arm64': 0.35.4 - '@img/sharp-linuxmusl-x64': 0.35.4 - '@img/sharp-webcontainers-wasm32': 0.35.4 - '@img/sharp-win32-arm64': 0.35.4 - '@img/sharp-win32-ia32': 0.35.4 - '@img/sharp-win32-x64': 0.35.4 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 '@types/node': 22.7.4 optional: true @@ -7375,15 +7423,6 @@ snapshots: array-back: 6.2.3 wordwrapjs: 5.1.1 - tar@7.5.22: - dependencies: - '@isaacs/fs-minipass': 4.0.1 - chownr: 3.0.0 - minipass: 7.1.3 - minizlib: 3.1.0 - yallist: 5.0.0 - optional: true - test-exclude@6.0.0: dependencies: '@istanbuljs/schema': 0.1.6 @@ -7431,6 +7470,9 @@ snapshots: tslib@2.8.1: {} + tslib@2.9.1: + optional: true + typanion@3.14.0: {} type-check@0.4.0: @@ -7588,9 +7630,6 @@ snapshots: yallist@3.1.1: {} - yallist@5.0.0: - optional: true - yaml@2.9.0: {} yargs-parser@21.1.1: {} diff --git a/nodejs/pnpm-workspace.yaml b/nodejs/pnpm-workspace.yaml index b6be57977..222b3fb1c 100644 --- a/nodejs/pnpm-workspace.yaml +++ b/nodejs/pnpm-workspace.yaml @@ -47,10 +47,3 @@ minimumReleaseAgeExclude: - js-yaml@4.3.1 - tar@7.5.21 - '@opentelemetry/core@2.8.0' - -# @huggingface/transformers pins sharp ^0.33.5 and no released version has moved -# past ^0.34.5, all of which inherit the libvips CVEs in GHSA-f88m-g3jw-g9cj. -# Force the patched line. sharp is only reached by transformers' image pipeline, -# which LanceDB's text embedding function never uses. -overrides: - sharp: ^0.35.4 diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs index 59cf61af6..b8f563103 100644 --- a/nodejs/src/blob.rs +++ b/nodejs/src/blob.rs @@ -8,19 +8,91 @@ use std::sync::atomic::{AtomicBool, Ordering}; use arrow_array::{Array, LargeBinaryArray}; use futures::future::abortable; -use lancedb::blob::BlobFile as LanceBlobFile; +use lancedb::blob::{ + BlobDescriptor as LanceBlobDescriptor, BlobDescriptorSource as LanceBlobDescriptorSource, + BlobFile as LanceBlobFile, +}; use napi::Env; use napi::bindgen_prelude::*; use napi_derive::napi; use crate::error::convert_error; +#[napi(object)] +pub struct BlobDescriptorInputSource { + pub uri: String, + pub version: BigInt, + pub committed_at_micros: BigInt, + pub branch: Option, + pub column: String, + pub row_reference: BigInt, + pub row_is_address: bool, +} + +#[napi(object)] +pub struct BlobDescriptorInput { + pub kind: u32, + pub position: BigInt, + pub size: BigInt, + pub blob_id: u32, + pub blob_uri: String, + pub source: BlobDescriptorInputSource, +} + +impl BlobDescriptorInput { + pub(crate) fn into_descriptor(self) -> napi::Result { + Ok(LanceBlobDescriptor { + kind: u8::try_from(self.kind).map_err(|_| { + napi::Error::from_reason("blob descriptor kind must be between 0 and 255") + })?, + position: parse_u64(self.position, "blob descriptor position")?, + size: parse_u64(self.size, "blob descriptor size")?, + blob_id: self.blob_id, + blob_uri: self.blob_uri, + source: LanceBlobDescriptorSource { + uri: self.source.uri, + version: parse_u64(self.source.version, "blob descriptor source version")?, + committed_at_micros: parse_u64( + self.source.committed_at_micros, + "blob descriptor source committed_at_micros", + )?, + branch: self.source.branch, + column: self.source.column, + row_reference: parse_u64( + self.source.row_reference, + "blob descriptor source row_reference", + )?, + row_is_address: self.source.row_is_address, + }, + }) + } +} + #[napi(object)] pub struct BlobRange { pub start: BigInt, pub end: BigInt, } +#[napi(object)] +pub struct BlobRangeRequest { + pub row_id: BigInt, + pub offset: BigInt, + pub length: BigInt, +} + +impl BlobRangeRequest { + pub(crate) fn parse(self) -> napi::Result { + let row_id = parse_u64(self.row_id, "row id")?; + let offset = parse_u64(self.offset, "offset")?; + let length = parse_u64(self.length, "length")?; + offset + .checked_add(length) + .ok_or_else(|| napi::Error::from_reason("blob range offset + length overflows u64"))?; + Ok(lancedb::blob::BlobRangeRequest::new(row_id, offset, length)) + } +} + #[napi] pub struct BlobFile { inner: Arc, @@ -205,14 +277,25 @@ pub fn parse_row_ids(row_ids: Vec) -> napi::Result> { .collect() } -pub fn copy_blob_buffers(array: LargeBinaryArray) -> Vec> { - (0..array.len()) - .map(|i| { - if array.is_null(i) { - None - } else { - Some(Buffer::from(array.value(i).to_vec())) - } - }) - .collect() +pub fn copy_blob_buffers(array: LargeBinaryArray) -> napi::Result>> { + let allocation_error = + |error| napi::Error::from_reason(format!("cannot allocate blob result: {error}")); + let mut result = Vec::new(); + result + .try_reserve_exact(array.len()) + .map_err(allocation_error)?; + for value in array.iter() { + let buffer = value + .map(|value| { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(value.len()) + .map_err(allocation_error)?; + bytes.extend_from_slice(value); + Ok::<_, napi::Error>(Buffer::from(bytes)) + }) + .transpose()?; + result.push(buffer); + } + Ok(result) } diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 914f9e4c9..7537a8bcd 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -303,6 +303,7 @@ impl Connection { } #[napi(catch_unwind)] + #[allow(clippy::too_many_arguments)] pub async fn create_materialized_view( &self, name: String, @@ -311,6 +312,11 @@ impl Connection { filter: Option, limit: Option, with_no_data: bool, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> napi::Result
      { let mut builder = self.get_inner()?.create_materialized_view(name, source); if let Some(projections) = projections { @@ -331,6 +337,45 @@ impl Connection { .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer"))?; builder = builder.limit(limit); } + const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + for (name, value, maximum, minimum) in [ + ("total_cpu_millis", total_cpu_millis, MAX_SAFE_INTEGER, 1.0), + ( + "total_memory_bytes", + total_memory_bytes, + MAX_SAFE_INTEGER, + 1.0, + ), + ("total_gpu_count", total_gpu_count, u32::MAX as f64, 0.0), + ] { + if let Some(value) = value { + if !value.is_finite() || value.fract() != 0.0 || value < minimum || value > maximum + { + return Err(napi::Error::from_reason(format!( + "{name} must be an integer between {minimum} and {maximum}" + ))); + } + builder = match name { + "total_cpu_millis" => builder.total_cpu_millis(value as u64), + "total_memory_bytes" => builder.total_memory_bytes(value as u64), + _ => builder.total_gpu_count(value as u32), + }; + } + } + if let Some(class) = gpu_class { + builder = builder.gpu_class(class); + } + if let Some(count) = gpu_count { + if !count.is_finite() + || count.fract() != 0.0 + || !(1.0..=u32::MAX as f64).contains(&count) + { + return Err(napi::Error::from_reason( + "gpuCount must be an integer between 1 and 4294967295", + )); + } + builder = builder.gpu_count(count as u32); + } builder = builder.with_no_data(with_no_data); let view = builder.execute().await.default_error()?; Ok(Table::new(view.table().clone())) @@ -567,7 +612,24 @@ impl Connection { #[napi(catch_unwind)] pub async fn open_job(&self, job_id: String) -> napi::Result { let job = self.get_inner()?.open_job(&job_id).await.default_error()?; - Ok(crate::job::Job::new(job)) + if job.job_type().as_deref() == Some("prewarm_page_cache") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) + } else if job.job_type().as_deref() == Some("cleanup") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) + } else if job.job_type().as_deref() == Some("compact") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) + } else { + Ok(crate::job::Job::new(job)) + } } /// List server-side jobs across the database's tables. diff --git a/nodejs/src/index.rs b/nodejs/src/index.rs index 39aa6f8b8..638d4856f 100644 --- a/nodejs/src/index.rs +++ b/nodejs/src/index.rs @@ -4,7 +4,9 @@ use std::sync::Mutex; use lancedb::index::Index as LanceDbIndex; -use lancedb::index::scalar::{BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder}; +use lancedb::index::scalar::{ + BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder, PluginIndexBuilder, RTreeIndexBuilder, +}; use lancedb::index::vector::{ IvfFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder, IvfRqIndexBuilder, @@ -226,6 +228,29 @@ impl Index { } } + /// `params_json`, if set, must be a string holding a JSON object. + #[napi(factory)] + pub fn plugin(index_type: String, params_json: Option) -> napi::Result { + let mut builder = PluginIndexBuilder::new(index_type).default_error()?; + if let Some(params_json) = params_json { + builder = builder.params_json(params_json).default_error()?; + } + Ok(Self { + inner: Mutex::new(Some(LanceDbIndex::Plugin(builder))), + }) + } + + #[napi(factory)] + pub fn rtree(page_size: Option) -> napi::Result { + let mut builder = RTreeIndexBuilder::default(); + if let Some(page_size) = page_size { + builder = builder.page_size(page_size).default_error()?; + } + Ok(Self { + inner: Mutex::new(Some(LanceDbIndex::RTree(builder))), + }) + } + #[napi(factory)] #[allow(clippy::too_many_arguments)] pub fn fts( diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index b8b2d9e94..b76793717 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -1,10 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use std::sync::Arc; +use std::{sync::Arc, time::Duration}; use arrow_array::RecordBatch; -use lancedb::job::JobEventsRequest; +use lancedb::job::{ + FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions, JobEventsRequest, + JobWaitOptions, +}; use napi::bindgen_prelude::Buffer; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; @@ -14,10 +17,22 @@ use crate::error::NapiErrorExt; type JobProgressFn = ThreadsafeFunction; +const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + +fn profile_integer(value: f64, name: &str) -> napi::Result { + if !value.is_finite() || value.fract() != 0.0 || !(0.0..=MAX_SAFE_INTEGER).contains(&value) { + return Err(napi::Error::new( + napi::Status::InvalidArg, + format!("{name} must be a nonnegative safe integer"), + )); + } + Ok(value as u64) +} + /// A handle to an operation that may still be running. #[napi] pub struct Job { - inner: Arc, + inner: Arc, String>>>, } impl Job { @@ -26,7 +41,19 @@ impl Job { T: Clone + Send + Sync + 'static, { Self { - inner: Arc::new(inner.map(|_| ())), + inner: Arc::new(inner.map(|_| Ok(None))), + } + } + pub(crate) fn new_typed(inner: lancedb::Job) -> Self + where + T: Clone + serde::Serialize + Send + Sync + 'static, + { + Self { + inner: Arc::new(inner.map(|result| { + serde_json::to_value(result) + .map(Some) + .map_err(|error| format!("failed to serialize typed job result: {error}")) + })), } } } @@ -40,8 +67,47 @@ impl Job { self.inner.id().map(str::to_string) } - /// The operation's current lifecycle state: "running", "finished", - /// "failed", or "cancelled". + #[napi(getter)] + pub fn job_id(&self) -> Option { + self.inner.job_id() + } + + #[napi(getter)] + pub fn operation_id(&self) -> Option { + self.inner.operation_id() + } + + #[napi(getter)] + pub fn attempt(&self) -> Option { + self.inner.attempt() + } + + #[napi(getter)] + pub fn retry_of(&self) -> Option { + self.inner.retry_of() + } + + #[napi(getter)] + pub fn lifecycle_state(&self) -> Option { + self.inner + .lifecycle_state() + .map(|state| state.as_str().to_string()) + } + + #[napi(getter)] + pub fn source_table_version(&self) -> Option { + self.inner + .source_table_version() + .map(|version| version as f64) + } + + #[napi(getter)] + pub fn execution_epoch(&self) -> Option { + self.inner.execution_epoch() + } + + /// The current status, usually "running", "finished", "failed", or "cancelled". + /// A Function refresh waiting for execution workers reports "waiting_for_capacity". /// /// A point snapshot; unlike {@link Job.wait} it does not block or reject /// on a terminal failure state. States a newer server reports that this @@ -67,22 +133,55 @@ impl Job { /// backend poller without starting another polling loop. #[napi( catch_unwind, - ts_args_type = "progressCallback?: (progress: Record) => void" + ts_args_type = "progressCallback?: (progress: Record) => void, timeoutMs?: number" )] - pub async fn wait(&self, progress_callback: Option) -> napi::Result<()> { - if let Some(progress_callback) = progress_callback { - self.inner - .wait_with_progress(move |description| { - progress_callback.call( - description.progress_snapshot(), - ThreadsafeFunctionCallMode::NonBlocking, - ); - }) - .await - .default_error() - } else { - self.inner.wait().await.default_error() + pub async fn wait( + &self, + progress_callback: Option, + timeout_ms: Option, + ) -> napi::Result<()> { + self.wait_result(progress_callback, timeout_ms) + .await + .map(|_| ()) + } + + /// The typed terminal value used by result-returning SDK operations. + #[napi( + catch_unwind, + ts_args_type = "progressCallback?: (progress: Record) => void, timeoutMs?: number" + )] + pub async fn wait_result( + &self, + progress_callback: Option, + timeout_ms: Option, + ) -> napi::Result> { + let mut options = JobWaitOptions::new(); + if let Some(timeout_ms) = timeout_ms { + if !timeout_ms.is_finite() + || timeout_ms.fract() != 0.0 + || !(0.0..=MAX_SAFE_INTEGER).contains(&timeout_ms) + { + return Err(napi::Error::new( + napi::Status::InvalidArg, + "timeoutMs must be a nonnegative safe integer", + )); + } + options = options.timeout(Duration::from_millis(timeout_ms as u64)); } + if let Some(progress_callback) = progress_callback { + options = options.progress(move |description| { + progress_callback.call( + description.progress_snapshot(), + ThreadsafeFunctionCallMode::NonBlocking, + ); + }); + } + let result = self + .inner + .wait_with_options(options) + .await + .default_error()?; + result.map_err(napi::Error::from_reason) } /// Request cancellation. Cancelling a finished operation is a no-op. @@ -91,6 +190,13 @@ impl Job { self.inner.cancel().await.default_error() } + #[napi(catch_unwind)] + pub async fn retry(&self) -> napi::Result { + Ok(Self { + inner: Arc::new(self.inner.retry().await.default_error()?), + }) + } + /// Ask the backend for this job's current state, and for a server-side job /// its full record, then cache it for the getters below. /// @@ -138,20 +244,103 @@ impl Job { /// Why the job failed, when it failed and the server reports a reason. #[napi(getter)] pub fn failure(&self) -> Option { - self.inner.failure().map(|failure| JobFailureInfo { - phase: failure.phase, - message: failure.message, - retryable: failure.retryable, - }) + self.inner.failure().map(Into::into) + } + + #[napi(catch_unwind)] + pub async fn capture_profile( + &self, + worker_id: String, + kind: String, + duration_seconds: Option, + session_slot: Option, + ) -> napi::Result { + let kind: FunctionProfileKind = + serde_json::from_value(serde_json::json!(kind)).map_err(|_| { + napi::Error::new(napi::Status::InvalidArg, "kind must be cpu, memory or gpu") + })?; + let mut options = FunctionProfileOptions::new(kind); + if let Some(slot) = session_slot { + options = options.session_slot(profile_integer(slot, "sessionSlot")? as usize); + } + if let Some(seconds) = duration_seconds { + let duration = Duration::try_from_secs_f64(seconds).map_err(|_| { + napi::Error::new( + napi::Status::InvalidArg, + "durationSeconds must be finite and nonnegative", + ) + })?; + options = options.duration(duration); + } + let profile = self + .inner + .capture_profile(worker_id, options) + .await + .default_error()?; + serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string())) + } + + #[napi(catch_unwind)] + pub async fn profile_status(&self, profile_id: String) -> napi::Result { + let profile = self + .inner + .profile_status(profile_id) + .await + .default_error()?; + serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string())) + } + + #[napi(catch_unwind)] + pub async fn wait_for_profile( + &self, + profile_id: String, + timeout_ms: Option, + poll_interval_ms: Option, + ) -> napi::Result { + let mut options = FunctionProfileWaitOptions::new(); + if let Some(ms) = timeout_ms { + options = options.timeout(Duration::from_millis(profile_integer(ms, "timeoutMs")?)); + } + if let Some(ms) = poll_interval_ms { + options = options.poll_interval(Duration::from_millis(profile_integer( + ms, + "pollIntervalMs", + )?)); + } + let profile = self + .inner + .wait_for_profile(profile_id, options) + .await + .default_error()?; + serde_json::to_string(&profile).map_err(|error| napi::Error::from_reason(error.to_string())) + } + + #[napi(catch_unwind)] + pub async fn profile_artifact(&self, profile_id: String) -> napi::Result { + Ok(self + .inner + .profile_artifact(profile_id) + .await + .default_error()? + .to_string()) } /// This job's recorded lifecycle events, as an Arrow IPC stream buffer. /// The TypeScript wrapper turns it into an Arrow table. #[napi(catch_unwind)] - pub async fn events(&self, limit: Option, filter: Option) -> napi::Result { + pub async fn events( + &self, + limit: Option, + filter: Option, + page_token: Option, + ) -> napi::Result { let batches = self .inner - .events(JobEventsRequest { limit, filter }) + .events(JobEventsRequest { + limit, + filter, + page_token, + }) .await .default_error()?; batches_to_ipc_buffer(&batches) @@ -191,6 +380,18 @@ pub struct JobInfo { pub state: String, /// When the job was created, in milliseconds since the epoch. pub created_at_millis: i64, + /// Terminal timestamp in milliseconds since the epoch, when known. + pub completed_at_millis: Option, + /// Creation-to-completion wall time, including queueing and pauses. + pub duration_millis: Option, + /// Affected columns; empty when unavailable or not column-scoped. + pub columns: Vec, + /// Pinned Function catalog name, with namespace segments joined by `$`. + pub function_name: Option, + /// Pinned Function version, when known. + pub function_version: Option, + /// Durable failure summary, when available. + pub failure: Option, /// Structured lifecycle, queue, pause, and job-type-specific progress. #[napi(ts_type = "Record")] pub progress: serde_json::Value, @@ -207,6 +408,12 @@ impl From for JobInfo { job_type: info.job_type, state: info.state, created_at_millis: info.created_at_millis, + completed_at_millis: info.completed_at_millis, + duration_millis: info.duration_millis, + columns: info.columns, + function_name: info.function_name, + function_version: info.function_version, + failure: info.failure.map(Into::into), progress, paused: info.paused, } @@ -215,8 +422,25 @@ impl From for JobInfo { /// The server's account of why a job failed. #[napi(object)] +#[derive(Clone, Debug)] pub struct JobFailureInfo { pub phase: Option, pub message: Option, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub retryable: Option, + /// Isolated SQL job that raised this failure, when supplied by the server. + pub sql_job_id: Option, +} + +impl From for JobFailureInfo { + fn from(failure: lancedb::error::JobFailure) -> Self { + Self { + phase: failure.phase, + message: failure.message, + traceback: failure.traceback, + retryable: failure.retryable, + sql_job_id: failure.sql_job_id, + } + } } diff --git a/nodejs/src/merge.rs b/nodejs/src/merge.rs index ccff2a689..86901c04f 100644 --- a/nodejs/src/merge.rs +++ b/nodejs/src/merge.rs @@ -65,12 +65,17 @@ impl NativeMergeInsertBuilder { } #[napi(catch_unwind)] - pub async fn execute(&self, buf: Buffer) -> napi::Result { + pub async fn execute(&self, buf: Buffer, retries: Option) -> napi::Result { let data = ipc_file_to_batches(buf.to_vec()).map_err(|e| { napi::Error::from_reason(format!("Failed to read IPC file: {}", convert_error(&e))) })?; - let this = self.clone(); + let mut this = self.clone(); + if let Some(retries) = retries { + let retries = u8::try_from(retries) + .map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?; + this.inner.retries(retries); + } let res = this.inner.execute(data).await.map_err(|e| { napi::Error::from_reason(format!( diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 9c9fd5156..536be3cd5 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -2,27 +2,185 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::collections::HashMap; +use std::sync::Arc; use chrono::{DateTime, Utc}; use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; use lancedb::table::{ - AddDataMode, ColumnAlteration as LanceColumnAlteration, + AddDataMode, ColumnAlteration as LanceColumnAlteration, DeltaRef as LanceDbDeltaRef, FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken, - NewColumnTransform, Ref, Table as LanceDbTable, + FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig, + FunctionRefreshPodResources as LanceFunctionRefreshPodResources, NewColumnTransform, Ref, + Table as LanceDbTable, TableDelta as LanceDbTableDelta, }; use napi::Env; use napi::bindgen_prelude::*; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; -use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable}; -use crate::error::NapiErrorExt; +use crate::blob::{ + BlobDescriptorInput, BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, + spawn_abortable, +}; +use crate::error::{NapiErrorExt, convert_error}; use crate::index::Index; +use crate::iterator::RecordBatchIterator; +use crate::job::JobFailureInfo; use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; use crate::util::schema_to_buffer; +/// Settings for durable data-cache prewarm submission. +#[napi(object)] +pub struct PrewarmDataOptions { + pub columns: Option>, + pub filter: Option, + pub concurrency: Option, + pub parameters: Option, +} + +impl PrewarmDataOptions { + fn into_options(self) -> napi::Result { + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(self.columns.unwrap_or_default()); + options.filter = self.filter; + if let Some(parameters) = self.parameters { + let mut batches = ipc_file_to_batches(parameters.to_vec()) + .and_then(|reader| { + reader + .collect::, _>>() + .map_err(Into::into) + }) + .map_err(|error| napi::Error::from_reason(error.to_string()))?; + if batches.len() != 1 || batches[0].num_rows() != 1 { + return Err(napi::Error::from_reason( + "prewarm parameters must contain one row in one batch", + )); + } + options.parameters = Some(batches.remove(0)); + } + if let Some(value) = self.concurrency { + if !value.is_finite() || value.fract() != 0.0 || value < 1.0 || value > u32::MAX as f64 + { + return Err(napi::Error::from_reason( + "concurrency must be an integer between 1 and 4294967295", + )); + } + options.concurrency = Some(value as u32); + } + Ok(options) + } +} + +/// Per-invocation file-compaction settings. All numbers must be safe integers. +#[napi(object)] +pub struct CompactionOptions { + pub target_rows_per_fragment: Option, + pub max_source_rows: Option, + pub io_buffer_size: Option, + pub batch_size: Option, +} + +impl CompactionOptions { + fn into_overrides(self) -> napi::Result { + const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; + fn integer( + value: Option, + name: &str, + max: u64, + allow_zero: bool, + ) -> napi::Result> { + let Some(value) = value else { + return Ok(None); + }; + let min = if allow_zero { 0 } else { 1 }; + let max = max.min(MAX_SAFE_INTEGER); + if !value.is_finite() + || value.fract() != 0.0 + || value < min as f64 + || value > max as f64 + { + return Err(napi::Error::from_reason(format!( + "{name} must be a safe integer between {min} and {max}" + ))); + } + Ok(Some(value as u64)) + } + let mut options = lancedb::table::optimize::CompactionOverrides::default(); + if let Some(target) = integer( + self.target_rows_per_fragment, + "targetRowsPerFragment", + u32::MAX as u64, + false, + )? { + options.target_rows_per_fragment = Some(target as usize); + } + options.max_source_rows = integer( + self.max_source_rows, + "maxSourceRows", + usize::MAX as u64, + false, + )? + .map(|v| v as usize); + options.io_buffer_size = integer(self.io_buffer_size, "ioBufferSize", u64::MAX, true)?; + options.batch_size = + integer(self.batch_size, "batchSize", u32::MAX as u64, false)?.map(|v| v as usize); + Ok(options) + } +} + +/// One endpoint of a table delta: a positive version or a same-branch tag. +#[napi(object)] +pub struct DeltaRef { + /// A persisted version, expressed as a positive lossless u64 bigint. + pub version: Option, + /// A tag on the table handle's current branch. + pub tag: Option, +} + +impl DeltaRef { + fn into_delta_ref(self) -> napi::Result { + match (self.version, self.tag) { + (Some(version), None) => { + let (negative, value, lossless) = version.get_u64(); + if negative || !lossless { + return Err(napi::Error::from_reason( + "delta version must be a positive lossless u64 bigint", + )); + } + if value == 0 { + return Err(napi::Error::from_reason( + "delta version must be greater than zero", + )); + } + Ok(LanceDbDeltaRef::Version(value)) + } + (None, Some(tag)) => { + if tag.is_empty() { + return Err(napi::Error::from_reason( + "delta tag must be a non-empty string", + )); + } + Ok(LanceDbDeltaRef::Tag(tag)) + } + _ => Err(napi::Error::from_reason( + "delta reference must contain exactly one of version or tag", + )), + } + } +} + +/// A committed transaction in a table delta range. +#[napi(object)] +pub struct TableDeltaTransaction { + pub read_version: BigInt, + pub uuid: String, + pub operation: String, + pub tag: Option, + pub transaction_properties: Option>, +} + #[napi] pub struct Table { // We keep a duplicate of the table name so we can use it for error @@ -75,7 +233,7 @@ impl Table { #[napi( catch_unwind, - ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean" + ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean, retries?: number" )] pub async fn add( &self, @@ -83,6 +241,7 @@ impl Table { mode: String, progress_callback: Option, allow_external_blob_outside_bases: Option, + retries: Option, ) -> napi::Result { let batches = ipc_file_to_batches(buf.to_vec()) .map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?; @@ -98,6 +257,11 @@ impl Table { }) .collect::>>()?; let mut op = self.inner_ref()?.add(batches); + if let Some(retries) = retries { + let retries = u8::try_from(retries) + .map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?; + op = op.retries(retries); + } op = if mode == "append" { op.mode(AddDataMode::Append) @@ -231,6 +395,40 @@ impl Table { .default_error() } + #[napi(catch_unwind)] + pub async fn prewarm_data_async( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(PrewarmDataOptions::into_options) + .transpose()? + .unwrap_or_default(); + let job = self + .inner_ref()? + .prewarm_data_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + + #[napi(catch_unwind)] + pub async fn explain_prewarm_data( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(PrewarmDataOptions::into_options) + .transpose()? + .unwrap_or_default(); + let plan = self + .inner_ref()? + .explain_prewarm_data(options) + .await + .default_error()?; + serde_json::to_value(plan).map_err(|error| napi::Error::from_reason(error.to_string())) + } + #[napi(catch_unwind)] pub async fn wait_for_index(&self, index_names: Vec, timeout_s: i64) -> Result<()> { let timeout = std::time::Duration::from_secs(timeout_s.try_into().unwrap()); @@ -284,6 +482,31 @@ impl Table { Ok(Query::new(self.inner_ref()?.query())) } + /// Whether this handle reads an in-process dataset. + #[napi] + pub fn is_native(&self) -> napi::Result { + Ok(self.inner_ref()?.as_native().is_some()) + } + + /// Constrain deferred blob reads by the producing query response. + #[napi(catch_unwind)] + pub async fn query_snapshot_with_identity( + &self, + version: String, + identity: String, + ) -> napi::Result { + // Keep u64 query versions exact across the JavaScript boundary. + let version = version + .parse::() + .map_err(|_| napi::Error::from_reason("Invalid query snapshot version"))?; + let snapshot = self + .inner_ref()? + .query_snapshot_with_identity(version, &identity) + .await + .default_error()?; + Ok(Self::new(snapshot)) + } + /// Return a read-only table handle pinned to the current query revision. #[napi(catch_unwind)] pub async fn query_snapshot(&self) -> napi::Result { @@ -355,7 +578,32 @@ impl Table { .fetch_blobs(column.as_str(), &row_ids) .await .default_error()?; - Ok(copy_blob_buffers(array)) + copy_blob_buffers(array) + }) + } + + #[napi(catch_unwind)] + pub fn fetch_blob_ranges<'env>( + &self, + env: &'env Env, + column: String, + requests: Vec, + signal: Option, + ) -> napi::Result>>> { + let mut ranges = Vec::new(); + ranges.try_reserve_exact(requests.len()).map_err(|error| { + napi::Error::from_reason(format!("cannot allocate blob range requests: {error}")) + })?; + for request in requests { + ranges.push(request.parse()?); + } + let table = self.inner_ref()?.clone(); + spawn_abortable(env, signal, async move { + let array = table + .fetch_blob_ranges(column.as_str(), ranges) + .await + .default_error()?; + copy_blob_buffers(array) }) } @@ -381,6 +629,21 @@ impl Table { }) } + #[napi(catch_unwind)] + pub fn open_blob_file<'env>( + &self, + env: &'env Env, + descriptor: BlobDescriptorInput, + signal: Option, + ) -> napi::Result> { + let descriptor = descriptor.into_descriptor()?; + let table = self.inner_ref()?.clone(); + spawn_abortable(env, signal, async move { + let file = table.open_blob_file(&descriptor).await.default_error()?; + Ok(BlobFile::new(file)) + }) + } + #[napi(catch_unwind)] pub fn vector_search(&self, vector: Float32Array) -> napi::Result { self.query()?.nearest_to(vector) @@ -421,23 +684,43 @@ impl Table { } #[napi(catch_unwind)] - pub async fn refresh_column(&self, column: String) -> napi::Result { + pub async fn refresh_column( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default().try_into()?; let res = self .inner_ref()? - .refresh_column(column) + .refresh_column_with_options(column, options) .await .default_error()?; Ok(res.into()) } #[napi(catch_unwind)] - pub async fn refresh_column_async(&self, column: String) -> napi::Result { + pub async fn refresh_column_async( + &self, + column: String, + options: Option, + recovery: Option, + ) -> napi::Result { + let mut options: lancedb::table::RefreshColumnOptions = + options.unwrap_or_default().try_into()?; + let typed_result = recovery.is_some(); + if let Some(recovery) = recovery { + recovery.apply(&mut options)?; + } let job = self .inner_ref()? - .refresh_column_async(column) + .refresh_column_async_with_options(column, options) .await .default_error()?; - Ok(crate::job::Job::new(job)) + Ok(if typed_result { + crate::job::Job::new_typed(job) + } else { + crate::job::Job::new(job) + }) } #[napi(catch_unwind)] @@ -446,17 +729,12 @@ impl Table { options: Option, ) -> napi::Result { let options = options.unwrap_or_default(); - let limit = options - .limit - .map(|limit| { - usize::try_from(limit) - .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer")) - }) - .transpose()?; let request = lancedb::function::FunctionErrorsRequest { + history: options.history.unwrap_or_default(), job_id: options.job_id, column: options.column, - limit, + limit: function_listing_limit(options.limit)?, + page_token: options.page_token, }; let errors = self .inner_ref()? @@ -467,10 +745,121 @@ impl Table { } #[napi(catch_unwind)] + pub async fn quarantine_function_errors( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default(); + let options = lancedb::function::FunctionQuarantineOptions { + quarantined: options.quarantined.unwrap_or(true), + job_id: options.job_id, + error_type: options.error_type, + after_attempts: positive_u32(options.after_attempts, "afterAttempts")?, + }; + let affected = self + .inner_ref()? + .quarantine_function_errors(&column, options) + .await + .default_error()?; + Ok(affected as f64) + } + + #[napi(catch_unwind)] + pub async fn function_provenance( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default(); + let version = match options.version { + None => None, + Some(Either::A(number)) => Some(positive_safe_integer(number, "version")?), + Some(Either::B(bigint)) => { + let (negative, value, lossless) = bigint.get_u64(); + if negative || !lossless || value == 0 { + return Err(napi::Error::from_reason( + "version must be a positive lossless u64 bigint", + )); + } + Some(value) + } + }; + let options = lancedb::function::FunctionProvenanceOptions { + version, + limit: function_listing_limit(options.limit)?, + }; + let provenance = self + .inner_ref()? + .function_provenance(&column, options) + .await + .default_error()?; + Ok(FunctionProvenance { + records: provenance.records.into_iter().map(Into::into).collect(), + truncated: provenance.truncated, + }) + } + + #[napi(catch_unwind)] + pub async fn function_column_statuses( + &self, + column: Option, + ) -> napi::Result> { + let statuses = self + .inner_ref()? + .function_column_statuses(column.as_deref()) + .await + .default_error()?; + Ok(statuses.into_iter().map(Into::into).collect()) + } + + #[napi(catch_unwind)] + pub async fn function_column_status( + &self, + column: String, + ) -> napi::Result { + let status = self + .inner_ref()? + .function_column_status(&column) + .await + .default_error()?; + Ok(status.into()) + } + + #[napi(catch_unwind)] + pub async fn wait_for_function_column( + &self, + column: String, + timeout_seconds: Option, + ) -> napi::Result { + let timeout = timeout_seconds + .map(|seconds| { + u64::try_from(seconds) + .map(std::time::Duration::from_secs) + .map_err(|_| { + napi::Error::from_reason("timeoutSeconds must be a non-negative integer") + }) + }) + .transpose()?; + let status = self + .inner_ref()? + .wait_for_function_column(&column, timeout) + .await + .default_error()?; + Ok(status.into()) + } + + #[napi(catch_unwind)] + #[allow(clippy::too_many_arguments)] pub async fn refresh_materialized_view( &self, source_version: Option, full: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> napi::Result { let view = lancedb::MaterializedView::from_table(self.inner_ref()?.clone()) .await @@ -482,6 +871,30 @@ impl Table { })?; builder = builder.source_version(version); } + let resources: lancedb::table::RefreshColumnOptions = RefreshColumnOptions { + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, + ..Default::default() + } + .try_into()?; + if let Some(value) = resources.total_cpu_millis { + builder = builder.total_cpu_millis(value); + } + if let Some(value) = resources.total_memory_bytes { + builder = builder.total_memory_bytes(value); + } + if let Some(value) = resources.total_gpu_count { + builder = builder.total_gpu_count(value); + } + if let Some(value) = resources.gpu_class { + builder = builder.gpu_class(value); + } + if let Some(value) = resources.gpu_count { + builder = builder.gpu_count(value); + } let result = builder.execute().await.default_error()?; Ok(result.into()) } @@ -601,6 +1014,37 @@ impl Table { Ok(spec.map(RTEWriteSpec::from)) } + #[napi(catch_unwind, ts_return_type = "Promise>")] + pub async fn get_table_overrides(&self) -> napi::Result { + self.inner_ref()? + .get_table_overrides() + .await + .default_error() + } + + #[napi( + catch_unwind, + ts_args_type = "overrides: Record", + ts_return_type = "Promise>" + )] + pub async fn update_table_overrides( + &self, + overrides: serde_json::Value, + ) -> napi::Result { + self.inner_ref()? + .update_table_overrides(overrides) + .await + .default_error() + } + + #[napi(catch_unwind, ts_return_type = "Promise>")] + pub async fn reset_table_overrides(&self) -> napi::Result { + self.inner_ref()? + .reset_table_overrides() + .await + .default_error() + } + #[napi(catch_unwind, js_name = "closeRTEWriters")] pub async fn close_rte_writers(&self) -> napi::Result<()> { self.inner_ref()?.close_rte_writers().await.default_error() @@ -670,6 +1114,19 @@ impl Table { self.inner_ref()?.checkout_latest().await.default_error() } + /// Compare two persisted versions or same-branch tags. + #[napi(catch_unwind)] + pub async fn delta( + &self, + from_version: DeltaRef, + to_version: Option, + ) -> napi::Result { + let from = from_version.into_delta_ref()?; + let to = to_version.map(DeltaRef::into_delta_ref).transpose()?; + let delta = self.inner_ref()?.delta(from, to).await.default_error()?; + Ok(TableDelta::new(delta)) + } + #[napi(catch_unwind)] pub async fn list_versions(&self) -> napi::Result> { self.inner_ref()? @@ -717,11 +1174,56 @@ impl Table { Ok(self.inner_ref()?.current_branch()) } + #[napi(catch_unwind)] + pub async fn explain_cleanup( + &self, + min_age_seconds: Option, + ) -> napi::Result { + let plan = self + .inner_ref()? + .explain_cleanup(parse_cleanup_options(min_age_seconds)?) + .await + .default_error()?; + serde_json::to_value(plan).map_err(|error| napi::Error::from_reason(error.to_string())) + } + + #[napi(catch_unwind)] + pub async fn cleanup_async( + &self, + min_age_seconds: Option, + ) -> napi::Result { + let options = parse_cleanup_options(min_age_seconds)?; + let job = self + .inner_ref()? + .cleanup_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + + #[napi(catch_unwind)] + pub async fn compact_async( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(CompactionOptions::into_overrides) + .transpose()? + .unwrap_or_default(); + let job = self + .inner_ref()? + .compact_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + #[napi(catch_unwind)] pub async fn optimize( &self, before_timestamp_ms: Option, delete_unverified: Option, + compaction_options: Option, ) -> napi::Result { let inner = self.inner_ref()?; @@ -736,8 +1238,11 @@ impl Table { .transpose()?; let stats = inner - .optimize_full( - lancedb::table::CompactionOptions::default(), + .optimize_full_with_overrides( + compaction_options + .map(CompactionOptions::into_overrides) + .transpose()? + .unwrap_or_default(), None, before_timestamp, delete_unverified, @@ -886,7 +1391,12 @@ pub struct IndexConfig { impl From for IndexConfig { fn from(value: lancedb::index::IndexConfig) -> Self { - let index_type = format!("{:?}", value.index_type); + // A registered plugin's type is its display name, such as "MinHashLsh", + // which `Debug` would render as `Custom("MinHashLsh")`. + let index_type = match value.index_type { + lancedb::index::IndexType::Custom(name) => name, + index_type => format!("{index_type:?}"), + }; Self { index_type, columns: value.columns, @@ -1513,6 +2023,351 @@ pub struct FunctionErrorsOptions { pub column: Option, /// At most this many records (server default 10000, cap 100000). pub limit: Option, + /// Include retained historical attempts, including repaired rows. Requires workflow version 1 or later. + pub history: Option, + /// Empty starts retained history, including repaired rows, for an exact jobId; otherwise continue that page. + pub page_token: Option, +} + +fn function_listing_limit(limit: Option) -> napi::Result> { + limit + .map(|limit| { + usize::try_from(limit) + .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer")) + }) + .transpose() +} + +/// Select current failures to quarantine or release. +#[napi(object)] +#[derive(Default)] +pub struct FunctionQuarantineOptions { + /// Quarantine by default. Set false to release failures for later refreshes. + pub quarantined: Option, + /// Only failures recorded by this job. + pub job_id: Option, + /// Only failures with this exception class. + pub error_type: Option, + /// Only failures with at least this many attempts. Defaults to 1. + pub after_attempts: Option, +} + +/// Snapshot and record limit for a producing-version listing. +#[napi(object)] +#[derive(Default)] +pub struct FunctionProvenanceOptions { + /// An exact table version. Defaults to the table handle's read version. + pub version: Option>, + /// Maximum records to return (server default 10000, cap 100000). + pub limit: Option, +} + +#[napi(object)] +pub struct FunctionRecoveryOptions { + pub retry_errors: Option, + pub retry_job_id: Option, + pub retry_error_type: Option, + pub include_quarantined: Option, + pub function_version: Option, + pub recompute: Option, +} + +impl FunctionRecoveryOptions { + fn apply(self, options: &mut lancedb::table::RefreshColumnOptions) -> napi::Result<()> { + use lancedb::function::FunctionRecompute; + options.retry_errors = self.retry_errors; + options.retry_job_id = self.retry_job_id; + options.retry_error_type = self.retry_error_type; + options.include_quarantined = self.include_quarantined; + options.function_version = self.function_version; + options.recompute = match self.recompute.as_deref() { + None => None, + Some("failed") => Some(FunctionRecompute::Failed), + Some("all") => Some(FunctionRecompute::All), + Some("none") => Some(FunctionRecompute::None), + Some(_) => { + return Err(napi::Error::from_reason( + "recompute must be 'failed', 'all', or 'none'", + )); + } + }; + Ok(()) + } +} + +/// CPU, memory, and ephemeral-storage limits for one Function refresh +/// control-plane pod. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionRefreshPodResources { + /// CPU limit in millicores; 1000 is one CPU. + pub cpu_millis: f64, + /// Memory limit in bytes. + pub memory_bytes: f64, + /// Ephemeral storage limit in bytes. + pub ephemeral_storage_bytes: f64, +} + +/// Resources and sizing policy for the planning fleet of one registered +/// Function refresh. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionRefreshPlanningConfig { + /// CPU, memory, and ephemeral-storage limits for one planning worker. + pub resources: FunctionRefreshPodResources, + /// Maximum number of planning workers. + pub max_workers: f64, + /// Maximum rows assigned to one planning worker. + pub rows_per_worker: f64, + /// Maximum fragments assigned to one planning worker. + pub fragments_per_worker: f64, +} + +/// Overrides retries of failed user-code calls for one refresh. Omitted +/// fields use the Function refresh defaults. +#[napi(object)] +#[derive(Clone, Debug, Default)] +pub struct FunctionRetryPolicy { + /// Total calls, including the first; 1 disables retries, maximum 100. + pub max_attempts: Option, + /// Initial exponential-backoff ceiling, in seconds. + pub initial_backoff_seconds: Option, + /// Maximum backoff, in seconds. + pub max_backoff_seconds: Option, + /// Exception class names, preferably qualified. + pub exception_types: Option>, + /// Regular expression matched against the exception class and message. + pub message_pattern: Option, + /// Structured provider error codes or HTTP status codes. + pub error_codes: Option>, + /// Match connection/timeouts, HTTP 429/503, SlowDown and + /// ServiceUnavailable. + pub transient: Option, + /// Honor Retry-After within the configured maximum. + pub honor_retry_after: Option, +} + +fn positive_safe_integer(value: f64, name: &str) -> napi::Result { + const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + if !value.is_finite() || value.fract() != 0.0 || !(1.0..=MAX_SAFE_INTEGER).contains(&value) { + return Err(napi::Error::from_reason(format!( + "{name} must be a positive safe integer" + ))); + } + Ok(value as u64) +} + +fn positive_u32(value: Option, name: &str) -> napi::Result> { + value + .map(|value| { + if !value.is_finite() + || value.fract() != 0.0 + || !(1.0..=u32::MAX as f64).contains(&value) + { + return Err(napi::Error::from_reason(format!( + "{name} must be an integer between 1 and 4294967295" + ))); + } + Ok(value as u32) + }) + .transpose() +} + +/// Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every +/// option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores +/// `batchSize`, `gpuClass` and `totalGpuCount` and rejects the rest. +#[napi(object)] +#[derive(Clone, Debug, Default)] +pub struct RefreshColumnOptions { + /// Only refresh the rows matching this SQL filter. + #[napi(js_name = "where")] + pub where_clause: Option, + /// Maximum rows per Function call; must be greater than zero. + pub batch_size: Option, + /// Row-count threshold for publishing completed Function split ranges. + /// Must be a positive safe integer. Omit for whole-fragment publication. + /// Actual publications can be larger; remaining rows publish at completion. + /// Requires LanceDB Enterprise with non-Blob Function outputs. + pub publication_interval_rows: Option, + /// Override the registered Function's maximum concurrent user-code calls + /// for this logical execution. + pub max_concurrency: Option, + /// GPU class for Function workers. + pub gpu_class: Option, + /// Positive GPU count allocated to each Function worker. + pub gpu_count: Option, + /// Override the total CPU budget in millicores for this refresh. + pub total_cpu_millis: Option, + /// Override the total memory budget in bytes for this refresh. + pub total_memory_bytes: Option, + /// CPU, memory, and ephemeral-storage limits for the refresh supervisor. + pub supervisor_resources: Option, + /// Resources and sizing for the refresh planning fleet. + pub planning_workers: Option, + /// Nonnegative total GPU budget for Function workers. + pub total_gpu_count: Option, + /// Override retries of failed user-code calls for this refresh. + pub retry_policy: Option, + /// `"fail"` stops on a row error; `"skip"` records it and continues, + /// subject to the failure limits. The default is server-dependent. + pub error_policy: Option, + /// Under a skip policy, fail the job once more than this share of rows + /// (0 to 1) has failed. + pub max_failed_fraction: Option, + /// Under a skip policy, fail the job once more than this many rows have + /// failed. + pub max_failed_rows: Option, + /// Deadline for one Function call, in seconds. + pub row_timeout_seconds: Option, + /// Deadline for Function initialization, in seconds. + pub init_timeout_seconds: Option, + /// Worker count for an expression column; Function columns reject it. + pub num_workers: Option, + /// Cap on executor processes per Function worker. + pub max_executor_processes_per_worker: Option, +} + +impl TryFrom for lancedb::table::RefreshColumnOptions { + type Error = napi::Error; + + fn try_from(value: RefreshColumnOptions) -> napi::Result { + let mut options = Self::default(); + options.where_clause = value.where_clause; + options.batch_size = value.batch_size.map(|size| size as usize); + options.publication_interval_rows = value + .publication_interval_rows + .map(|rows| positive_safe_integer(rows, "publicationIntervalRows")) + .transpose()?; + options.max_concurrency = positive_u32(value.max_concurrency, "maxConcurrency")?; + options.gpu_class = value.gpu_class; + options.gpu_count = positive_u32(value.gpu_count, "gpuCount")?; + options.total_cpu_millis = value + .total_cpu_millis + .map(|value| positive_safe_integer(value, "totalCpuMillis")) + .transpose()?; + options.total_memory_bytes = value + .total_memory_bytes + .map(|value| positive_safe_integer(value, "totalMemoryBytes")) + .transpose()?; + options.supervisor_resources = value + .supervisor_resources + .map(|resources| { + Ok::<_, napi::Error>(LanceFunctionRefreshPodResources::new( + positive_safe_integer(resources.cpu_millis, "supervisorResources.cpuMillis")?, + positive_safe_integer( + resources.memory_bytes, + "supervisorResources.memoryBytes", + )?, + positive_safe_integer( + resources.ephemeral_storage_bytes, + "supervisorResources.ephemeralStorageBytes", + )?, + )) + }) + .transpose()?; + options.planning_workers = value + .planning_workers + .map(|planning| { + let resources = LanceFunctionRefreshPodResources::new( + positive_safe_integer( + planning.resources.cpu_millis, + "planningWorkers.resources.cpuMillis", + )?, + positive_safe_integer( + planning.resources.memory_bytes, + "planningWorkers.resources.memoryBytes", + )?, + positive_safe_integer( + planning.resources.ephemeral_storage_bytes, + "planningWorkers.resources.ephemeralStorageBytes", + )?, + ); + let max_workers = usize::try_from(positive_safe_integer( + planning.max_workers, + "planningWorkers.maxWorkers", + )?) + .map_err(|_| napi::Error::from_reason("planningWorkers.maxWorkers is too large"))?; + Ok::<_, napi::Error>(LanceFunctionRefreshPlanningConfig::new( + resources, + max_workers, + positive_safe_integer( + planning.rows_per_worker, + "planningWorkers.rowsPerWorker", + )?, + positive_safe_integer( + planning.fragments_per_worker, + "planningWorkers.fragmentsPerWorker", + )?, + )) + }) + .transpose()?; + options.total_gpu_count = value + .total_gpu_count + .map(|count| { + if !count.is_finite() + || count.fract() != 0.0 + || !(0.0..=u32::MAX as f64).contains(&count) + { + return Err(napi::Error::from_reason( + "totalGpuCount must be an integer between 0 and 4294967295", + )); + } + Ok(count as u32) + }) + .transpose()?; + options.retry_policy = value.retry_policy.map(|policy| { + let mut converted = lancedb::function::FunctionRetryPolicy::default(); + if let Some(max_attempts) = policy.max_attempts { + converted.max_attempts = max_attempts; + } + if let Some(seconds) = policy.initial_backoff_seconds { + converted.initial_backoff_seconds = seconds; + } + if let Some(seconds) = policy.max_backoff_seconds { + converted.max_backoff_seconds = seconds; + } + if let Some(exception_types) = policy.exception_types { + converted.exception_types = exception_types; + } + if let Some(pattern) = policy.message_pattern { + converted.message_pattern = Some(pattern); + } + if let Some(error_codes) = policy.error_codes { + converted.error_codes = error_codes; + } + if let Some(transient) = policy.transient { + converted.transient = transient; + } + if let Some(honor_retry_after) = policy.honor_retry_after { + converted.honor_retry_after = honor_retry_after; + } + converted + }); + options.error_policy = match value.error_policy.as_deref() { + None => None, + Some("fail") => Some(lancedb::function::FunctionErrorPolicy::Fail), + Some("skip") => Some(lancedb::function::FunctionErrorPolicy::Skip), + Some(other) => { + return Err(napi::Error::from_reason(format!( + "errorPolicy must be \"fail\" or \"skip\", got \"{other}\"" + ))); + } + }; + options.max_failed_fraction = value.max_failed_fraction; + options.max_failed_rows = value + .max_failed_rows + .map(|rows| { + u64::try_from(rows).map_err(|_| { + napi::Error::from_reason("maxFailedRows must be a non-negative integer") + }) + }) + .transpose()?; + options.row_timeout_seconds = value.row_timeout_seconds; + options.init_timeout_seconds = value.init_timeout_seconds; + options.num_workers = value.num_workers.map(|workers| workers as usize); + options.max_executor_processes_per_worker = value.max_executor_processes_per_worker; + Ok(options) + } } /// One row a Function refresh skipped, as the server recorded it. @@ -1524,32 +2379,113 @@ pub struct FunctionErrorRecord { /// The row's offset within the fragment; absent when the fragment's /// detail was capped. pub row_offset: Option, + /// Stable row identity when recorded. It survives compaction and rewrite. + pub row_id: Option, + /// Physical row address at the recorded version. A rewrite can change it. + pub row_address: Option, pub column: String, pub function: String, pub function_version: String, pub table_version: i64, pub error_type: String, pub error_message: String, + /// Number of failed invocation attempts, when recorded. + pub attempts: Option, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub created_at_millis: i64, + /// First failure time for this row, when recorded. + pub first_seen_at_millis: Option, + /// Latest failure time for this row, when recorded. + pub last_seen_at_millis: Option, + /// Whether the failure is quarantined. Absent on older listings. + pub quarantined: Option, + /// Source identities for a materialized-view Function invocation. + #[napi(ts_type = "unknown")] + pub input: Option, } -impl From for FunctionErrorRecord { - fn from(record: lancedb::function::FunctionErrorRecord) -> Self { +impl FunctionErrorRecord { + fn from_record(record: lancedb::function::FunctionErrorRecord, has_workflow: bool) -> Self { Self { job_id: record.job_id, fragment_id: record.fragment_id as i64, row_offset: record.row_offset.map(i64::from), + row_id: record.row_id.map(BigInt::from), + row_address: record.row_address.map(BigInt::from), column: record.column, function: record.function, function_version: record.function_version, table_version: record.table_version as i64, error_type: record.error_type, error_message: record.error_message, + attempts: record.attempts, + traceback: record.traceback, created_at_millis: record.created_at_millis, + first_seen_at_millis: record.first_seen_at_millis, + last_seen_at_millis: record.last_seen_at_millis, + quarantined: has_workflow.then_some(record.quarantined), + input: record.input, } } } +/// One cause among the returned Function errors. +#[napi(object)] +pub struct FunctionErrorGroup { + pub column: String, + pub error_type: String, + pub error_message: String, + pub rows_failed: BigInt, +} + +impl From for FunctionErrorGroup { + fn from(group: lancedb::function::FunctionErrorGroup) -> Self { + Self { + column: group.column, + error_type: group.error_type, + error_message: group.error_message, + rows_failed: BigInt::from(group.rows_failed), + } + } +} + +/// The Function and job that produced one stored value. +#[napi(object)] +pub struct FunctionValueProvenance { + pub column: String, + pub job_id: String, + pub function_name: String, + pub function_version: String, + pub row_id: Option, + pub row_address: Option, + pub source_version: BigInt, + pub published_version: BigInt, +} + +impl From for FunctionValueProvenance { + fn from(record: lancedb::function::FunctionValueProvenance) -> Self { + Self { + column: record.column, + job_id: record.job_id, + function_name: record.function_name, + function_version: record.function_version, + row_id: record.row_id.map(BigInt::from), + row_address: record.row_address.map(BigInt::from), + source_version: BigInt::from(record.source_version), + published_version: BigInt::from(record.published_version), + } + } +} + +/// A bounded producing-version listing for a table snapshot. +#[napi(object)] +pub struct FunctionProvenance { + pub records: Vec, + /// Whether the listing stopped at its limit. + pub truncated: bool, +} + /// A fragment whose per-row error detail was capped: `rowsSkipped` rows /// failed, of which only `rowsRecorded` have a record of their own. #[napi(object)] @@ -1574,22 +2510,147 @@ impl From for FunctionErrorFragment { /// A table's per-row Function errors. #[napi(object)] -#[derive(Clone, Debug)] pub struct FunctionErrors { + /// Version of the Enterprise row-failure workflow, if advertised by the server. + pub workflow_version: Option, + /// Grouped causes over the returned records, if the server supports the workflow. + /// Counts can be incomplete. Check `truncated` and `fragments` before using them as totals. + pub error_groups: Option>, /// The recorded rows, newest job first. pub records: Vec, /// Fragments whose detail was capped. pub fragments: Vec, /// Whether the listing stopped at its limit. pub truncated: bool, + /// Continue the same job/filter. Absent for complete pages and older servers. + pub page_token: Option, +} + +/// One exact immutable Function revision attached to a table output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnVersionStatus { + pub name: String, + pub namespace_path: Vec, + pub object_id: String, + pub location: String, + pub version: String, + pub manifest_digest: String, +} + +/// Latest matching refresh Job projected for a Function output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + pub automatic: Option, + pub completed_at_millis: Option, + pub failure: Option, +} + +impl From for FunctionColumnLastRefreshJob { + fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self { + Self { + job_id: job.job_id, + state: job.state, + automatic: job.automatic, + completed_at_millis: job.completed_at_millis.map(BigInt::from), + failure: job.failure.map(Into::into), + } + } +} + +/// Automatic-refresh projection for a Function output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + pub interval_seconds: Option, + pub active_job_id: Option, + pub state: String, + pub failure_streak: u32, + pub effective_cooldown_millis: Option, + pub blocked_reason: Option, + pub next_run_at_millis: Option, + pub next_run_at_reason: Option, +} + +/// Exact four-way status of one Function output at one table version. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: BigInt, + pub rows: BigInt, + pub fresh: BigInt, + pub stale: BigInt, + pub never_computed: BigInt, + pub failed: BigInt, + pub last_refresh_job: Option, + pub last_failure_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +impl From for FunctionColumnStatus { + fn from(status: lancedb::table::FunctionColumnStatus) -> Self { + Self { + column: status.column, + binding_id: status.binding_id, + function: FunctionColumnVersionStatus { + name: status.function.name, + namespace_path: status.function.namespace_path, + object_id: status.function.object_id, + location: status.function.location, + version: status.function.version, + manifest_digest: status.function.manifest_digest, + }, + table_version: BigInt::from(status.table_version), + rows: BigInt::from(status.rows), + fresh: BigInt::from(status.fresh), + stale: BigInt::from(status.stale), + never_computed: BigInt::from(status.never_computed), + failed: BigInt::from(status.failed), + last_refresh_job: status.last_refresh_job.map(Into::into), + last_failure_job: status.last_failure_job.map(Into::into), + auto_refresh: FunctionColumnAutoRefreshStatus { + enabled: status.auto_refresh.enabled, + interval_seconds: status.auto_refresh.interval_seconds.map(BigInt::from), + active_job_id: status.auto_refresh.active_job_id, + state: status.auto_refresh.state.as_str().to_string(), + failure_streak: status.auto_refresh.failure_streak, + effective_cooldown_millis: status + .auto_refresh + .effective_cooldown_millis + .map(BigInt::from), + blocked_reason: status + .auto_refresh + .blocked_reason + .map(|reason| reason.as_str().to_string()), + next_run_at_millis: status.auto_refresh.next_run_at_millis.map(BigInt::from), + next_run_at_reason: status.auto_refresh.next_run_at_reason, + }, + } + } } impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { + let has_workflow = errors.workflow_version.is_some_and(|version| version >= 1); Self { - records: errors.records.into_iter().map(Into::into).collect(), + workflow_version: errors.workflow_version, + error_groups: has_workflow + .then(|| errors.error_groups.into_iter().map(Into::into).collect()), + records: errors + .records + .into_iter() + .map(|record| FunctionErrorRecord::from_record(record, has_workflow)) + .collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, + page_token: errors.page_token, } } } @@ -1688,6 +2749,84 @@ pub struct BranchContents { pub manifest_size: i64, } +fn from_tag_hint(name: &str, tag: &str) -> String { + let name_literal = serde_json::Value::String(name.to_string()).to_string(); + let tag_literal = serde_json::Value::String(tag.to_string()).to_string(); + format!( + "If {tag_literal} is a tag, use branches.create({name_literal}, {{ fromTag: {tag_literal} }}) instead of fromRef." + ) +} + +/// A pinned version range with streaming row changes. +#[napi] +pub struct TableDelta { + inner: Arc, +} + +impl TableDelta { + fn new(inner: LanceDbTableDelta) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + +#[napi] +impl TableDelta { + #[napi] + pub fn begin_version(&self) -> BigInt { + BigInt::from(self.inner.begin_version()) + } + + #[napi] + pub fn end_version(&self) -> BigInt { + BigInt::from(self.inner.end_version()) + } + + #[napi(catch_unwind)] + pub async fn inserted_rows(&self) -> napi::Result { + let stream = self.inner.inserted_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn updated_rows(&self) -> napi::Result { + let stream = self.inner.updated_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn upserted_rows(&self) -> napi::Result { + let stream = self.inner.upserted_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn deleted_row_ids(&self) -> napi::Result { + let stream = self.inner.deleted_row_ids().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn list_transactions(&self) -> napi::Result> { + let transactions = self.inner.list_transactions().await.default_error()?; + Ok(transactions + .into_iter() + .map(|transaction| TableDeltaTransaction { + read_version: BigInt::from(transaction.read_version), + uuid: transaction.uuid, + operation: transaction.operation.name().to_string(), + tag: transaction.tag, + transaction_properties: transaction + .transaction_properties + .as_ref() + .map(|properties| (**properties).clone()), + }) + .collect()) + } +} + +/// Tags label table versions with human-readable names. #[napi] pub struct Tags { inner: LanceDbTable, @@ -1726,12 +2865,20 @@ impl Tags { .default_error() } + /// Create a tag for a table version. + /// + /// Omit `version` to tag the version this handle currently shows, + /// including a checked-out version. #[napi] - pub async unsafe fn create(&mut self, tag: String, version: i64) -> napi::Result<()> { + pub async unsafe fn create(&mut self, tag: String, version: Option) -> napi::Result<()> { + let version = match version { + Some(version) => version as u64, + None => self.inner.version().await.default_error()?, + }; let mut rust_tags = self.inner.tags().await.default_error()?; rust_tags .as_mut() - .create(tag.as_str(), version as u64) + .create(tag.as_str(), version) .await .default_error() } @@ -1789,7 +2936,18 @@ impl Branches { name: String, from_ref: Option, from_version: Option, + from_tag: Option, ) -> napi::Result
      { + if from_tag.is_some() && (from_ref.is_some() || from_version.is_some()) { + return Err(napi::Error::from_reason( + "fromTag cannot be combined with fromRef or fromVersion; pass only one source", + )); + } + let from_branch = if from_tag.is_none() { + from_ref.clone() + } else { + None + }; let from_ref = from_ref.filter(|b| b != "main"); let from_version = from_version .map(|v| { @@ -1798,13 +2956,27 @@ impl Branches { }) }) .transpose()?; - let from = Ref::Version(from_ref, from_version); - let table = self - .inner - .create_branch(&name, from) - .await - .default_error()?; - Ok(Table::new(table)) + let from = match from_tag { + Some(tag) => Ref::Tag(tag), + None => Ref::Version(from_ref, from_version), + }; + match self.inner.create_branch(&name, from).await { + Ok(table) => Ok(Table::new(table)), + Err(error) => { + // A missing branch is a native NotFound. A missing version is + // VersionNotFound, and an Enterprise 404 is an ambiguous + // TableNotFound, so only the native branch case gets the hint. + let missing_branch = matches!( + &error, + lancedb::Error::Lance { source } if source.is_not_found() + ); + let mut error = convert_error(&error); + if missing_branch && let Some(branch) = from_branch.as_deref() { + error.reason = format!("{}\n{}", error.reason, from_tag_hint(&name, branch)); + } + Err(error) + } + } } #[napi] @@ -1852,3 +3024,36 @@ impl Branches { }) } } + +fn parse_cleanup_options( + min_age_seconds: Option, +) -> napi::Result { + let mut options = lancedb::table::CleanupOptions::new(); + if let Some(age) = min_age_seconds { + if !age.is_finite() || age.fract() != 0.0 || !(0.0..=9_007_199_254_740_991.0).contains(&age) + { + return Err(napi::Error::from_reason( + "minAgeSeconds must be a nonnegative safe integer", + )); + } + options.min_age_seconds = Some(age as u64); + } + Ok(options) +} + +#[cfg(test)] +mod tests { + use super::from_tag_hint; + + #[test] + fn from_tag_hint_uses_escaped_javascript_string_literals() { + assert_eq!( + from_tag_hint("exp", "baseline"), + r#"If "baseline" is a tag, use branches.create("exp", { fromTag: "baseline" }) instead of fromRef."# + ); + assert_eq!( + from_tag_hint("branch\"name\\path", "tag\"name\\path"), + r#"If "tag\"name\\path" is a tag, use branches.create("branch\"name\\path", { fromTag: "tag\"name\\path" }) instead of fromRef."# + ); + } +} diff --git a/python/CONTRIBUTING.md b/python/CONTRIBUTING.md index f86dea706..556cebf64 100644 --- a/python/CONTRIBUTING.md +++ b/python/CONTRIBUTING.md @@ -16,7 +16,7 @@ The Python package is a wrapper around the Rust library, `lancedb`. We use To set up your development environment, you will need to install the following: -1. Python 3.10 or later +1. Python 3.11 or later 2. Cargo (Rust's package manager). Use [rustup](https://rustup.rs/) to install. 3. [protoc](https://grpc.io/docs/protoc-installation/) (Protocol Buffers compiler) diff --git a/python/Cargo.toml b/python/Cargo.toml index e816ca6d7..45aee7038 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.4" +version = "0.42.0-beta.37" publish = false edition.workspace = true description = "Python bindings for LanceDB" @@ -8,7 +8,7 @@ license.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true -rust-version = "1.95.0" +rust-version = "1.98.0" [lib] name = "_lancedb" @@ -30,13 +30,14 @@ env_logger.workspace = true log.workspace = true # Maturin enables extension-module mode for Python builds. Keeping it out of # Cargo features lets Rust unit tests link against libpython. -pyo3 = { version = "0.29", features = ["abi3-py310", "chrono", "uuid"] } +pyo3 = { version = "0.29", features = ["abi3-py311", "chrono", "uuid"] } chrono.workspace = true pyo3-async-runtimes = { version = "0.29", features = [ "attributes", "tokio-runtime", ] } reqwest.workspace = true +rattler_conda_types = { version = "0.58.3", default-features = false } pin-project.workspace = true futures.workspace = true serde.workspace = true @@ -50,7 +51,7 @@ libc = "0.2" pyo3-build-config = "0.29" [features] -default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"] +default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] experimental-functions = ["lancedb/experimental-functions"] diff --git a/python/RUST_THIRD_PARTY_LICENSES.html b/python/RUST_THIRD_PARTY_LICENSES.html index f5e8197fd..2e0c1f20c 100644 --- a/python/RUST_THIRD_PARTY_LICENSES.html +++ b/python/RUST_THIRD_PARTY_LICENSES.html @@ -44,18 +44,19 @@

      Overview of licenses:

      All license text:

      @@ -64,230 +65,20 @@

      BSD Zero Clause License

      Used by:

      -
      Copyright (C) 2020 by museun <museun@outlook.com>
      +                
      Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
       
      -Permission to use, copy, modify, and/or distribute this software for any purpose
      -with or without fee is hereby granted.
      +Permission to use, copy, modify, and/or distribute this software for
      +any purpose with or without fee is hereby granted.
       
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
      -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
      -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
      -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
      -THIS SOFTWARE.
      -
      - -
    • -

      Apache License 2.0

      -

      Used by:

      - -
      -                                 Apache License
      -                           Version 2.0, January 2004
      -                        http://www.apache.org/licenses/
      -
      -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      -
      -   1. Definitions.
      -
      -      "License" shall mean the terms and conditions for use, reproduction,
      -      and distribution as defined by Sections 1 through 9 of this document.
      -
      -      "Licensor" shall mean the copyright owner or entity authorized by
      -      the copyright owner that is granting the License.
      -
      -      "Legal Entity" shall mean the union of the acting entity and all
      -      other entities that control, are controlled by, or are under common
      -      control with that entity. For the purposes of this definition,
      -      "control" means (i) the power, direct or indirect, to cause the
      -      direction or management of such entity, whether by contract or
      -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      -      outstanding shares, or (iii) beneficial ownership of such entity.
      -
      -      "You" (or "Your") shall mean an individual or Legal Entity
      -      exercising permissions granted by this License.
      -
      -      "Source" form shall mean the preferred form for making modifications,
      -      including but not limited to software source code, documentation
      -      source, and configuration files.
      -
      -      "Object" form shall mean any form resulting from mechanical
      -      transformation or translation of a Source form, including but
      -      not limited to compiled object code, generated documentation,
      -      and conversions to other media types.
      -
      -      "Work" shall mean the work of authorship, whether in Source or
      -      Object form, made available under the License, as indicated by a
      -      copyright notice that is included in or attached to the work
      -      (an example is provided in the Appendix below).
      -
      -      "Derivative Works" shall mean any work, whether in Source or Object
      -      form, that is based on (or derived from) the Work and for which the
      -      editorial revisions, annotations, elaborations, or other modifications
      -      represent, as a whole, an original work of authorship. For the purposes
      -      of this License, Derivative Works shall not include works that remain
      -      separable from, or merely link (or bind by name) to the interfaces of,
      -      the Work and Derivative Works thereof.
      -
      -      "Contribution" shall mean any work of authorship, including
      -      the original version of the Work and any modifications or additions
      -      to that Work or Derivative Works thereof, that is intentionally
      -      submitted to Licensor for inclusion in the Work by the copyright owner
      -      or by an individual or Legal Entity authorized to submit on behalf of
      -      the copyright owner. For the purposes of this definition, "submitted"
      -      means any form of electronic, verbal, or written communication sent
      -      to the Licensor or its representatives, including but not limited to
      -      communication on electronic mailing lists, source code control systems,
      -      and issue tracking systems that are managed by, or on behalf of, the
      -      Licensor for the purpose of discussing and improving the Work, but
      -      excluding communication that is conspicuously marked or otherwise
      -      designated in writing by the copyright owner as "Not a Contribution."
      -
      -      "Contributor" shall mean Licensor and any individual or Legal Entity
      -      on behalf of whom a Contribution has been received by Licensor and
      -      subsequently incorporated within the Work.
      -
      -   2. Grant of Copyright License. Subject to the terms and conditions of
      -      this License, each Contributor hereby grants to You a perpetual,
      -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      -      copyright license to reproduce, prepare Derivative Works of,
      -      publicly display, publicly perform, sublicense, and distribute the
      -      Work and such Derivative Works in Source or Object form.
      -
      -   3. Grant of Patent License. Subject to the terms and conditions of
      -      this License, each Contributor hereby grants to You a perpetual,
      -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      -      (except as stated in this section) patent license to make, have made,
      -      use, offer to sell, sell, import, and otherwise transfer the Work,
      -      where such license applies only to those patent claims licensable
      -      by such Contributor that are necessarily infringed by their
      -      Contribution(s) alone or by combination of their Contribution(s)
      -      with the Work to which such Contribution(s) was submitted. If You
      -      institute patent litigation against any entity (including a
      -      cross-claim or counterclaim in a lawsuit) alleging that the Work
      -      or a Contribution incorporated within the Work constitutes direct
      -      or contributory patent infringement, then any patent licenses
      -      granted to You under this License for that Work shall terminate
      -      as of the date such litigation is filed.
      -
      -   4. Redistribution. You may reproduce and distribute copies of the
      -      Work or Derivative Works thereof in any medium, with or without
      -      modifications, and in Source or Object form, provided that You
      -      meet the following conditions:
      -
      -      (a) You must give any other recipients of the Work or
      -          Derivative Works a copy of this License; and
      -
      -      (b) You must cause any modified files to carry prominent notices
      -          stating that You changed the files; and
      -
      -      (c) You must retain, in the Source form of any Derivative Works
      -          that You distribute, all copyright, patent, trademark, and
      -          attribution notices from the Source form of the Work,
      -          excluding those notices that do not pertain to any part of
      -          the Derivative Works; and
      -
      -      (d) If the Work includes a "NOTICE" text file as part of its
      -          distribution, then any Derivative Works that You distribute must
      -          include a readable copy of the attribution notices contained
      -          within such NOTICE file, excluding those notices that do not
      -          pertain to any part of the Derivative Works, in at least one
      -          of the following places: within a NOTICE text file distributed
      -          as part of the Derivative Works; within the Source form or
      -          documentation, if provided along with the Derivative Works; or,
      -          within a display generated by the Derivative Works, if and
      -          wherever such third-party notices normally appear. The contents
      -          of the NOTICE file are for informational purposes only and
      -          do not modify the License. You may add Your own attribution
      -          notices within Derivative Works that You distribute, alongside
      -          or as an addendum to the NOTICE text from the Work, provided
      -          that such additional attribution notices cannot be construed
      -          as modifying the License.
      -
      -      You may add Your own copyright statement to Your modifications and
      -      may provide additional or different license terms and conditions
      -      for use, reproduction, or distribution of Your modifications, or
      -      for any such Derivative Works as a whole, provided Your use,
      -      reproduction, and distribution of the Work otherwise complies with
      -      the conditions stated in this License.
      -
      -   5. Submission of Contributions. Unless You explicitly state otherwise,
      -      any Contribution intentionally submitted for inclusion in the Work
      -      by You to the Licensor shall be under the terms and conditions of
      -      this License, without any additional terms or conditions.
      -      Notwithstanding the above, nothing herein shall supersede or modify
      -      the terms of any separate license agreement you may have executed
      -      with Licensor regarding such Contributions.
      -
      -   6. Trademarks. This License does not grant permission to use the trade
      -      names, trademarks, service marks, or product names of the Licensor,
      -      except as required for reasonable and customary use in describing the
      -      origin of the Work and reproducing the content of the NOTICE file.
      -
      -   7. Disclaimer of Warranty. Unless required by applicable law or
      -      agreed to in writing, Licensor provides the Work (and each
      -      Contributor provides its Contributions) on an "AS IS" BASIS,
      -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      -      implied, including, without limitation, any warranties or conditions
      -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      -      PARTICULAR PURPOSE. You are solely responsible for determining the
      -      appropriateness of using or redistributing the Work and assume any
      -      risks associated with Your exercise of permissions under this License.
      -
      -   8. Limitation of Liability. In no event and under no legal theory,
      -      whether in tort (including negligence), contract, or otherwise,
      -      unless required by applicable law (such as deliberate and grossly
      -      negligent acts) or agreed to in writing, shall any Contributor be
      -      liable to You for damages, including any direct, indirect, special,
      -      incidental, or consequential damages of any character arising as a
      -      result of this License or out of the use or inability to use the
      -      Work (including but not limited to damages for loss of goodwill,
      -      work stoppage, computer failure or malfunction, or any and all
      -      other commercial damages or losses), even if such Contributor
      -      has been advised of the possibility of such damages.
      -
      -   9. Accepting Warranty or Additional Liability. While redistributing
      -      the Work or Derivative Works thereof, You may choose to offer,
      -      and charge a fee for, acceptance of support, warranty, indemnity,
      -      or other liability obligations and/or rights consistent with this
      -      License. However, in accepting such obligations, You may act only
      -      on Your own behalf and on Your sole responsibility, not on behalf
      -      of any other Contributor, and only if You agree to indemnify,
      -      defend, and hold each Contributor harmless for any liability
      -      incurred by, or claims asserted against, such Contributor by reason
      -      of your accepting any such warranty or additional liability.
      -
      -   END OF TERMS AND CONDITIONS
      -
      -   APPENDIX: How to apply the Apache License to your work.
      -
      -      To apply the Apache License to your work, attach the following
      -      boilerplate notice, with the fields enclosed by brackets "[]"
      -      replaced with your own identifying information. (Don't include
      -      the brackets!)  The text should be enclosed in the appropriate
      -      comment syntax for the file format. We also recommend that a
      -      file or class name and description of purpose be included on the
      -      same "printed page" as the copyright notice for easier
      -      identification within third-party archives.
      -
      -   Copyright 2023 Jacob Pratt
      -
      -   Licensed under the Apache License, Version 2.0 (the "License");
      -   you may not use this file except in compliance with the License.
      -   You may obtain a copy of the License at
      -
      -       http://www.apache.org/licenses/LICENSE-2.0
      -
      -   Unless required by applicable law or agreed to in writing, software
      -   distributed under the License is distributed on an "AS IS" BASIS,
      -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      -   See the License for the specific language governing permissions and
      -   limitations under the License.
      +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
      +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
      +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
      +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
    • @@ -504,7 +295,7 @@ THIS SOFTWARE.

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -714,7 +505,8 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -923,24 +715,18 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

      @@ -1151,7 +937,8 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -1363,7 +1150,13 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -1591,34 +1384,316 @@ Software.
                       

      Apache License 2.0

      Used by:

      +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +Licenses for support code
      +-------------------------
      +
      +Parts of the TLS test suite are under the Go license. This code is not included
      +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
      +distributing code linked against BoringSSL does not trigger this license:
      +
      +Copyright (c) 2009 The Go Authors. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +   * Redistributions of source code must retain the above copyright
      +notice, this list of conditions and the following disclaimer.
      +   * Redistributions in binary form must reproduce the above
      +copyright notice, this list of conditions and the following disclaimer
      +in the documentation and/or other materials provided with the
      +distribution.
      +   * Neither the name of Google Inc. nor the names of its
      +contributors may be used to endorse or promote products derived from
      +this software without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
      +BoringSSL uses the Chromium test infrastructure to run a continuous build,
      +trybots etc. The scripts which manage this, and the script for generating build
      +metadata, are under the Chromium license. Distributing code linked against
      +BoringSSL does not trigger this license.
      +
      +Copyright 2015 The Chromium Authors. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +   * Redistributions of source code must retain the above copyright
      +notice, this list of conditions and the following disclaimer.
      +   * Redistributions in binary form must reproduce the above
      +copyright notice, this list of conditions and the following disclaimer
      +in the documentation and/or other materials provided with the
      +distribution.
      +   * Neither the name of Google Inc. nor the names of its
      +contributors may be used to endorse or promote products derived from
      +this software without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                        Apache License
      @@ -1832,6 +1907,238 @@ This project includes code from Apache Aurora.
       Copyright: 2016 The Apache Software Foundation.
       Home page: https://aurora.apache.org/
       License: http://www.apache.org/licenses/LICENSE-2.0
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +--------------------------------------------------------------------------------
      +
      +arrow-array/src/delta.rs: MIT
      +
      +This file is derived from the chronoutil crate. The full MIT license
      +text is in arrow-array/LICENSE-MIT.
       
    • @@ -1839,9 +2146,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

      Used by:

                                        Apache License
      @@ -2051,7 +2356,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -2460,41 +2765,30 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2703,7 +2997,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2912,7 +3206,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3102,7 +3397,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
             same "printed page" as the copyright notice for easier
             identification within third-party archives.
       
      -   Copyright 2020 - 2025 Tatsuya Kawano
      +   Copyright 2019 TiKV Project Authors.
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 - 2026 Tatsuya Kawano
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 Sébastien Crozet
       
          Licensed under the Apache License, Version 2.0 (the "License");
          you may not use this file except in compliance with the License.
      @@ -3122,7 +3835,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3330,8 +4042,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3750,7 +4462,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3959,9 +4671,21 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -4170,7 +4894,456 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +------------------------------------------------------------------------------------
      +This product bundles third-party components under other open source licenses.
      +This section summarizes those components and their licenses. See the referenced
      +license files for text of these licenses.
      +
      +
      +Creative Commons Zero v1.0 Universal
      +------------------------------------
      +
      +bindings/dotnet/.gitignore
      +
      +The above file is derived from VisualStudio.gitignore in
      +https://github.com/github/gitignore. Its license text is in
      +bindings/dotnet/LICENSE-CC0-1.0.txt.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +   
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                       Apache License
                                  Version 2.0, January 2004
      @@ -4379,6 +5552,218 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "{}"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright Individual contributors
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                       Apache License
      @@ -4588,22 +5973,28 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -4813,12 +6204,221 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 Sébastien Crozet
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                      Apache License
                                  Version 2.0, January 2004
      @@ -5028,7 +6628,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                     Apache License
                                  Version 2.0, January 2004
      @@ -5446,15 +7046,15 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5664,7 +7264,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5872,7 +7472,8 @@ limitations under the License.

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6081,8 +7682,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6291,7 +7891,6 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
      @@ -6501,7 +8100,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6691,7 +8290,7 @@ APPENDIX: How to apply the Apache License to your work.
          same "printed page" as the copyright notice for easier
          identification within third-party archives.
       
      -Copyright 2018 The pin-utils authors
      +Copyright 2018 Brian Myers
       
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
      @@ -6710,8 +8309,8 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7118,6 +8717,215 @@ You may obtain a copy of the License at
       
          http://www.apache.org/licenses/LICENSE-2.0
       
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright 2019 quininer kel
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      @@ -7130,7 +8938,9 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7340,7 +9150,7 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7758,7 +9568,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7967,7 +9777,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -8178,7 +9988,216 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright 2024 Liam Gray <gmail@liamg.me>
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                    Apache License
                               Version 2.0, January 2004
      @@ -8388,7 +10407,8 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -8596,150 +10616,170 @@ limitations under the License.

      Apache License 2.0

      Used by:

        +
      • addr2line 0.25.1
      • ahash 0.8.12
      • -
      • arc-swap 1.7.1
      • -
      • arrayvec 0.7.6
      • +
      • arc-swap 1.9.3
      • +
      • arrayvec 0.7.8
      • async-channel 2.5.0
      • -
      • async-compression 0.4.19
      • -
      • async-lock 3.4.1
      • +
      • async-compression 0.4.42
      • +
      • async-lock 3.4.2
      • atomic-waker 1.1.2
      • autocfg 1.5.0
      • -
      • base64 0.21.7
      • +
      • backtrace 0.3.76
      • base64 0.22.1
      • -
      • bitflags 2.9.4
      • -
      • bumpalo 3.19.0
      • +
      • base64 0.23.1
      • +
      • bitflags 1.3.2
      • +
      • bitflags 2.11.1
      • +
      • bstr 1.12.1
      • +
      • bumpalo 3.20.2
      • bytes-utils 0.1.4
      • -
      • cc 1.2.40
      • -
      • cfg-if 1.0.3
      • +
      • cast 0.3.0
      • +
      • cc 1.2.62
      • +
      • cfg-if 0.1.10
      • +
      • cfg-if 1.0.4
      • +
      • cmake 0.1.58
      • +
      • compression-codecs 0.4.38
      • +
      • compression-core 0.4.32
      • concurrent-queue 2.5.0
      • const-random-macro 0.1.16
      • const-random 0.1.18
      • core-foundation-sys 0.8.7
      • core-foundation 0.10.1
      • core-foundation 0.9.4
      • +
      • cpp_demangle 0.4.5
      • +
      • criterion-plot 0.8.2
      • +
      • criterion 0.8.2
      • crossbeam-channel 0.5.15
      • crossbeam-deque 0.8.6
      • -
      • crossbeam-epoch 0.9.18
      • +
      • crossbeam-epoch 0.9.20
      • crossbeam-queue 0.3.12
      • +
      • crossbeam-skiplist 0.1.3
      • crossbeam-utils 0.8.21
      • +
      • debugid 0.8.0
      • displaydoc 0.2.5
      • either 1.15.0
      • +
      • encoding_rs_io 0.1.7
      • equivalent 1.0.2
      • errno 0.3.14
      • event-listener-strategy 0.5.4
      • -
      • event-listener 5.4.1
      • -
      • fastrand 2.3.0
      • -
      • find-msvc-tools 0.1.3
      • +
      • event-listener 5.4.2
      • +
      • fastrand 2.4.1
      • +
      • find-msvc-tools 0.1.9
      • +
      • findshlibs 0.10.2
      • fixedbitset 0.5.7
      • +
      • flate2 1.1.9
      • fnv 1.0.7
      • form_urlencoded 1.2.2
      • -
      • fs4 0.8.4
      • +
      • foyer-intrusive-collections 0.10.0-dev
      • +
      • fs4 0.13.1
      • futures-timer 3.0.3
      • -
      • geohash 0.13.1
      • +
      • geohash 0.13.2
      • +
      • gimli 0.32.3
      • glob 0.3.3
      • -
      • group 0.12.1
      • +
      • group 0.14.0
      • hash32 0.3.1
      • hashbrown 0.14.5
      • hashbrown 0.15.5
      • -
      • hashbrown 0.16.0
      • +
      • hashbrown 0.16.1
      • +
      • hashbrown 0.17.1
      • heapless 0.8.0
      • heck 0.5.0
      • hermit-abi 0.5.2
      • httparse 1.10.1
      • -
      • hyper-rustls 0.24.2
      • -
      • hyper-rustls 0.27.7
      • +
      • hyper-rustls 0.27.9
      • +
      • hyper-timeout 0.5.2
      • idna 1.1.0
      • -
      • idna_adapter 1.2.1
      • -
      • indexmap 2.12.0
      • -
      • itertools 0.11.0
      • +
      • idna_adapter 1.2.2
      • +
      • indexmap 2.14.0
      • itertools 0.13.0
      • itertools 0.14.0
      • +
      • itertools 0.15.0
      • jobserver 0.1.34
      • -
      • js-sys 0.3.81
      • +
      • js-sys 0.3.107
      • lazy_static 1.5.0
      • -
      • linux-raw-sys 0.11.0
      • -
      • linux-raw-sys 0.4.15
      • +
      • linux-raw-sys 0.12.1
      • lock_api 0.4.14
      • -
      • log 0.4.28
      • +
      • log 0.4.34
      • matrixmultiply 0.3.10
      • mime 0.3.17
      • -
      • multimap 0.10.1
      • ndarray 0.16.1
      • -
      • num-bigint-dig 0.8.4
      • +
      • num-bigint-dig 0.8.6
      • num-bigint 0.4.6
      • +
      • num-bigint 0.5.1
      • num-complex 0.4.6
      • num-integer 0.1.46
      • num-iter 0.1.45
      • +
      • num-rational 0.4.2
      • num-traits 0.2.19
      • num_cpus 1.17.0
      • -
      • once_cell 1.21.3
      • -
      • openssl-probe 0.1.6
      • +
      • oauth2 5.0.0
      • +
      • object 0.37.3
      • +
      • once_cell 1.21.4
      • +
      • openssl-probe 0.2.1
      • parking 2.2.1
      • parking_lot 0.12.5
      • parking_lot_core 0.9.12
      • percent-encoding 2.3.2
      • petgraph 0.8.3
      • -
      • pkg-config 0.3.32
      • -
      • prost-build 0.14.3
      • -
      • prost-derive 0.14.3
      • +
      • pkg-config 0.3.33
      • +
      • prost-derive 0.14.4
      • prost-types 0.14.3
      • -
      • prost 0.14.3
      • +
      • prost 0.14.4
      • +
      • rand_xoshiro 0.6.0
      • rawpointer 0.2.1
      • rayon-core 1.13.0
      • -
      • rayon 1.11.0
      • -
      • regex-automata 0.4.13
      • -
      • regex-lite 0.1.7
      • -
      • regex-syntax 0.8.6
      • -
      • regex 1.12.2
      • +
      • rayon 1.12.0
      • +
      • regex-automata 0.4.16
      • +
      • regex-lite 0.1.9
      • +
      • regex-syntax 0.8.11
      • +
      • regex 1.13.1
      • ring 0.17.14
      • +
      • roaring 0.11.5
      • robust 1.2.0
      • +
      • rustc-demangle 0.1.27
      • rustc_version 0.4.1
      • -
      • rustix 0.38.44
      • -
      • rustix 1.1.2
      • -
      • rustls-native-certs 0.6.3
      • -
      • rustls-native-certs 0.8.1
      • -
      • rustls-pemfile 1.0.4
      • -
      • rustls-pemfile 2.2.0
      • -
      • rustls 0.21.12
      • -
      • rustls 0.23.31
      • +
      • rustix 1.1.4
      • +
      • rustls-native-certs 0.8.3
      • +
      • rustls 0.23.46
      • scoped-tls 1.0.1
      • scopeguard 1.2.0
      • -
      • sct 0.7.1
      • -
      • security-framework-sys 2.15.0
      • -
      • security-framework 2.11.1
      • -
      • security-framework 3.5.1
      • -
      • serde_with 3.15.0
      • -
      • serde_with_macros 3.15.0
      • -
      • shellexpand 3.1.1
      • -
      • signal-hook-registry 1.4.6
      • -
      • smallvec 1.15.1
      • -
      • socket2 0.5.10
      • -
      • socket2 0.6.0
      • -
      • sqlparser 0.59.0
      • -
      • sqlparser_derive 0.3.0
      • -
      • stable_deref_trait 1.2.0
      • -
      • syn 1.0.109
      • +
      • security-framework-sys 2.17.0
      • +
      • security-framework 3.7.0
      • +
      • serde_with 3.24.0
      • +
      • serde_with_macros 3.24.0
      • +
      • shellexpand 3.1.2
      • +
      • signal-hook-registry 1.4.8
      • +
      • simd_cesu8 1.1.1
      • +
      • smallvec 1.16.5
      • +
      • socket2 0.6.3
      • +
      • sqlparser 0.62.0
      • +
      • sqlparser_derive 0.5.0
      • +
      • stable_deref_trait 1.2.1
      • +
      • str_stack 0.1.1
      • +
      • symlink 0.1.0
      • system-configuration-sys 0.6.0
      • -
      • system-configuration 0.6.1
      • -
      • tempfile 3.23.0
      • +
      • system-configuration 0.7.0
      • +
      • tempfile 3.27.0
      • thread-tree 0.3.3
      • -
      • thread_local 1.1.9
      • -
      • unicase 2.8.1
      • -
      • unicode-segmentation 1.12.0
      • -
      • unicode-width 0.2.2
      • -
      • url 2.5.7
      • -
      • uuid 1.18.1
      • +
      • thread_local 1.1.10
      • +
      • tinytemplate 1.2.1
      • +
      • unicase 2.9.0
      • +
      • unicode-normalization 0.1.25
      • +
      • unicode-segmentation 1.13.2
      • +
      • unicode-width 0.2.3
      • +
      • url 2.5.8
      • +
      • uuid 1.29.0
      • version_check 0.9.5
      • wasi 0.11.1+wasi-snapshot-preview1
      • wasi 0.14.7+wasi-0.2.4
      • -
      • wasm-bindgen-backend 0.2.104
      • -
      • wasm-bindgen-futures 0.4.54
      • -
      • wasm-bindgen-macro-support 0.2.104
      • -
      • wasm-bindgen-macro 0.2.104
      • -
      • wasm-bindgen-shared 0.2.104
      • -
      • wasm-bindgen 0.2.104
      • -
      • web-sys 0.3.81
      • -
      • wit-bindgen 0.46.0
      • +
      • wasip2 1.0.3+wasi-0.2.9
      • +
      • wasm-bindgen-futures 0.4.80
      • +
      • wasm-bindgen-macro-support 0.2.130
      • +
      • wasm-bindgen-macro 0.2.130
      • +
      • wasm-bindgen-shared 0.2.130
      • +
      • wasm-bindgen 0.2.130
      • +
      • web-sys 0.3.107
      • +
      • wit-bindgen 0.57.1
      • wkb 0.9.2
      • wkt 0.14.0
      • xmlparser 0.13.6
      • @@ -8951,7 +10991,7 @@ limitations under the License.

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9161,14 +11201,14 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9378,41 +11418,56 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9621,10 +11676,209 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +Copyright (c) 2015-2022 Amod Malviya
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        + +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                      Apache License
                                 Version 2.0, January 2004
        @@ -9819,11 +12073,13 @@ APPENDIX: How to apply the Apache License to your work.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -10032,8 +12288,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -10242,7 +12497,217 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +APPENDIX: How to apply the Apache License to your work.
        +
        +   To apply the Apache License to your work, attach the following
        +   boilerplate notice, with the fields enclosed by brackets "[]"
        +   replaced with your own identifying information. (Don't include
        +   the brackets!)  The text should be enclosed in the appropriate
        +   comment syntax for the file format. We also recommend that a
        +   file or class name and description of purpose be included on the
        +   same "printed page" as the copyright notice for easier
        +   identification within third-party archives.
        +
        +Copyright [yyyy] [name of copyright owner]
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
           Copyright (c) 2017-present PyO3 Project and Contributors.  https://github.com/PyO3
         
        @@ -10439,7 +12904,220 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        +
        Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "{}"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright {yyyy} {name of copyright owner}
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
        Apache License
         Version 2.0, January 2004
        @@ -10718,135 +13396,182 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
         Version 2.0, January 2004
        @@ -11163,10 +13888,10 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Rust-chrono is dual-licensed under The MIT License [1] and
        -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
        +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
         contributors.
         
         Nota Bene: This is same as the Rust Project's own license.
        @@ -11405,6 +14130,40 @@ See the License for the specific language governing permissions and
         limitations under the License.
         ~~~~
         
        +
        +
      • +
      • +

        BSD 2-Clause "Simplified" License

        +

        Used by:

        + +
        Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are
        +met:
        +
        +1. Redistributions of source code must retain the above copyright
        +   notice, this list of conditions and the following disclaimer.
        +
        +2. Redistributions in binary form must reproduce the above copyright
        +   notice, this list of conditions and the following disclaimer in the
        +   documentation and/or other materials provided with the
        +   distribution.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
        +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
        +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
        +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
        +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
      • @@ -11439,6 +14198,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
      • + +
      • +

        BSD 2-Clause "Simplified" License

        +

        Used by:

        + +
        Copyright (c) 2017-2020
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are met:
        +
        +1. Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +2. Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
        +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
        +//
        +// Redistribution and use in source and binary forms, with or without
        +// modification, are permitted provided that the following conditions are met:
        +//
        +// 1. Redistributions of source code must retain the above copyright notice, this
        +//    list of conditions and the following disclaimer.
        +//
        +// 2. Redistributions in binary form must reproduce the above copyright notice,
        +//    this list of conditions and the following disclaimer in the documentation
        +//    and/or other materials provided with the distribution.
        +//
        +// 3. Neither the name of the copyright holder nor the names of its
        +//    contributors may be used to endorse or promote products derived from
        +//    this software without specific prior written permission.
        +//
        +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +/// The PUA code points special-cased in the GB18030 encoder.
        +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
        +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
        +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
        +];
        +
        +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
        +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
        +    [0xA6, 0xD9],
        +    [0xA6, 0xDA],
        +    [0xA6, 0xDB],
        +    [0xA6, 0xDC],
        +    [0xA6, 0xDD],
        +    [0xA6, 0xDE],
        +    [0xA6, 0xDF],
        +    [0xA6, 0xEC],
        +    [0xA6, 0xED],
        +    [0xA6, 0xF3],
        +    [0xFE, 0x59],
        +    [0xFE, 0x61],
        +    [0xFE, 0x66],
        +    [0xFE, 0x67],
        +    [0xFE, 0x6D],
        +    [0xFE, 0x7E],
        +    [0xFE, 0x90],
        +    [0xFE, 0xA0],
        +];
         
      • @@ -11446,6 +14298,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

        Used by:

        BSD 3-Clause License
         
        @@ -11482,10 +14335,88 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        +
        BSD 3-Clause License
        +
        +Copyright (c) 2026, Alexandre Bury
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are met:
        +
        +1. Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        +2. Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        +3. Neither the name of the copyright holder nor the names of its
        +   contributors may be used to endorse or promote products derived from
        +   this software without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        BSD License
        +
        +For Zstandard software
        +
        +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without modification,
        +are permitted provided that the following conditions are met:
        +
        + * Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        + * Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        + * Neither the name Facebook, nor Meta, nor the names of its contributors may
        +   be used to endorse or promote products derived from this software without
        +   specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        +
        Copyright (c) 2001, Dr Martin Porter
         Copyright (c) 2004,2005, Richard Boulton
        +Copyright (c) 2013, Yoshiki Shibukawa
        +Copyright (c) 2006-2025, Olly Betts
         All rights reserved.
         
         Redistribution and use in source and binary forms, with or without
        @@ -11510,16 +14441,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
         LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
         ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
         (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
      • BSD 3-Clause "New" or "Revised" License

        Used by:

        Copyright (c) 2016 Dropbox, Inc.
         All rights reserved.
        @@ -11576,8 +14507,53 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        +
        Copyright (c) 2026, frostem contributors
        +Copyright (c) 2001, Dr Martin Porter
        +Copyright (c) 2004,2005, Richard Boulton
        +Copyright (c) 2013, Yoshiki Shibukawa
        +Copyright (c) 2006-2025, Olly Betts
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions
        +are met:
        +
        +  1. Redistributions of source code must retain the above copyright notice,
        +     this list of conditions and the following disclaimer.
        +  2. Redistributions in binary form must reproduce the above copyright notice,
        +     this list of conditions and the following disclaimer in the documentation
        +     and/or other materials provided with the distribution.
        +  3. Neither the name of the Snowball project nor the names of its contributors
        +     may be used to endorse or promote products derived from this software
        +     without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        +
        Copyright (c) <year> <owner>. 
         
        @@ -11624,13 +14600,53 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
         CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
         OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
         OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        The auto-generated bindings are under the 3-clause BSD license:
        +
        +BSD License
        +
        +For Zstandard software
        +
        +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without modification,
        +are permitted provided that the following conditions are met:
        +
        + * Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        + * Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        + * Neither the name Facebook, nor Meta, nor the names of its contributors may
        +   be used to endorse or promote products derived from this software without
        +   specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
      • Boost Software License 1.0

        Used by:

        Boost Software License - Version 1.0 - August 17th, 2003
         
        @@ -11784,13 +14800,405 @@ express Statement of Purpose.
          d. Affirmer understands and acknowledges that Creative Commons is not a
             party to this document and has no duty or obligation with respect to
             this CC0 or use of the Work.
        +
        +
      • +
      • +

        Common Development and Distribution License 1.0

        +

        Used by:

        + +
        Unless otherwise noted, all files in this distribution are released
        +under the Common Development and Distribution License (CDDL).
        +Exceptions are noted within the associated source files.
        +
        +--------------------------------------------------------------------
        +
        +
        +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
        +
        +1. Definitions.
        +
        +    1.1. "Contributor" means each individual or entity that creates
        +         or contributes to the creation of Modifications.
        +
        +    1.2. "Contributor Version" means the combination of the Original
        +         Software, prior Modifications used by a Contributor (if any),
        +         and the Modifications made by that particular Contributor.
        +
        +    1.3. "Covered Software" means (a) the Original Software, or (b)
        +         Modifications, or (c) the combination of files containing
        +         Original Software with files containing Modifications, in
        +         each case including portions thereof.
        +
        +    1.4. "Executable" means the Covered Software in any form other
        +         than Source Code.
        +
        +    1.5. "Initial Developer" means the individual or entity that first
        +         makes Original Software available under this License.
        +
        +    1.6. "Larger Work" means a work which combines Covered Software or
        +         portions thereof with code not governed by the terms of this
        +         License.
        +
        +    1.7. "License" means this document.
        +
        +    1.8. "Licensable" means having the right to grant, to the maximum
        +         extent possible, whether at the time of the initial grant or
        +         subsequently acquired, any and all of the rights conveyed
        +         herein.
        +
        +    1.9. "Modifications" means the Source Code and Executable form of
        +         any of the following:
        +
        +        A. Any file that results from an addition to, deletion from or
        +           modification of the contents of a file containing Original
        +           Software or previous Modifications;
        +
        +        B. Any new file that contains any part of the Original
        +           Software or previous Modifications; or
        +
        +        C. Any new file that is contributed or otherwise made
        +           available under the terms of this License.
        +
        +    1.10. "Original Software" means the Source Code and Executable
        +          form of computer software code that is originally released
        +          under this License.
        +
        +    1.11. "Patent Claims" means any patent claim(s), now owned or
        +          hereafter acquired, including without limitation, method,
        +          process, and apparatus claims, in any patent Licensable by
        +          grantor.
        +
        +    1.12. "Source Code" means (a) the common form of computer software
        +          code in which modifications are made and (b) associated
        +          documentation included in or with such code.
        +
        +    1.13. "You" (or "Your") means an individual or a legal entity
        +          exercising rights under, and complying with all of the terms
        +          of, this License.  For legal entities, "You" includes any
        +          entity which controls, is controlled by, or is under common
        +          control with You.  For purposes of this definition,
        +          "control" means (a) the power, direct or indirect, to cause
        +          the direction or management of such entity, whether by
        +          contract or otherwise, or (b) ownership of more than fifty
        +          percent (50%) of the outstanding shares or beneficial
        +          ownership of such entity.
        +
        +2. License Grants.
        +
        +    2.1. The Initial Developer Grant.
        +
        +    Conditioned upon Your compliance with Section 3.1 below and
        +    subject to third party intellectual property claims, the Initial
        +    Developer hereby grants You a world-wide, royalty-free,
        +    non-exclusive license:
        +
        +        (a) under intellectual property rights (other than patent or
        +            trademark) Licensable by Initial Developer, to use,
        +            reproduce, modify, display, perform, sublicense and
        +            distribute the Original Software (or portions thereof),
        +            with or without Modifications, and/or as part of a Larger
        +            Work; and
        +
        +        (b) under Patent Claims infringed by the making, using or
        +            selling of Original Software, to make, have made, use,
        +            practice, sell, and offer for sale, and/or otherwise
        +            dispose of the Original Software (or portions thereof).
        +
        +        (c) The licenses granted in Sections 2.1(a) and (b) are
        +            effective on the date Initial Developer first distributes
        +            or otherwise makes the Original Software available to a
        +            third party under the terms of this License.
        +
        +        (d) Notwithstanding Section 2.1(b) above, no patent license is
        +            granted: (1) for code that You delete from the Original
        +            Software, or (2) for infringements caused by: (i) the
        +            modification of the Original Software, or (ii) the
        +            combination of the Original Software with other software
        +            or devices.
        +
        +    2.2. Contributor Grant.
        +
        +    Conditioned upon Your compliance with Section 3.1 below and
        +    subject to third party intellectual property claims, each
        +    Contributor hereby grants You a world-wide, royalty-free,
        +    non-exclusive license:
        +
        +        (a) under intellectual property rights (other than patent or
        +            trademark) Licensable by Contributor to use, reproduce,
        +            modify, display, perform, sublicense and distribute the
        +            Modifications created by such Contributor (or portions
        +            thereof), either on an unmodified basis, with other
        +            Modifications, as Covered Software and/or as part of a
        +            Larger Work; and
        +
        +        (b) under Patent Claims infringed by the making, using, or
        +            selling of Modifications made by that Contributor either
        +            alone and/or in combination with its Contributor Version
        +            (or portions of such combination), to make, use, sell,
        +            offer for sale, have made, and/or otherwise dispose of:
        +            (1) Modifications made by that Contributor (or portions
        +            thereof); and (2) the combination of Modifications made by
        +            that Contributor with its Contributor Version (or portions
        +            of such combination).
        +
        +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
        +            effective on the date Contributor first distributes or
        +            otherwise makes the Modifications available to a third
        +            party.
        +
        +        (d) Notwithstanding Section 2.2(b) above, no patent license is
        +            granted: (1) for any code that Contributor has deleted
        +            from the Contributor Version; (2) for infringements caused
        +            by: (i) third party modifications of Contributor Version,
        +            or (ii) the combination of Modifications made by that
        +            Contributor with other software (except as part of the
        +            Contributor Version) or other devices; or (3) under Patent
        +            Claims infringed by Covered Software in the absence of
        +            Modifications made by that Contributor.
        +
        +3. Distribution Obligations.
        +
        +    3.1. Availability of Source Code.
        +
        +    Any Covered Software that You distribute or otherwise make
        +    available in Executable form must also be made available in Source
        +    Code form and that Source Code form must be distributed only under
        +    the terms of this License.  You must include a copy of this
        +    License with every copy of the Source Code form of the Covered
        +    Software You distribute or otherwise make available.  You must
        +    inform recipients of any such Covered Software in Executable form
        +    as to how they can obtain such Covered Software in Source Code
        +    form in a reasonable manner on or through a medium customarily
        +    used for software exchange.
        +
        +    3.2. Modifications.
        +
        +    The Modifications that You create or to which You contribute are
        +    governed by the terms of this License.  You represent that You
        +    believe Your Modifications are Your original creation(s) and/or
        +    You have sufficient rights to grant the rights conveyed by this
        +    License.
        +
        +    3.3. Required Notices.
        +
        +    You must include a notice in each of Your Modifications that
        +    identifies You as the Contributor of the Modification.  You may
        +    not remove or alter any copyright, patent or trademark notices
        +    contained within the Covered Software, or any notices of licensing
        +    or any descriptive text giving attribution to any Contributor or
        +    the Initial Developer.
        +
        +    3.4. Application of Additional Terms.
        +
        +    You may not offer or impose any terms on any Covered Software in
        +    Source Code form that alters or restricts the applicable version
        +    of this License or the recipients' rights hereunder.  You may
        +    choose to offer, and to charge a fee for, warranty, support,
        +    indemnity or liability obligations to one or more recipients of
        +    Covered Software.  However, you may do so only on Your own behalf,
        +    and not on behalf of the Initial Developer or any Contributor.
        +    You must make it absolutely clear that any such warranty, support,
        +    indemnity or liability obligation is offered by You alone, and You
        +    hereby agree to indemnify the Initial Developer and every
        +    Contributor for any liability incurred by the Initial Developer or
        +    such Contributor as a result of warranty, support, indemnity or
        +    liability terms You offer.
        +
        +    3.5. Distribution of Executable Versions.
        +
        +    You may distribute the Executable form of the Covered Software
        +    under the terms of this License or under the terms of a license of
        +    Your choice, which may contain terms different from this License,
        +    provided that You are in compliance with the terms of this License
        +    and that the license for the Executable form does not attempt to
        +    limit or alter the recipient's rights in the Source Code form from
        +    the rights set forth in this License.  If You distribute the
        +    Covered Software in Executable form under a different license, You
        +    must make it absolutely clear that any terms which differ from
        +    this License are offered by You alone, not by the Initial
        +    Developer or Contributor.  You hereby agree to indemnify the
        +    Initial Developer and every Contributor for any liability incurred
        +    by the Initial Developer or such Contributor as a result of any
        +    such terms You offer.
        +
        +    3.6. Larger Works.
        +
        +    You may create a Larger Work by combining Covered Software with
        +    other code not governed by the terms of this License and
        +    distribute the Larger Work as a single product.  In such a case,
        +    You must make sure the requirements of this License are fulfilled
        +    for the Covered Software.
        +
        +4. Versions of the License.
        +
        +    4.1. New Versions.
        +
        +    Sun Microsystems, Inc. is the initial license steward and may
        +    publish revised and/or new versions of this License from time to
        +    time.  Each version will be given a distinguishing version number.
        +    Except as provided in Section 4.3, no one other than the license
        +    steward has the right to modify this License.
        +
        +    4.2. Effect of New Versions.
        +
        +    You may always continue to use, distribute or otherwise make the
        +    Covered Software available under the terms of the version of the
        +    License under which You originally received the Covered Software.
        +    If the Initial Developer includes a notice in the Original
        +    Software prohibiting it from being distributed or otherwise made
        +    available under any subsequent version of the License, You must
        +    distribute and make the Covered Software available under the terms
        +    of the version of the License under which You originally received
        +    the Covered Software.  Otherwise, You may also choose to use,
        +    distribute or otherwise make the Covered Software available under
        +    the terms of any subsequent version of the License published by
        +    the license steward.
        +
        +    4.3. Modified Versions.
        +
        +    When You are an Initial Developer and You want to create a new
        +    license for Your Original Software, You may create and use a
        +    modified version of this License if You: (a) rename the license
        +    and remove any references to the name of the license steward
        +    (except to note that the license differs from this License); and
        +    (b) otherwise make it clear that the license contains terms which
        +    differ from this License.
        +
        +5. DISCLAIMER OF WARRANTY.
        +
        +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
        +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
        +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
        +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
        +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
        +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
        +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
        +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
        +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
        +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
        +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
        +    DISCLAIMER.
        +
        +6. TERMINATION.
        +
        +    6.1. This License and the rights granted hereunder will terminate
        +    automatically if You fail to comply with terms herein and fail to
        +    cure such breach within 30 days of becoming aware of the breach.
        +    Provisions which, by their nature, must remain in effect beyond
        +    the termination of this License shall survive.
        +
        +    6.2. If You assert a patent infringement claim (excluding
        +    declaratory judgment actions) against Initial Developer or a
        +    Contributor (the Initial Developer or Contributor against whom You
        +    assert such claim is referred to as "Participant") alleging that
        +    the Participant Software (meaning the Contributor Version where
        +    the Participant is a Contributor or the Original Software where
        +    the Participant is the Initial Developer) directly or indirectly
        +    infringes any patent, then any and all rights granted directly or
        +    indirectly to You by such Participant, the Initial Developer (if
        +    the Initial Developer is not the Participant) and all Contributors
        +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
        +    notice from Participant terminate prospectively and automatically
        +    at the expiration of such 60 day notice period, unless if within
        +    such 60 day period You withdraw Your claim with respect to the
        +    Participant Software against such Participant either unilaterally
        +    or pursuant to a written agreement with Participant.
        +
        +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
        +    all end user licenses that have been validly granted by You or any
        +    distributor hereunder prior to termination (excluding licenses
        +    granted to You by any distributor) shall survive termination.
        +
        +7. LIMITATION OF LIABILITY.
        +
        +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
        +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
        +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
        +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
        +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
        +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
        +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
        +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
        +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
        +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
        +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
        +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
        +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
        +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
        +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
        +    APPLY TO YOU.
        +
        +8. U.S. GOVERNMENT END USERS.
        +
        +    The Covered Software is a "commercial item," as that term is
        +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
        +    computer software" (as that term is defined at 48
        +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
        +    documentation" as such terms are used in 48 C.F.R. 12.212
        +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
        +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
        +    U.S. Government End Users acquire Covered Software with only those
        +    rights set forth herein.  This U.S. Government Rights clause is in
        +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
        +    provision that addresses Government rights in computer software
        +    under this License.
        +
        +9. MISCELLANEOUS.
        +
        +    This License represents the complete agreement concerning subject
        +    matter hereof.  If any provision of this License is held to be
        +    unenforceable, such provision shall be reformed only to the extent
        +    necessary to make it enforceable.  This License shall be governed
        +    by the law of the jurisdiction specified in a notice contained
        +    within the Original Software (except to the extent applicable law,
        +    if any, provides otherwise), excluding such jurisdiction's
        +    conflict-of-law provisions.  Any litigation relating to this
        +    License shall be subject to the jurisdiction of the courts located
        +    in the jurisdiction and venue specified in a notice contained
        +    within the Original Software, with the losing party responsible
        +    for costs, including, without limitation, court costs and
        +    reasonable attorneys' fees and expenses.  The application of the
        +    United Nations Convention on Contracts for the International Sale
        +    of Goods is expressly excluded.  Any law or regulation which
        +    provides that the language of a contract shall be construed
        +    against the drafter shall not apply to this License.  You agree
        +    that You alone are responsible for compliance with the United
        +    States export administration regulations (and the export control
        +    laws and regulation of any other countries) when You use,
        +    distribute or otherwise make available any Covered Software.
        +
        +10. RESPONSIBILITY FOR CLAIMS.
        +
        +    As between Initial Developer and the Contributors, each party is
        +    responsible for claims and damages arising, directly or
        +    indirectly, out of its utilization of rights under this License
        +    and You agree to work with Initial Developer and Contributors to
        +    distribute such responsibility on an equitable basis.  Nothing
        +    herein is intended or shall be deemed to constitute any admission
        +    of liability.
        +
        +--------------------------------------------------------------------
        +
        +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
        +DISTRIBUTION LICENSE (CDDL)
        +
        +For Covered Software in this distribution, this License shall
        +be governed by the laws of the State of California (excluding
        +conflict-of-law provisions).
        +
        +Any litigation relating to this License shall be subject to the
        +jurisdiction of the Federal Courts of the Northern District of
        +California and the state courts of the State of California, with
        +venue lying in Santa Clara County, California.
         
      • Community Data License Agreement Permissive 2.0

        Used by:

        # Community Data License Agreement - Permissive - Version 2.0
         
        @@ -11853,6 +15261,88 @@ agreement.
         5.4. "Results" means any outcome obtained by computational analysis
         of Data, including for example machine learning models and models'
         insights.
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        /* Copyright (c) 2014, Intel Corporation.
        + *
        + * Permission to use, copy, modify, and/or distribute this software for any
        + * purpose with or without fee is hereby granted, provided that the above
        + * copyright notice and this permission notice appear in all copies.
        + *
        + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
        +
        +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +
        +#include "../../limbs/limbs.h"
        +
        +#define P384_LIMBS (384u / LIMB_BITS)
        +
        +typedef struct {
        +  Limb X[P384_LIMBS];
        +  Limb Y[P384_LIMBS];
        +  Limb Z[P384_LIMBS];
        +} P384_POINT;
        +
        +typedef struct {
        +  Limb X[P384_LIMBS];
        +  Limb Y[P384_LIMBS];
        +} P384_POINT_AFFINE;
        +
        +
        +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2015-2016 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! EdDSA Signatures.
        +
        +use super::ops::ELEM_LEN;
        +use crate::digest;
        +
        +pub mod signing;
        +pub mod verification;
        +
        +/// The length of an Ed25519 public key.
        +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
        +
        +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
        +    let mut ctx = digest::Context::new(&digest::SHA512);
        +    ctx.update(signature_r);
        +    ctx.update(public_key);
        +    ctx.update(msg);
        +    ctx.finish()
        +}
         
      • @@ -11880,29 +15370,44 @@ insights.

        ISC License

        Used by:

        -
        // Copyright 2021 Brian Smith.
        +                
        // Copyright 2015-2022 Brian Smith.
         //
         // Permission to use, copy, modify, and/or distribute this software for any
         // purpose with or without fee is hereby granted, provided that the above
         // copyright notice and this permission notice appear in all copies.
         //
        -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
         // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
        -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
        -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
        -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
        -#[test]
        -fn cert_without_extensions_test() {
        -    // Check the certificate is valid with
        -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
        -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
        +use crate::limb::Limb;
         
        -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
        +#[derive(Clone, Copy)]
        +#[repr(transparent)]
        +pub struct N0([Limb; 2]);
        +
        +impl N0 {
        +    #[cfg(feature = "alloc")]
        +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
        +
        +    #[inline]
        +    pub const fn precalculated(n0: u64) -> Self {
        +        #[cfg(target_pointer_width = "64")]
        +        {
        +            Self([n0, 0])
        +        }
        +
        +        #[cfg(target_pointer_width = "32")]
        +        {
        +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
        +        }
        +    }
         }
         
      • @@ -11910,21 +15415,372 @@ fn cert_without_extensions_test() {

        ISC License

        Used by:

        -
        Copyright (c) 2017 Adam Wick
        +                
        // Copyright 2015-2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
        -Permission to use, copy, modify, and/or distribute this software for any purpose
        -with or without fee is hereby granted, provided that the above copyright notice
        -and this permission notice appear in all copies.
        +use crate::{bb, error};
         
        -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
        -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
        -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
        -THIS SOFTWARE.
        +#[deprecated(
        +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
        +)]
        +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
        +    bb::verify_slices_are_equal(a, b)
        +}
        +
        + +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2016 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Elliptic curve operations and schemes using Curve25519.
        +
        +pub mod ed25519;
        +
        +pub mod x25519;
        +
        +mod ops;
        +mod scalar;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2016-2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +use crate::error::{KeyRejected, Unspecified};
        +
        +impl From<untrusted::EndOfInput> for Unspecified {
        +    fn from(source: untrusted::EndOfInput) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +impl From<core::array::TryFromSliceError> for Unspecified {
        +    fn from(source: core::array::TryFromSliceError) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +impl From<KeyRejected> for Unspecified {
        +    fn from(source: KeyRejected) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2018 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Serialization and deserialization.
        +
        +#[doc(hidden)]
        +pub mod der;
        +
        +#[cfg(feature = "alloc")]
        +mod writer;
        +
        +#[cfg(feature = "alloc")]
        +pub(crate) mod der_writer;
        +
        +pub(crate) mod positive;
        +
        +pub use self::positive::Positive;
        +
        +#[cfg(feature = "alloc")]
        +pub(crate) use self::writer::TooLongError;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2019-2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +use super::BlockLen;
        +
        +pub(super) use self::{
        +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
        +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
        +};
        +
        +pub(super) const CHAINING_WORDS: usize = 8;
        +
        +#[cfg(any(
        +    all(target_arch = "aarch64", target_endian = "little"),
        +    all(target_arch = "arm", target_endian = "little"),
        +    target_arch = "x86_64"
        +))]
        +#[macro_use]
        +mod ffi;
        +
        +pub(super) mod fallback;
        +mod sha2_32;
        +mod sha2_64;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
        +#[allow(dead_code)]
        +#[inline(always)]
        +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
        +    r
        +}
        +
        +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
        +#[allow(dead_code)]
        +#[inline(always)]
        +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
        +    r
        +}
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Integration tests for non-public APIs.
        +
        +mod bits_tests;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +pub use self::{
        +    array::Array,
        +    base::{IndexError, Overlapping},
        +    partial_block::PartialBlock,
        +};
        +
        +mod array;
        +mod base;
        +mod partial_block;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
        +
        +pub(in super::super) mod mont;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +#![cfg(target_arch = "x86_64")]
        +
        +pub(in super::super::super) mod mont;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +mod storage;
        +
        +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +pub(super) mod aarch64;
        +pub(super) mod x86_64;
         
      • @@ -11952,7 +15808,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

        ISC License

        Used by:

        Except as otherwise noted, this project is licensed under the following
         (ISC-style) terms:
        @@ -11979,12 +15835,12 @@ third-party/chromium/LICENSE.
                         

        ISC License

        Used by:

        ISC License
         
         Copyright (c) 2016, Mapbox
        -Copyright (c) 2018, Tree Cricket
        +Copyright (c) 2023, Taku Fukada
         
         Permission to use, copy, modify, and/or distribute this software for any purpose
         with or without fee is hereby granted, provided that the above copyright notice
        @@ -11997,13 +15853,603 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
         OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
         TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
         THIS SOFTWARE.
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        ISC License:
        +
        +Copyright (c) 2004-2010 by Internet Systems Consortium, Inc. ("ISC")
        +Copyright (c) 1995-2003 by Internet Software Consortium
        +
        +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
        +
        +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
      • MIT License

        Used by:

        +
                                          MIT License
        +
        +Copyright 2024 Antoine Catton
        +Copyright 2016-2024 David Tolnay
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        # 3rd Party Notices
        +
        +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
        +
        +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
        +
        +    tectonic_cfg_support is licensed under the MIT License.
        +
        +    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.
        +---
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Codegen exports used by `tonic-build`.
        +
        +pub use async_trait::async_trait;
        +pub use tokio_stream;
        +
        +pub use std::future::Future;
        +pub use std::pin::Pin;
        +pub use std::sync::Arc;
        +pub use std::task::{Context, Poll};
        +pub use tower_service::Service;
        +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
        +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
        +pub use crate::extensions::GrpcMethod;
        +pub use crate::service::interceptor::InterceptedService;
        +pub use bytes::Bytes;
        +pub use http;
        +pub use http_body::Body;
        +
        +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
        +pub type BoxStream<T> =
        +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Utilities for using Tower services with Tonic.
        +
        +pub mod interceptor;
        +pub(crate) mod layered;
        +#[cfg(feature = "router")]
        +pub(crate) mod router;
        +
        +#[doc(inline)]
        +pub use self::interceptor::{Interceptor, InterceptorLayer};
        +pub use self::layered::{LayerExt, Layered};
        +#[doc(inline)]
        +#[cfg(feature = "router")]
        +pub use self::router::{Routes, RoutesBuilder};
        +#[cfg(feature = "router")]
        +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
        +
        +pub mod recover_error;
        +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Various utilities used throughout tonic.
        +
        +// some combinations of features might cause things here not to be used
        +#![allow(dead_code)]
        +
        +pub(crate) mod base64 {
        +    use base64::{
        +        alphabet,
        +        engine::{
        +            DecodePaddingMode,
        +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
        +        },
        +    };
        +
        +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
        +        &alphabet::STANDARD,
        +        GeneralPurposeConfig::new()
        +            .with_encode_padding(true)
        +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
        +    );
        +
        +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
        +        &alphabet::STANDARD,
        +        GeneralPurposeConfig::new()
        +            .with_encode_padding(false)
        +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
        +    );
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +/// A gRPC Method info extension.
        +#[derive(Debug, Clone)]
        +pub struct GrpcMethod<'a> {
        +    service: &'a str,
        +    method: &'a str,
        +}
        +
        +impl<'a> GrpcMethod<'a> {
        +    /// Create a new `GrpcMethod` extension.
        +    #[doc(hidden)]
        +    pub fn new(service: &'a str, method: &'a str) -> Self {
        +        Self { service, method }
        +    }
        +
        +    /// gRPC service name
        +    pub fn service(&self) -> &str {
        +        self.service
        +    }
        +    /// gRPC method name
        +    pub fn method(&self) -> &str {
        +        self.method
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +mod add_origin;
        +use self::add_origin::AddOrigin;
        +
        +mod user_agent;
        +use self::user_agent::UserAgent;
        +
        +mod reconnect;
        +use self::reconnect::Reconnect;
        +
        +mod connection;
        +pub(super) use self::connection::Connection;
        +
        +mod discover;
        +pub use self::discover::Change;
        +pub(super) use self::discover::DynamicServiceStream;
        +
        +mod io;
        +use self::io::BoxedIo;
        +
        +mod connector;
        +pub(crate) use self::connector::Connector;
        +
        +mod executor;
        +pub(super) use self::executor::{Executor, SharedExec};
        +
        +#[cfg(feature = "_tls-any")]
        +mod tls;
        +#[cfg(feature = "_tls-any")]
        +pub(super) use self::tls::TlsConnector;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +mod io;
        +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
        +
        +#[cfg(feature = "_tls-any")]
        +mod tls;
        +#[cfg(feature = "_tls-any")]
        +pub(crate) use self::tls::TlsAcceptor;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +pub(crate) mod grpc_timeout;
        +#[cfg(feature = "_tls-any")]
        +pub(crate) mod tls;
        +
        +pub(crate) use self::grpc_timeout::GrpcTimeout;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +use crate::transport::channel::BoxFuture;
        +use hyper_util::rt::TokioExecutor;
        +use std::{future::Future, sync::Arc};
        +
        +pub(crate) use hyper::rt::Executor;
        +
        +#[derive(Clone)]
        +pub(crate) struct SharedExec {
        +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
        +}
        +
        +impl SharedExec {
        +    pub(crate) fn new<E>(exec: E) -> Self
        +    where
        +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
        +    {
        +        Self {
        +            inner: Arc::new(exec),
        +        }
        +    }
        +
        +    pub(crate) fn tokio() -> Self {
        +        Self::new(TokioExecutor::new())
        +    }
        +}
        +
        +impl<F> Executor<F> for SharedExec
        +where
        +    F: Future<Output = ()> + Send + 'static,
        +{
        +    fn execute(&self, fut: F) {
        +        self.inner.execute(Box::pin(fut))
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +use super::Connected;
        +use std::sync::Arc;
        +
        +/// Connection info for Unix domain socket streams.
        +///
        +/// This type will be accessible through [request extensions][ext] if you're using
        +/// a unix stream.
        +///
        +/// See [Connected] for more details.
        +///
        +/// [ext]: crate::Request::extensions
        +#[derive(Clone, Debug)]
        +pub struct UdsConnectInfo {
        +    /// Peer address. This will be "unnamed" for client unix sockets.
        +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
        +    /// Process credentials for the unix socket.
        +    pub peer_cred: Option<tokio::net::unix::UCred>,
        +}
        +
        +impl Connected for tokio::net::UnixStream {
        +    type ConnectInfo = UdsConnectInfo;
        +
        +    fn connect_info(&self) -> Self::ConnectInfo {
        +        UdsConnectInfo {
        +            peer_addr: self.peer_addr().ok().map(Arc::new),
        +            peer_cred: self.peer_cred().ok(),
        +        }
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        // Copyright (c) 2019 Nuclear Furnace
        +//
        +// 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
         
        @@ -12030,7 +16476,7 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2014 Carl Lerche and other MIO contributors
         
        @@ -12057,7 +16503,6 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2014-2019 Geoffroy Couprie
        @@ -12086,9 +16531,36 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2014-2021 Sean McArthur
        +                
        Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright (c) 2014-2026 Sean McArthur
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -12113,34 +16585,8 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2014-2025 Sean McArthur
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2015 Jonathan Reem
         
        @@ -12173,7 +16619,7 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2015 steffengy
         
        @@ -12181,21 +16627,6 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         
         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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2016 Paul Masurel
        -
        -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.
         
      • @@ -12259,8 +16690,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

        MIT License

        Used by:

        Copyright (c) 2017 h2 authors
         
        @@ -12293,7 +16723,7 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2018 Carl Lerche
         
        @@ -12326,52 +16756,34 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2018 Paul Masurel
        +                
        Copyright (c) 2018 Tom Parker-Shemilt
         
        -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:
        +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 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.
        -
        +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.
      • MIT License

        Used by:

        -
        Copyright (c) 2018 by Quickwit, Inc. 
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2018-2019 Sean McArthur
         
        @@ -12462,7 +16874,7 @@ DEALINGS IN THE SOFTWARE.
                         

        Used by:

        Copyright (c) 2019 Carl Lerche
         
        @@ -12549,44 +16961,13 @@ SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019 Hyper Contributors
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2019 Tokio Contributors
         
        @@ -12621,7 +17002,7 @@ DEALINGS IN THE SOFTWARE.
                         
                         
        Copyright (c) 2019 Tower Contributors
         
        @@ -12654,10 +17035,9 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019-2021 Tower Contributors
        +                
        Copyright (c) 2019 axum Contributors
         
         Permission is hereby granted, free of charge, to any
         person obtaining a copy of this software and associated
        @@ -12688,9 +17068,10 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
        +                
        Copyright (c) 2019-2021 Tower Contributors
         
         Permission is hereby granted, free of charge, to any
         person obtaining a copy of this software and associated
        @@ -12754,7 +17135,68 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        +
        Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright (c) 2021 Metrics Contributors
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Copyright (c) 2023-2025 Sean McArthur
         
        @@ -12775,36 +17217,6 @@ 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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2024 by Quickwit Inc.
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2024-Present Paul Masurel
        -
        -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.
         
      • @@ -12812,6 +17224,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

        Used by:

        Copyright 2016 Nika Layzell
         
        @@ -12819,6 +17232,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         
         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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2019 gRPC authors.
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2020 David Koloski
        +
        +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.
         
      • @@ -12841,25 +17296,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

        MIT License

        Used by:

        -
        Includes portions of humantime
        -Copyright (c) 2016 The humantime Developers
        +                
        Copyright 2021 David Koloski
         
         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.
        -
        -
         
      • MIT License

        Used by:

        +
        Copyright 2023 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2023 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2024 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12882,6 +17385,65 @@ 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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2016 Michael Ma
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2016 fengcen
        +Copyright (c) 2019 svartalf
        +
        +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.
        +
      • MIT License

        @@ -12903,6 +17465,35 @@ 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. +
      • + +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2017 Denis Kurilenko
        +
        +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
        @@ -12975,9 +17566,41 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2017 Sam Rijs
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12993,6 +17616,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2018 Canop
        +
        +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
        @@ -13036,7 +17688,36 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2018 sgodwincs
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13065,7 +17746,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13094,36 +17775,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        -
        MIT License
        -
        -Copyright (c) 2019 Aeledfyr
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        MIT License
         
        @@ -13152,8 +17804,37 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2019 Kornel
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13182,7 +17863,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13236,6 +17917,40 @@ 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.
         
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2019–2025 axum Contributors
        +
        +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.
      • MIT License

        @@ -13270,7 +17985,24 @@ SOFTWARE.

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2020 Katharos Technology
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13288,6 +18020,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020 magiclen.org (Ron Li)
        +
        +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
        @@ -13317,6 +18078,93 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020-2022 Oliver Margetts
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020-2026 Nugine
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2021 Adel Prokurov
        +
        +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
        @@ -13346,6 +18194,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2022 Arthur Silva
        +
        +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
        @@ -13360,6 +18237,7 @@ SOFTWARE.
                         

        Used by:

        MIT License
         
        @@ -13375,6 +18253,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2022 Jeroen Van Der Donckt
        +
        +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
        @@ -13416,7 +18323,36 @@ SOFTWARE.

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2022 sarah
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13445,8 +18381,8 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13475,8 +18411,66 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2023 sarah
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2024 Spire Team
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13506,19 +18500,28 @@ SOFTWARE.
                         

        Used by:

        MIT License
        @@ -13545,9 +18548,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13576,7 +18579,99 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) [2021] [Marvin Countryman]
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Permission is hereby granted, free of charge, to any person obtaining
         a copy of this software and associated documentation files (the
        @@ -13602,12 +18697,42 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        The MIT License (MIT)
        +                
        Portions of this project are derived from atty, which bears the following
        +copyright notice and permission notice:
         
        -Copyright (c) 2014 Benjamin Sago
        -Copyright (c) 2021-2022 The Nushell Project Developers
        +Copyright (c) 2015-2019 Doug Tangren
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License
        +
        +Copyright 2015 The Fancy Regex Authors.
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13616,23 +18741,24 @@ 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 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.
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        +THE SOFTWARE.
         
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13655,13 +18781,63 @@ 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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Mathijs van de Nes
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Y. T. CHUNG
        +
        +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.
        +
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13689,21 +18865,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        The MIT License (MIT)
         
        -Copyright (c) 2015 Andrew Gallant
        +Copyright (c) 2015 
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13712,28 +18878,39 @@ 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 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.
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
         
      • MIT License

        Used by:

        The MIT License (MIT)
         
         Copyright (c) 2015 Andrew Gallant
        -Copyright (c) 2019 Paul Masurel
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13783,6 +18960,36 @@ 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.
         
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Carl Lerche + nix-rust Authors
        +
        +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.
         
      • @@ -13814,6 +19021,64 @@ 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. +
      • + +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Gerd Zellweger
        +
        +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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Guillaume Gomez
        +
        +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.
        +
         
      • @@ -13849,11 +19114,72 @@ SOFTWARE.

        MIT License

        Used by:

        The MIT License (MIT)
         
        -Copyright (c) 2015 Vincent Prouillet
        +Copyright (c) 2015 Markus Westerlind
        +
        +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.
        +
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Michael Sproul
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015-2020 the fiat-crypto authors (see
        +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13878,7 +19204,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13894,6 +19220,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2016 nabijaczleweli
        +
        +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
        @@ -13967,8 +19322,36 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        The MIT License (MIT)
        +
        +Copyright (c) 2019 Simon Heath
        +
        +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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        The MIT License (MIT)
         
        @@ -14035,6 +19418,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Benjamin Sago
        +Copyright (c) 2021-2022 The Nushell Project 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.
         
      • @@ -14099,8 +19512,9 @@ SOFTWARE.
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -14153,6 +19567,387 @@ 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.
        +
        + +
      • +

        Mozilla Public License 2.0

        +

        Used by:

        + +
        Mozilla Public License Version 2.0
        +==================================
        +
        +1. Definitions
        +--------------
        +
        +1.1. "Contributor"
        +    means each individual or legal entity that creates, contributes to
        +    the creation of, or owns Covered Software.
        +
        +1.2. "Contributor Version"
        +    means the combination of the Contributions of others (if any) used
        +    by a Contributor and that particular Contributor's Contribution.
        +
        +1.3. "Contribution"
        +    means Covered Software of a particular Contributor.
        +
        +1.4. "Covered Software"
        +    means Source Code Form to which the initial Contributor has attached
        +    the notice in Exhibit A, the Executable Form of such Source Code
        +    Form, and Modifications of such Source Code Form, in each case
        +    including portions thereof.
        +
        +1.5. "Incompatible With Secondary Licenses"
        +    means
        +
        +    (a) that the initial Contributor has attached the notice described
        +        in Exhibit B to the Covered Software; or
        +
        +    (b) that the Covered Software was made available under the terms of
        +        version 1.1 or earlier of the License, but not also under the
        +        terms of a Secondary License.
        +
        +1.6. "Executable Form"
        +    means any form of the work other than Source Code Form.
        +
        +1.7. "Larger Work"
        +    means a work that combines Covered Software with other material, in 
        +    a separate file or files, that is not Covered Software.
        +
        +1.8. "License"
        +    means this document.
        +
        +1.9. "Licensable"
        +    means having the right to grant, to the maximum extent possible,
        +    whether at the time of the initial grant or subsequently, any and
        +    all of the rights conveyed by this License.
        +
        +1.10. "Modifications"
        +    means any of the following:
        +
        +    (a) any file in Source Code Form that results from an addition to,
        +        deletion from, or modification of the contents of Covered
        +        Software; or
        +
        +    (b) any new file in Source Code Form that contains any Covered
        +        Software.
        +
        +1.11. "Patent Claims" of a Contributor
        +    means any patent claim(s), including without limitation, method,
        +    process, and apparatus claims, in any patent Licensable by such
        +    Contributor that would be infringed, but for the grant of the
        +    License, by the making, using, selling, offering for sale, having
        +    made, import, or transfer of either its Contributions or its
        +    Contributor Version.
        +
        +1.12. "Secondary License"
        +    means either the GNU General Public License, Version 2.0, the GNU
        +    Lesser General Public License, Version 2.1, the GNU Affero General
        +    Public License, Version 3.0, or any later versions of those
        +    licenses.
        +
        +1.13. "Source Code Form"
        +    means the form of the work preferred for making modifications.
        +
        +1.14. "You" (or "Your")
        +    means an individual or a legal entity exercising rights under this
        +    License. For legal entities, "You" includes any entity that
        +    controls, is controlled by, or is under common control with You. For
        +    purposes of this definition, "control" means (a) the power, direct
        +    or indirect, to cause the direction or management of such entity,
        +    whether by contract or otherwise, or (b) ownership of more than
        +    fifty percent (50%) of the outstanding shares or beneficial
        +    ownership of such entity.
        +
        +2. License Grants and Conditions
        +--------------------------------
        +
        +2.1. Grants
        +
        +Each Contributor hereby grants You a world-wide, royalty-free,
        +non-exclusive license:
        +
        +(a) under intellectual property rights (other than patent or trademark)
        +    Licensable by such Contributor to use, reproduce, make available,
        +    modify, display, perform, distribute, and otherwise exploit its
        +    Contributions, either on an unmodified basis, with Modifications, or
        +    as part of a Larger Work; and
        +
        +(b) under Patent Claims of such Contributor to make, use, sell, offer
        +    for sale, have made, import, and otherwise transfer either its
        +    Contributions or its Contributor Version.
        +
        +2.2. Effective Date
        +
        +The licenses granted in Section 2.1 with respect to any Contribution
        +become effective for each Contribution on the date the Contributor first
        +distributes such Contribution.
        +
        +2.3. Limitations on Grant Scope
        +
        +The licenses granted in this Section 2 are the only rights granted under
        +this License. No additional rights or licenses will be implied from the
        +distribution or licensing of Covered Software under this License.
        +Notwithstanding Section 2.1(b) above, no patent license is granted by a
        +Contributor:
        +
        +(a) for any code that a Contributor has removed from Covered Software;
        +    or
        +
        +(b) for infringements caused by: (i) Your and any other third party's
        +    modifications of Covered Software, or (ii) the combination of its
        +    Contributions with other software (except as part of its Contributor
        +    Version); or
        +
        +(c) under Patent Claims infringed by Covered Software in the absence of
        +    its Contributions.
        +
        +This License does not grant any rights in the trademarks, service marks,
        +or logos of any Contributor (except as may be necessary to comply with
        +the notice requirements in Section 3.4).
        +
        +2.4. Subsequent Licenses
        +
        +No Contributor makes additional grants as a result of Your choice to
        +distribute the Covered Software under a subsequent version of this
        +License (see Section 10.2) or under the terms of a Secondary License (if
        +permitted under the terms of Section 3.3).
        +
        +2.5. Representation
        +
        +Each Contributor represents that the Contributor believes its
        +Contributions are its original creation(s) or it has sufficient rights
        +to grant the rights to its Contributions conveyed by this License.
        +
        +2.6. Fair Use
        +
        +This License is not intended to limit any rights You have under
        +applicable copyright doctrines of fair use, fair dealing, or other
        +equivalents.
        +
        +2.7. Conditions
        +
        +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
        +in Section 2.1.
        +
        +3. Responsibilities
        +-------------------
        +
        +3.1. Distribution of Source Form
        +
        +All distribution of Covered Software in Source Code Form, including any
        +Modifications that You create or to which You contribute, must be under
        +the terms of this License. You must inform recipients that the Source
        +Code Form of the Covered Software is governed by the terms of this
        +License, and how they can obtain a copy of this License. You may not
        +attempt to alter or restrict the recipients' rights in the Source Code
        +Form.
        +
        +3.2. Distribution of Executable Form
        +
        +If You distribute Covered Software in Executable Form then:
        +
        +(a) such Covered Software must also be made available in Source Code
        +    Form, as described in Section 3.1, and You must inform recipients of
        +    the Executable Form how they can obtain a copy of such Source Code
        +    Form by reasonable means in a timely manner, at a charge no more
        +    than the cost of distribution to the recipient; and
        +
        +(b) You may distribute such Executable Form under the terms of this
        +    License, or sublicense it under different terms, provided that the
        +    license for the Executable Form does not attempt to limit or alter
        +    the recipients' rights in the Source Code Form under this License.
        +
        +3.3. Distribution of a Larger Work
        +
        +You may create and distribute a Larger Work under terms of Your choice,
        +provided that You also comply with the requirements of this License for
        +the Covered Software. If the Larger Work is a combination of Covered
        +Software with a work governed by one or more Secondary Licenses, and the
        +Covered Software is not Incompatible With Secondary Licenses, this
        +License permits You to additionally distribute such Covered Software
        +under the terms of such Secondary License(s), so that the recipient of
        +the Larger Work may, at their option, further distribute the Covered
        +Software under the terms of either this License or such Secondary
        +License(s).
        +
        +3.4. Notices
        +
        +You may not remove or alter the substance of any license notices
        +(including copyright notices, patent notices, disclaimers of warranty,
        +or limitations of liability) contained within the Source Code Form of
        +the Covered Software, except that You may alter any license notices to
        +the extent required to remedy known factual inaccuracies.
        +
        +3.5. Application of Additional Terms
        +
        +You may choose to offer, and to charge a fee for, warranty, support,
        +indemnity or liability obligations to one or more recipients of Covered
        +Software. However, You may do so only on Your own behalf, and not on
        +behalf of any Contributor. You must make it absolutely clear that any
        +such warranty, support, indemnity, or liability obligation is offered by
        +You alone, and You hereby agree to indemnify every Contributor for any
        +liability incurred by such Contributor as a result of warranty, support,
        +indemnity or liability terms You offer. You may include additional
        +disclaimers of warranty and limitations of liability specific to any
        +jurisdiction.
        +
        +4. Inability to Comply Due to Statute or Regulation
        +---------------------------------------------------
        +
        +If it is impossible for You to comply with any of the terms of this
        +License with respect to some or all of the Covered Software due to
        +statute, judicial order, or regulation then You must: (a) comply with
        +the terms of this License to the maximum extent possible; and (b)
        +describe the limitations and the code they affect. Such description must
        +be placed in a text file included with all distributions of the Covered
        +Software under this License. Except to the extent prohibited by statute
        +or regulation, such description must be sufficiently detailed for a
        +recipient of ordinary skill to be able to understand it.
        +
        +5. Termination
        +--------------
        +
        +5.1. The rights granted under this License will terminate automatically
        +if You fail to comply with any of its terms. However, if You become
        +compliant, then the rights granted under this License from a particular
        +Contributor are reinstated (a) provisionally, unless and until such
        +Contributor explicitly and finally terminates Your grants, and (b) on an
        +ongoing basis, if such Contributor fails to notify You of the
        +non-compliance by some reasonable means prior to 60 days after You have
        +come back into compliance. Moreover, Your grants from a particular
        +Contributor are reinstated on an ongoing basis if such Contributor
        +notifies You of the non-compliance by some reasonable means, this is the
        +first time You have received notice of non-compliance with this License
        +from such Contributor, and You become compliant prior to 30 days after
        +Your receipt of the notice.
        +
        +5.2. If You initiate litigation against any entity by asserting a patent
        +infringement claim (excluding declaratory judgment actions,
        +counter-claims, and cross-claims) alleging that a Contributor Version
        +directly or indirectly infringes any patent, then the rights granted to
        +You by any and all Contributors for the Covered Software under Section
        +2.1 of this License shall terminate.
        +
        +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
        +end user license agreements (excluding distributors and resellers) which
        +have been validly granted by You or Your distributors under this License
        +prior to termination shall survive termination.
        +
        +************************************************************************
        +*                                                                      *
        +*  6. Disclaimer of Warranty                                           *
        +*  -------------------------                                           *
        +*                                                                      *
        +*  Covered Software is provided under this License on an "as is"       *
        +*  basis, without warranty of any kind, either expressed, implied, or  *
        +*  statutory, including, without limitation, warranties that the       *
        +*  Covered Software is free of defects, merchantable, fit for a        *
        +*  particular purpose or non-infringing. The entire risk as to the     *
        +*  quality and performance of the Covered Software is with You.        *
        +*  Should any Covered Software prove defective in any respect, You     *
        +*  (not any Contributor) assume the cost of any necessary servicing,   *
        +*  repair, or correction. This disclaimer of warranty constitutes an   *
        +*  essential part of this License. No use of any Covered Software is   *
        +*  authorized under this License except under this disclaimer.         *
        +*                                                                      *
        +************************************************************************
        +
        +************************************************************************
        +*                                                                      *
        +*  7. Limitation of Liability                                          *
        +*  --------------------------                                          *
        +*                                                                      *
        +*  Under no circumstances and under no legal theory, whether tort      *
        +*  (including negligence), contract, or otherwise, shall any           *
        +*  Contributor, or anyone who distributes Covered Software as          *
        +*  permitted above, be liable to You for any direct, indirect,         *
        +*  special, incidental, or consequential damages of any character      *
        +*  including, without limitation, damages for lost profits, loss of    *
        +*  goodwill, work stoppage, computer failure or malfunction, or any    *
        +*  and all other commercial damages or losses, even if such party      *
        +*  shall have been informed of the possibility of such damages. This   *
        +*  limitation of liability shall not apply to liability for death or   *
        +*  personal injury resulting from such party's negligence to the       *
        +*  extent applicable law prohibits such limitation. Some               *
        +*  jurisdictions do not allow the exclusion or limitation of           *
        +*  incidental or consequential damages, so this exclusion and          *
        +*  limitation may not apply to You.                                    *
        +*                                                                      *
        +************************************************************************
        +
        +8. Litigation
        +-------------
        +
        +Any litigation relating to this License may be brought only in the
        +courts of a jurisdiction where the defendant maintains its principal
        +place of business and such litigation shall be governed by laws of that
        +jurisdiction, without reference to its conflict-of-law provisions.
        +Nothing in this Section shall prevent a party's ability to bring
        +cross-claims or counter-claims.
        +
        +9. Miscellaneous
        +----------------
        +
        +This License represents the complete agreement concerning the subject
        +matter hereof. If any provision of this License is held to be
        +unenforceable, such provision shall be reformed only to the extent
        +necessary to make it enforceable. Any law or regulation which provides
        +that the language of a contract shall be construed against the drafter
        +shall not be used to construe this License against a Contributor.
        +
        +10. Versions of the License
        +---------------------------
        +
        +10.1. New Versions
        +
        +Mozilla Foundation is the license steward. Except as provided in Section
        +10.3, no one other than the license steward has the right to modify or
        +publish new versions of this License. Each version will be given a
        +distinguishing version number.
        +
        +10.2. Effect of New Versions
        +
        +You may distribute the Covered Software under the terms of the version
        +of the License under which You originally received the Covered Software,
        +or under the terms of any subsequent version published by the license
        +steward.
        +
        +10.3. Modified Versions
        +
        +If you create software not governed by this License, and you want to
        +create a new license for such software, you may create and use a
        +modified version of this License if you rename the license and remove
        +any references to the name of the license steward (except to note that
        +such modified license differs from this License).
        +
        +10.4. Distributing Source Code Form that is Incompatible With Secondary
        +Licenses
        +
        +If You choose to distribute Source Code Form that is Incompatible With
        +Secondary Licenses under the terms of this version of the License, the
        +notice described in Exhibit B of this License must be attached.
        +
        +Exhibit A - Source Code Form License Notice
        +-------------------------------------------
        +
        +  This Source Code Form is subject to the terms of the Mozilla Public
        +  License, v. 2.0. If a copy of the MPL was not distributed with this
        +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
        +
        +If it is not possible or desirable to put the notice in a particular
        +file, then You may include the notice in a location (such as a LICENSE
        +file in a relevant directory) where a recipient would be likely to look
        +for such a notice.
        +
        +You may add additional accurate notices of copyright ownership.
        +
        +Exhibit B - "Incompatible With Secondary Licenses" Notice
        +---------------------------------------------------------
        +
        +  This Source Code Form is "Incompatible With Secondary Licenses", as
        +  defined by the Mozilla Public License, v. 2.0.
         
      • @@ -14540,7 +20335,7 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice

        Unicode License v3

        Used by:

        UNICODE LICENSE V3
         
        @@ -14587,24 +20382,28 @@ authorization of the copyright holder.
                         

        Unicode License v3

        Used by:

        UNICODE LICENSE V3
         
        @@ -14653,12 +20452,63 @@ SPDX-License-Identifier: Unicode-3.0
         Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
         ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
         
        +
      • +
      • +

        zlib License

        +

        Used by:

        + +
        Copyright (c) 2021 Matias Rodriguez.
        +
        +This software is provided 'as-is', without any express or implied
        +warranty. In no event will the authors be held liable for any damages
        +arising from the use of this software.
        +
        +Permission is granted to anyone to use this software for any purpose,
        +including commercial applications, and to alter it and redistribute it
        +freely, subject to the following restrictions:
        +
        +1. The origin of this software must not be misrepresented; you must not
        +   claim that you wrote the original software. If you use this software
        +   in a product, an acknowledgment in the product documentation would be
        +   appreciated but is not required.
        +2. Altered source versions must be plainly marked as such, and must not be
        +   misrepresented as being the original software.
        +3. This notice may not be removed or altered from any source distribution.
        +
      • +
      • +

        zlib License

        +

        Used by:

        + +
        Copyright (c) 2023 Matias Rodriguez.
        +
        +This software is provided 'as-is', without any express or implied
        +warranty. In no event will the authors be held liable for any damages
        +arising from the use of this software.
        +
        +Permission is granted to anyone to use this software for any purpose,
        +including commercial applications, and to alter it and redistribute it
        +freely, subject to the following restrictions:
        +
        +1. The origin of this software must not be misrepresented; you must not
        +   claim that you wrote the original software. If you use this software
        +   in a product, an acknowledgment in the product documentation would be
        +   appreciated but is not required.
        +2. Altered source versions must be plainly marked as such, and must not be
        +   misrepresented as being the original software.
        +3. This notice may not be removed or altered from any source distribution.
      • zlib License

        Used by:

        Copyright (c) 2024 Orson Peters
         
        diff --git a/python/benchmarks/bench_fetch_blobs_rss.py b/python/benchmarks/bench_fetch_blobs_rss.py
        new file mode 100644
        index 000000000..8281490f0
        --- /dev/null
        +++ b/python/benchmarks/bench_fetch_blobs_rss.py
        @@ -0,0 +1,183 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +"""Measure fetch_blobs RSS in a fresh client process against real HTTP.
        +
        +Run with the uv environment's Python. The server lives in a separate process so
        +payload generation and Arrow serialization are excluded from the client's RSS.
        +Each row contains 1 MiB; requests over the server's 64 MiB limit are split by the
        +SDK. Example: python benchmarks/bench_fetch_blobs_rss.py --rows 48 144
        +"""
        +
        +import argparse
        +import json
        +import resource
        +import subprocess
        +import sys
        +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
        +
        +
        +def serve(batch_rows, row_mib):
        +    import pyarrow as pa
        +
        +    payload = b"x" * (row_mib << 20)
        +
        +    class Handler(BaseHTTPRequestHandler):
        +        protocol_version = "HTTP/1.1"
        +
        +        def log_message(self, *args):
        +            pass
        +
        +        def respond(self, status, data, content_type="application/json"):
        +            self.send_response(status)
        +            self.send_header("Content-Type", content_type)
        +            self.send_header("Content-Length", str(len(data)))
        +            self.send_header("phalanx-version", "0.5.0")
        +            self.send_header("x-lancedb-version", "1")
        +            self.end_headers()
        +            for offset in range(0, len(data), 8192):
        +                self.wfile.write(data[offset : offset + 8192])
        +
        +        def do_POST(self):
        +            length = int(self.headers.get("Content-Length", 0))
        +            request_body = self.rfile.read(length)
        +            if self.path.endswith("/describe/"):
        +                self.do_GET()
        +                return
        +            body = json.loads(request_body)
        +            count = len(body["row_ids"])
        +            if count * row_mib > 64:
        +                self.respond(
        +                    400,
        +                    b"fetch_blobs accepts at most 67108864 total blob bytes",
        +                )
        +                return
        +            schema = pa.schema([pa.field("image", pa.large_binary())])
        +            sink = pa.BufferOutputStream()
        +            with pa.ipc.new_stream(sink, schema) as writer:
        +                for start in range(0, count, batch_rows):
        +                    array = pa.array(
        +                        [payload] * min(batch_rows, count - start),
        +                        type=pa.large_binary(),
        +                    )
        +                    writer.write_batch(pa.record_batch([array], schema=schema))
        +            self.respond(200, sink.getvalue(), "application/vnd.apache.arrow.stream")
        +
        +        def do_GET(self):
        +            if "/blob/image/" in self.path:
        +                start, end = map(int, self.headers["Range"][6:].split("-"))
        +                body = memoryview(payload)[start : end + 1]
        +                self.send_response(206)
        +                self.send_header("Content-Length", str(len(body)))
        +                self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
        +                self.send_header("x-lancedb-version", "1")
        +                self.end_headers()
        +                for offset in range(0, len(body), 8192):
        +                    self.wfile.write(body[offset : offset + 8192])
        +                return
        +            self.respond(
        +                200,
        +                json.dumps(
        +                    {
        +                        "table": "test",
        +                        "version": 1,
        +                        "schema": {"fields": []},
        +                    }
        +                ).encode(),
        +            )
        +
        +    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
        +    print(server.server_port, flush=True)
        +    server.serve_forever()
        +
        +
        +def client(port, rows, row_mib):
        +    import lancedb
        +
        +    db = lancedb.connect(
        +        "db://rss-test", api_key="test", host_override=f"http://127.0.0.1:{port}"
        +    )
        +    table = db.open_table("test")
        +    # Reset the Linux high-water mark after imports and connection setup.
        +    with open("/proc/self/clear_refs", "w") as reset:
        +        reset.write("5")
        +
        +    def memory_kib(field):
        +        with open("/proc/self/status") as status:
        +            return next(
        +                int(line.split()[1]) for line in status if line.startswith(field + ":")
        +            )
        +
        +    before = memory_kib("VmRSS")
        +    values = table.fetch_blobs("image", list(range(rows)))
        +    peak = memory_kib("VmHWM")
        +    assert len(values) == rows
        +    assert values.buffers()[2].size == rows * (row_mib << 20)
        +    # Inspect slices without copying the result to Python bytes.
        +    for i in (0, rows - 1):
        +        assert values.slice(i, 1).buffers()[2][i * (row_mib << 20)] == ord("x")
        +    print(
        +        json.dumps(
        +            {
        +                "rows": rows,
        +                "payload_mib": rows * row_mib,
        +                "baseline_rss_kib": before,
        +                "peak_rss_kib": peak,
        +                "peak_delta_kib": peak - before,
        +                "peak_delta_per_payload": (peak - before) / (rows * row_mib * 1024),
        +                "rusage_maxrss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
        +            }
        +        ),
        +        flush=True,
        +    )
        +
        +
        +def main():
        +    parser = argparse.ArgumentParser(description=__doc__)
        +    parser.add_argument("--rows", nargs="+", type=int, default=[48, 144])
        +    parser.add_argument("--batch-rows", type=int, default=48)
        +    parser.add_argument("--row-mib", type=int, default=1)
        +    parser.add_argument("--serve", action="store_true")
        +    parser.add_argument("--client", type=int)
        +    args = parser.parse_args()
        +    if args.serve:
        +        serve(args.batch_rows, args.row_mib)
        +    elif args.client is not None:
        +        client(args.client, args.rows[0], args.row_mib)
        +    else:
        +        server = subprocess.Popen(
        +            [
        +                sys.executable,
        +                __file__,
        +                "--serve",
        +                "--batch-rows",
        +                str(args.batch_rows),
        +                "--row-mib",
        +                str(args.row_mib),
        +            ],
        +            stdout=subprocess.PIPE,
        +            text=True,
        +        )
        +        try:
        +            port = server.stdout.readline().strip()
        +            for rows in args.rows:
        +                subprocess.run(
        +                    [
        +                        sys.executable,
        +                        __file__,
        +                        "--client",
        +                        port,
        +                        "--rows",
        +                        str(rows),
        +                        "--row-mib",
        +                        str(args.row_mib),
        +                    ],
        +                    check=True,
        +                )
        +        finally:
        +            server.terminate()
        +            server.wait()
        +
        +
        +if __name__ == "__main__":
        +    main()
        diff --git a/python/pyproject.toml b/python/pyproject.toml
        index a8005f973..b0fa12adc 100644
        --- a/python/pyproject.toml
        +++ b/python/pyproject.toml
        @@ -12,17 +12,17 @@ dependencies = [
             "tqdm>=4.27.0",
             "lance-namespace>=0.13.0"
         ]
        -description = "lancedb"
        +description = "Embedded database for vector, full-text and hybrid search on Lance tables"
         authors = [{ name = "LanceDB Devs", email = "dev@lancedb.com" }]
         license = { file = "LICENSE" }
         readme = "README.md"
        -requires-python = ">=3.10"
        +requires-python = ">=3.11"
         keywords = [
        -    "data-format",
        -    "data-science",
        -    "machine-learning",
        -    "arrow",
        -    "data-analytics",
        +    "lance",
        +    "vector-search",
        +    "full-text-search",
        +    "dataset",
        +    "versioning",
         ]
         classifiers = [
             "Development Status :: 3 - Alpha",
        @@ -33,7 +33,6 @@ classifiers = [
             "Programming Language :: Python",
             "Programming Language :: Python :: 3",
             "Programming Language :: Python :: 3 :: Only",
        -    "Programming Language :: Python :: 3.10",
             "Programming Language :: Python :: 3.11",
             "Programming Language :: Python :: 3.12",
             "Programming Language :: Python :: 3.13",
        @@ -46,7 +45,7 @@ repository = "https://github.com/lancedb/lancedb"
         [project.optional-dependencies]
         pylance = [
             # Keep the minimum in the bundled Lance major and compatible with tests below.
        -    "pylance>=15.0.0b3",
        +    "pylance>=16.0.0b2",
         ]
         # A library only needs the OpenTelemetry API; the application supplies and
         # configures the SDK (the actual exporter/reader). See
        @@ -56,17 +55,16 @@ tests = [
             "aiohttp>=3.9.0",
             "boto3>=1.28.57",
             "pandas>=1.4",
        +    "pillow>=13.0.0",
             "pytest>=7.0",
             "pytest-mock>=3.10",
             "pytest-asyncio>=0.21",
             "duckdb>=0.9.0",
             "pytz>=2023.3",
             "polars>=0.19, <=1.32.3",
        -    "pyarrow<25",
        +    "pyarrow>=16",
             "pyarrow-stubs>=16.0",
        -    # pylance 15.0.0b5+ has not published macOS wheels.
        -    "pylance==15.0.0b9; sys_platform != 'darwin'",
        -    "pylance==15.0.0b4; sys_platform == 'darwin'",
        +    "pylance==16.0.0b4",
             "requests>=2.31.0",
             "datafusion>=54,<55",
             "opentelemetry-sdk>=1.30.0",
        @@ -75,18 +73,17 @@ dev = [
             "ruff>=0.3.0",
             "pre-commit>=3.5.0",
             "pyright>=1.1.350",
        -    'typing-extensions>=4.0.0; python_version < "3.11"',
             "maturin>=1.10",
         ]
        -docs = ["mkdocs", "mkdocs-jupyter", "mkdocs-material", "mkdocstrings-python"]
        -clip = ["torch", "pillow>=12.1.1", "open-clip-torch"]
        -siglip = ["torch", "pillow>=12.1.1", "transformers>=4.41.0","sentencepiece"]
        +docs = ["mkdocs", "mkdocs-jupyter", "mkdocs-material>=9.8.2", "mkdocstrings[python]>=1.0.7,<2"]
        +clip = ["torch", "pillow>=13.0.0", "open-clip-torch"]
        +siglip = ["torch", "pillow>=13.0.0", "transformers>=4.41.0","sentencepiece"]
         embeddings = [
             "requests>=2.31.0",
             "openai>=1.6.1",
             "sentence-transformers>=2.2.0",
             "torch>=2.0.0",
        -    "pillow>=12.1.1",
        +    "pillow>=13.0.0",
             "open-clip-torch>=2.20.0",
             "cohere>=4.0",
             "colpali-engine>=0.3.10",
        diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py
        index 6ff0dd1ff..e368c985d 100644
        --- a/python/python/lancedb/__init__.py
        +++ b/python/python/lancedb/__init__.py
        @@ -3,6 +3,7 @@
         
         
         import os
        +import warnings
         from concurrent.futures import ThreadPoolExecutor
         from datetime import timedelta
         from typing import Dict, Optional, Union, Any, List, Iterable, Literal, TYPE_CHECKING
        @@ -16,9 +17,18 @@ __version__ = str(_Version(_native_version))
         
         from ._lancedb import connect as lancedb_connect
         from ._lancedb import FtsToken
        +from ._lancedb import (
        +    FunctionColumnAutoRefreshStatus as FunctionColumnAutoRefreshStatus,
        +)
        +from ._lancedb import (
        +    FunctionColumnLastRefreshJob as FunctionColumnLastRefreshJob,
        +)
        +from ._lancedb import FunctionColumnStatus as FunctionColumnStatus
        +from ._lancedb import (
        +    FunctionColumnVersionStatus as FunctionColumnVersionStatus,
        +)
         from ._lancedb import FunctionErrorFragment as FunctionErrorFragment
         from ._lancedb import FunctionErrorRecord as FunctionErrorRecord
        -from ._lancedb import FunctionErrors as FunctionErrors
         from ._lancedb import GpuClass as GpuClass
         from ._lancedb import RTEWriteSpec
         from ._lancedb import tokenize as _tokenize
        @@ -28,23 +38,34 @@ from .db import AsyncConnection, DBConnection, LanceDBConnection
         from .remote import ClientConfig
         from .remote.db import RemoteDBConnection
         from .expr import Expr, col, lit, func
        -from .schema import blob, vector
        +from .schema import BasePath, blob, blob_uri_array, vector
         from ._blob_reader import BlobReader as BlobReader
        -from .job import AsyncJob, Job
        +from .job import AsyncJob, Job, JobState
         from .sql import AsyncQuery as AsyncSqlQuery
         from .sql import Query as SqlQuery
         from .sql import QueryDescription
         from .functions import (
        +    FunctionErrors as FunctionErrors,
        +    AsyncFunctionErrors as AsyncFunctionErrors,
        +    FunctionErrorGroup as FunctionErrorGroup,
        +    FunctionProvenance as FunctionProvenance,
        +    FunctionValueProvenance as FunctionValueProvenance,
             AssignmentMapping as AssignmentMapping,
             FunctionArtifactRequest as FunctionArtifactRequest,
             FunctionApplication as FunctionApplication,
             FunctionBinding as FunctionBinding,
        +    FunctionDefinition as FunctionDefinition,
        +    FunctionEnvironment as FunctionEnvironment,
             FunctionRegistrationRequest as FunctionRegistrationRequest,
        +    FunctionRetryPolicy as FunctionRetryPolicy,
             FunctionVersion as FunctionVersion,
             HuggingFaceModel as HuggingFaceModel,
             PythonRuntimeSpec as PythonRuntimeSpec,
        +    ResolvedEnvironment as ResolvedEnvironment,
        +    ResolvedEnvironmentProvenance as ResolvedEnvironmentProvenance,
        +    ResolvedPackage as ResolvedPackage,
             RefreshColumnResult as RefreshColumnResult,
        -    UdfDefinition as UdfDefinition,
        +    function as function,
             udf as udf,
         )
         from .secrets import EnvVarSecret as EnvVarSecret
        @@ -58,6 +79,7 @@ from .materialized_view import (
         from .view import ViewDescription as ViewDescription
         from .graph import PropertyGraph, PropertyGraphDescription
         from .table import AsyncTable, CompactionOptions, Table
        +from .query import ColumnOrdering as ColumnOrdering
         from .types import BaseTokenizerType
         from ._lancedb import Session
         from .namespace import (
        @@ -77,6 +99,7 @@ from .catalog import (
         
         if TYPE_CHECKING:
             from lance.blob import BlobType as BlobType
        +    from .functions import UdfDefinition as UdfDefinition
         
         
         def __getattr__(name: str):
        @@ -85,6 +108,13 @@ def __getattr__(name: str):
         
                 globals()["BlobType"] = BlobType
                 return BlobType
        +    if name == "UdfDefinition":
        +        from . import functions
        +
        +        warnings.warn(
        +            functions.UDF_DEFINITION_DEPRECATION, DeprecationWarning, stacklevel=2
        +        )
        +        return functions.FunctionDefinition
             raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
         
         
        @@ -649,6 +679,15 @@ __all__ = [
             "AsyncTable",
             "CompactionOptions",
             "FtsToken",
        +    "FunctionColumnAutoRefreshStatus",
        +    "FunctionColumnLastRefreshJob",
        +    "FunctionColumnStatus",
        +    "FunctionColumnVersionStatus",
        +    "FunctionErrors",
        +    "AsyncFunctionErrors",
        +    "FunctionErrorGroup",
        +    "FunctionProvenance",
        +    "FunctionValueProvenance",
             "col",
             "Expr",
             "func",
        @@ -657,9 +696,12 @@ __all__ = [
             "sanitize_uri",
             "blob",
             "BlobType",
        +    "BasePath",
        +    "blob_uri_array",
             "vector",
             "DBConnection",
             "Job",
        +    "JobState",
             "QueryDescription",
             "SqlQuery",
             "LanceDBConnection",
        diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py
        index 010c92009..77d9877e7 100644
        --- a/python/python/lancedb/_blob.py
        +++ b/python/python/lancedb/_blob.py
        @@ -1,19 +1,25 @@
         # SPDX-License-Identifier: Apache-2.0
         # SPDX-FileCopyrightText: Copyright The LanceDB Authors
         
        -"""Blob fetch API and v2 projection helpers."""
        +"""Blob fetch API and projection helpers."""
         
         from __future__ import annotations
         
         import io
         import operator
        +import re
         from collections.abc import Awaitable, Callable, Iterable, Mapping
        +from dataclasses import dataclass
         from typing import TYPE_CHECKING, Optional, Union
         
         import pyarrow as pa
         
         from .expr import Expr
        -from .schema import blob_column_paths, row_addressable_blob_v2_paths
        +from .schema import (
        +    blob_column_paths,
        +    row_addressable_blob_paths,
        +    row_addressable_blob_v2_paths,
        +)
         from .types import BlobMode, QueryProjection, QueryProjectionSpec
         
         if TYPE_CHECKING:
        @@ -26,10 +32,56 @@ BLOB_MODE_TO_HANDLING = {
         }
         
         ROW_ID_FIELD_NAME = "_lance_row_id"
        +QUERY_VERSION_METADATA_KEY = b"lancedb:query_version"
        +QUERY_SNAPSHOT_METADATA_KEY = b"lancedb:query_snapshot"
         
         FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
         FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
         
        +_POSITION_HELP = (
        +    "If you only have row positions, call "
        +    "table.take_offsets(offsets, with_row_id=True) first and pass the resulting "
        +    "'_rowid' values."
        +)
        +
        +
        +def _remote_blob_snapshot(
        +    schema: pa.Schema, *, operation: str = "blob_mode='bytes'"
        +) -> tuple[int, str]:
        +    """Validate the snapshot metadata a remote query attaches to its result."""
        +    value = (schema.metadata or {}).get(QUERY_VERSION_METADATA_KEY, b"")
        +    if not value.isdigit() or not 0 < int(value) < 2**64:
        +        raise NotImplementedError(
        +            f"{operation} requires a stable table snapshot: the query response "
        +            "has a missing, invalid, or inconsistent x-lancedb-query-version header. "
        +            "Upgrade the server and use a table without Realtime/MemWAL, or use "
        +            "blob_mode='descriptions'."
        +        )
        +    identity = (schema.metadata or {}).get(QUERY_SNAPSHOT_METADATA_KEY, b"")
        +    if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
        +        raise NotImplementedError(
        +            f"{operation} requires a trustworthy query snapshot identity: "
        +            "missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
        +            "on every serving node, or use blob_mode='descriptions'."
        +        )
        +    return int(value), identity.decode("ascii")
        +
        +
        +@dataclass(frozen=True)
        +class _BlobRowIdSelection:
        +    row_ids: list[int]
        +    version: Optional[int] = None
        +    snapshot_identity: Optional[str] = None
        +
        +
        +def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]:
        +    if size is None:
        +        return None
        +    size = operator.index(size)
        +    if size < 0:
        +        raise ValueError("buffer_size must be non-negative")
        +    return size
        +
         
         def _normalize_blob_descriptor(value):
             if isinstance(value, pa.Scalar):
        @@ -54,6 +106,16 @@ class BlobFile(io.RawIOBase):
             def __init__(self, inner) -> None:
                 self._inner = inner
         
        +    def set_buffer_size(self, size: int) -> None:
        +        """Set sequential read-ahead bytes (default 512 KiB); 0 disables it.
        +
        +        Changing the size discards unused prefetched bytes without moving the
        +        cursor. Explicit ``read_range`` and ``read_ranges`` bypass read-ahead.
        +        """
        +        if self.closed:
        +            raise ValueError("set_buffer_size of closed file")
        +        self._inner.set_buffer_size(_validate_blob_buffer_size(size))
        +
             async def aread(self) -> bytes:
                 if self.closed:
                     raise ValueError("read of closed file")
        @@ -165,6 +227,25 @@ def blob_v2_projection_sources(
             return _project_blob_paths(row_addressable_blob_v2_paths(schema), projection)
         
         
        +def blob_projection_sources(
        +    schema: pa.Schema,
        +    projection: QueryProjection,
        +    *,
        +    include_legacy: bool = False,
        +) -> dict[str, str]:
        +    """Map projected blob outputs to row-addressable source columns.
        +
        +    Legacy v1 columns are included only when the caller can safely fetch them
        +    through the same row-id path as v2.
        +    """
        +    paths = (
        +        row_addressable_blob_paths(schema)
        +        if include_legacy
        +        else row_addressable_blob_v2_paths(schema)
        +    )
        +    return _project_blob_paths(paths, projection)
        +
        +
         def reject_unfetchable_blob_columns(
             schema: pa.Schema, projection: QueryProjection, blob_sources: dict[str, str]
         ) -> None:
        @@ -177,8 +258,9 @@ def reject_unfetchable_blob_columns(
             if unfetchable:
                 raise ValueError(
                     f"blob_mode='bytes' cannot fetch blob columns {unfetchable}. Bytes are "
        -            "fetched by row id, which covers blob v2 columns with one blob per "
        -            "row but not legacy blob columns or blobs inside lists. Use "
        +            "fetched by row id for legacy and v2 columns in local plain scans, "
        +            "but not for blobs inside lists or query shapes whose result columns "
        +            "cannot be matched back to the source. Use "
                     "blob_mode='descriptions' or remove these columns from the projection."
                 )
         
        @@ -269,7 +351,7 @@ def finalize_blob_query_table(
             return stash_auto_row_ids(tbl, blob_paths)
         
         
        -async def replace_v2_blob_columns_with_bytes(
        +async def replace_blob_columns_with_bytes(
             tbl: pa.Table,
             blob_sources: dict[str, str],
             fetch_blobs: FetchBlobsAsync,
        @@ -289,7 +371,7 @@ async def replace_v2_blob_columns_with_bytes(
             return tbl
         
         
        -def replace_v2_blob_columns_with_bytes_sync(
        +def replace_blob_columns_with_bytes_sync(
             tbl: pa.Table,
             blob_sources: dict[str, str],
             fetch_blobs: FetchBlobsSync,
        @@ -333,7 +415,7 @@ def _hit_row_ids(tbl: pa.Table, blob_sources: dict[str, str]) -> list[int]:
             raise ValueError(
                 f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
                 f"field on blob columns {list(blob_sources)}. Call .with_row_id(True) "
        -        "to fetch blob bytes for this query."
        +        f"to fetch blob bytes for this query. {_POSITION_HELP}"
             )
         
         
        @@ -374,7 +456,8 @@ def read_row_ids_from_hits(hits: pa.Table, blob_column: str) -> list[int]:
             raise ValueError(
                 f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
                 f"field on blob column '{blob_column}'. Pass fresh blob query "
        -        "results, call .with_row_id(True), or pass a list of row ids."
        +        f"results, call .with_row_id(True), or pass a list of row ids. "
        +        f"{_POSITION_HELP}"
             )
         
         
        @@ -595,11 +678,31 @@ def _walk_struct_fields(
             return data_type
         
         
        +def _query_snapshot_for_blob_fetch(
        +    schema: pa.Schema,
        +) -> Optional[tuple[int, str]]:
        +    """Use the query snapshot when a result table carries one.
        +
        +    A table without either metadata key came from a local table or a server
        +    that cannot pin deferred reads, so row ids keep their existing
        +    current-snapshot behavior.
        +    """
        +    metadata = schema.metadata or {}
        +    if not any(
        +        key in metadata
        +        for key in (QUERY_VERSION_METADATA_KEY, QUERY_SNAPSHOT_METADATA_KEY)
        +    ):
        +        return None
        +    return _remote_blob_snapshot(schema, operation="fetching blobs for a query result")
        +
        +
         def _normalize_blob_row_ids(
             row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], blob_column: str
        -) -> list[int]:
        +) -> _BlobRowIdSelection:
        +    snapshot = None
             if isinstance(row_ids, pa.Table):
                 values = read_row_ids_from_hits(row_ids, blob_column)
        +        snapshot = _query_snapshot_for_blob_fetch(row_ids.schema)
             elif isinstance(row_ids, (pa.Array, pa.ChunkedArray)):
                 if not pa.types.is_integer(row_ids.type):
                     raise ValueError(
        @@ -619,7 +722,8 @@ def _normalize_blob_row_ids(
                 if row_id < 0:
                     raise ValueError("row ids must be non-negative")
                 normalized.append(row_id)
        -    return normalized
        +    version, snapshot_identity = snapshot if snapshot else (None, None)
        +    return _BlobRowIdSelection(normalized, version, snapshot_identity)
         
         
         def _wrap_blob_files(handles: Iterable[object]) -> list[Optional[BlobFile]]:
        diff --git a/python/python/lancedb/_blob_writer.py b/python/python/lancedb/_blob_writer.py
        new file mode 100644
        index 000000000..898250fa8
        --- /dev/null
        +++ b/python/python/lancedb/_blob_writer.py
        @@ -0,0 +1,91 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +"""Streaming Blob output for Enterprise Functions."""
        +
        +from __future__ import annotations
        +
        +import pyarrow as pa
        +
        +from .schema import blob
        +
        +_BLOB_WRITER_METADATA_KEY = b"lance.function.blob_writer"
        +_REFRESH_REQUIRED = (
        +    "BlobWriter is available only during a LanceDB Enterprise computed column refresh"
        +)
        +
        +
        +def _mark_blob_writer(field: pa.Field) -> pa.Field:
        +    metadata: dict[bytes | str, bytes | str] = {
        +        key: value for key, value in (field.metadata or {}).items()
        +    }
        +    metadata[_BLOB_WRITER_METADATA_KEY] = b"true"
        +    return field.with_metadata(metadata)
        +
        +
        +class BlobWriter:
        +    """Write one Blob v2 value in chunks during a computed column refresh.
        +
        +    Annotate a scalar Function's return value with ``BlobWriter`` to declare a
        +    Blob v2 result. For named or nested results, use :meth:`field` for each
        +    writer-capable field in the output schema. A vectorized Function returns
        +    a row-aligned list or tuple of results.
        +
        +    Open one writer per Blob value. Writes are sequential and block for
        +    capacity. Closing the writer seals the result, including an empty Blob.
        +    A context manager seals on normal exit and aborts on exceptional exit.
        +    A discarded writer still uses one entry in the batch's cumulative
        +    descriptor allowance. Explicit writers and implicit uploads of returned
        +    ``bytes`` share this allowance.
        +
        +    Return the sealed writer once at its declared Blob v2 output field during
        +    the same invocation. Unclosed or reused writers are invalid results.
        +
        +    The worker provides the implementation when it runs the packaged Function.
        +
        +    Examples
        +    --------
        +    ```python
        +    from lancedb.functions import BlobWriter, function
        +
        +    @function
        +    def render(text: str) -> BlobWriter:
        +        with BlobWriter.open() as output:
        +            for line in text.splitlines():
        +                output.write(line.encode("utf-8"))
        +                output.write(b"\\n")
        +        return output
        +    ```
        +    """
        +
        +    def __init__(self) -> None:
        +        raise RuntimeError(_REFRESH_REQUIRED)
        +
        +    @classmethod
        +    def open(cls) -> BlobWriter:
        +        """Open a sequential writer for one Blob in the active invocation."""
        +        raise RuntimeError(_REFRESH_REQUIRED)
        +
        +    def write(self, data) -> int:
        +        """Write a bytes-like object and return the accepted byte count."""
        +        raise RuntimeError(_REFRESH_REQUIRED)
        +
        +    def close(self) -> None:
        +        """Seal the Blob so the writer can be returned as a result."""
        +        raise RuntimeError(_REFRESH_REQUIRED)
        +
        +    def __enter__(self) -> BlobWriter:
        +        raise RuntimeError(_REFRESH_REQUIRED)
        +
        +    def __exit__(self, exc_type, exc, traceback) -> None:
        +        raise RuntimeError(_REFRESH_REQUIRED)
        +
        +    @staticmethod
        +    def field(name: str, nullable: bool = True) -> pa.Field:
        +        """Declare a writer-capable Blob v2 field in a Function output schema.
        +
        +        A marked field also accepts ordinary ``bytes`` and, if nullable,
        +        ``None``. Use this helper for Function output schemas and use
        +        [``lancedb.blob``][lancedb.blob] for table schemas.
        +        """
        +        return _mark_blob_writer(blob(name, nullable=nullable))
        diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi
        index 02d9c9e87..1080626a1 100644
        --- a/python/python/lancedb/_lancedb.pyi
        +++ b/python/python/lancedb/_lancedb.pyi
        @@ -25,6 +25,9 @@ from .index import (
             LabelList,
             Fm,
             NGram,
        +    ZoneMap,
        +    RTree,
        +    ScalarPlugin,
             HnswPq,
             HnswSq,
             HnswFlat,
        @@ -116,7 +119,7 @@ class PyExpr:
         
         def expr_col(name: str) -> PyExpr: ...
         def expr_lit(
        -    value: Union[bool, int, float, str, bytes, date, datetime, Decimal],
        +    value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
         ) -> PyExpr: ...
         def expr_func(name: str, args: List[PyExpr]) -> PyExpr: ...
         
        @@ -184,12 +187,20 @@ class Connection(object):
                 limit: Optional[int],
             ) -> list[str]: ...  # Deprecated: Use list_tables instead
             async def open_job(self, job_id: str) -> Job: ...
        +    async def server_info(self) -> str: ...
             async def list_gpu_classes(self) -> list[GpuClass]: ...
             async def create_function_async(
        -        self, request_json: str, namespace_path: Optional[List[str]] = None
        +        self,
        +        request_json: str,
        +        namespace_path: Optional[List[str]] = None,
        +        *,
        +        exist_ok: bool = False,
             ) -> Job: ...
             async def get_function(
        -        self, name: str, version: str, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        version: Optional[str] = None,
        +        namespace_path: Optional[List[str]] = None,
             ) -> str: ...
             def list_functions(
                 self,
        @@ -201,6 +212,9 @@ class Connection(object):
             async def drop_function(
                 self, name: str, version: str, namespace_path: Optional[List[str]] = None
             ) -> bool: ...
        +    async def _drop_function_with_warnings(
        +        self, name: str, version: str, namespace_path: Optional[List[str]] = None
        +    ) -> Tuple[bool, list[str]]: ...
             async def drop_function_async(
                 self, name: str, version: str, namespace_path: Optional[List[str]] = None
             ) -> Tuple[bool, Job]: ...
        @@ -221,7 +235,12 @@ class Connection(object):
                 self, name: str, namespace_path: Optional[List[str]] = None
             ) -> None: ...
             async def create_secret(
        -        self, name: str, value: str, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        value: str,
        +        namespace_path: Optional[List[str]] = None,
        +        *,
        +        exist_ok: bool = False,
             ) -> None: ...
             async def alter_secret(
                 self, name: str, value: str, namespace_path: Optional[List[str]] = None
        @@ -240,7 +259,12 @@ class Connection(object):
                 self, name: str, namespace_path: Optional[List[str]] = None
             ) -> Tuple[str, int, int]: ...
             async def create_view(
        -        self, name: str, query: str, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        query: str,
        +        namespace_path: Optional[List[str]] = None,
        +        *,
        +        exist_ok: bool = False,
             ) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ...
             async def describe_view(
                 self, name: str, namespace_path: Optional[List[str]] = None
        @@ -278,7 +302,19 @@ class Connection(object):
                 page_limit: Optional[int] = None,
             ) -> NameListing: ...
             def list_jobs(
        -        self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
        +        self,
        +        *,
        +        page_token: Optional[str] = None,
        +        page_limit: Optional[int] = None,
        +        table: Optional[str] = None,
        +        namespace_path: Optional[List[str]] = None,
        +        state: Optional[
        +            Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
        +        ] = None,
        +        job_type: Optional[str] = None,
        +        job_types: Optional[List[str]] = None,
        +        created_at_gte_millis: Optional[int] = None,
        +        created_at_lt_millis: Optional[int] = None,
             ) -> JobListing: ...
             async def cancel_job(self, job_id: str) -> bool: ...
             async def pause_job(self, job_id: str) -> str: ...
        @@ -289,6 +325,9 @@ class Connection(object):
                 *,
                 default_namespace_path: Optional[List[str]] = None,
                 parameters: Optional[pa.RecordBatch] = None,
        +        timeout: Optional[timedelta] = None,
        +        read_timeout: Optional[timedelta] = None,
        +        cancel_on_drop: bool = False,
             ) -> SqlQuery: ...
             async def describe_query(self, query_id: UUID) -> QueryDescription: ...
             async def create_table(
        @@ -299,6 +338,9 @@ class Connection(object):
                 namespace_path: Optional[List[str]] = None,
                 storage_options: Optional[Dict[str, str]] = None,
                 location: Optional[str] = None,
        +        namespace_client: Optional[Any] = None,
        +        initial_bases: Optional[List[Any]] = None,
        +        allow_external_blob_outside_bases: bool = False,
             ) -> Table: ...
             async def create_empty_table(
                 self,
        @@ -308,6 +350,8 @@ class Connection(object):
                 namespace_path: Optional[List[str]] = None,
                 storage_options: Optional[Dict[str, str]] = None,
                 location: Optional[str] = None,
        +        namespace_client: Optional[Any] = None,
        +        initial_bases: Optional[List[Any]] = None,
             ) -> Table: ...
             async def open_table(
                 self,
        @@ -325,6 +369,8 @@ class Connection(object):
                 source_version: Optional[int] = None,
                 source_tag: Optional[str] = None,
                 is_shallow: bool = True,
        +        *,
        +        exist_ok: bool = False,
             ) -> Table: ...
             async def rename_table(
                 self,
        @@ -336,24 +382,40 @@ class Connection(object):
             async def create_materialized_view(
                 self,
                 name: str,
        -        source: str,
        +        source: Optional[str] = None,
                 projections: Optional[List[Tuple[str, str]]] = None,
                 filter: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
        +        *,
        +        query: Optional[str] = None,
        +        exist_ok: bool = False,
             ) -> Table: ...
             async def create_materialized_view_async(
                 self,
                 name: str,
        -        source: str,
        +        source: Optional[str] = None,
                 projections: Optional[List[Tuple[str, str]]] = None,
                 filter: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
        +        *,
        +        query: Optional[str] = None,
        +        exist_ok: bool = False,
             ) -> Job: ...
             def list_materialized_views(
                 self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
        @@ -385,11 +447,26 @@ class BlobFile:
             def seek(self, position: int) -> None: ...
             def tell(self) -> int: ...
             def size(self) -> int: ...
        +    def set_buffer_size(self, size: int) -> None: ...
             def read_range(self, offset: int, length: int) -> bytes: ...
             def read_ranges(self, ranges: list[tuple[int, int]]) -> list[bytes]: ...
             def read_up_to(self, length: int) -> bytes: ...
         
         class Job:
        +    @property
        +    def job_id(self) -> Optional[str]: ...
        +    @property
        +    def operation_id(self) -> Optional[str]: ...
        +    @property
        +    def attempt(self) -> Optional[int]: ...
        +    @property
        +    def retry_of(self) -> Optional[str]: ...
        +    @property
        +    def lifecycle_state(self) -> Optional[str]: ...
        +    @property
        +    def source_table_version(self) -> Optional[int]: ...
        +    @property
        +    def execution_epoch(self) -> Optional[int]: ...
             @property
             def id(self) -> Optional[str]: ...
             @property
        @@ -404,12 +481,34 @@ class Job:
                 progress: Optional[Callable[[dict[str, Any]], None]] = None,
             ) -> Optional[str]: ...
             async def cancel(self) -> None: ...
        +    async def retry(self) -> Job: ...
             async def refresh(self) -> None: ...
        +    async def timeline(self) -> str: ...
        +    async def stack(self, worker_id: str) -> str: ...
        +    async def capture_profile(
        +        self,
        +        worker_id: str,
        +        *,
        +        kind: str = "cpu",
        +        duration_seconds: Optional[float] = None,
        +        session_slot: int = 0,
        +    ) -> str: ...
        +    async def profile_status(self, profile_id: str) -> str: ...
        +    async def wait_for_profile(
        +        self,
        +        profile_id: str,
        +        *,
        +        timeout_seconds: Optional[float] = None,
        +        poll_interval_seconds: Optional[float] = None,
        +    ) -> str: ...
        +    async def profile_artifact(self, profile_id: str) -> str: ...
        +    async def stats(self) -> Optional[str]: ...
             async def events(
                 self,
                 *,
                 limit: Optional[int] = None,
                 filter: Optional[str] = None,
        +        page_token: Optional[str] = None,
             ) -> pa.Table: ...
         
         class JobInfo:
        @@ -424,6 +523,18 @@ class JobInfo:
             @property
             def created_at_millis(self) -> int: ...
             @property
        +    def completed_at_millis(self) -> Optional[int]: ...
        +    @property
        +    def duration_millis(self) -> Optional[int]: ...
        +    @property
        +    def columns(self) -> list[str]: ...
        +    @property
        +    def function_name(self) -> Optional[str]: ...
        +    @property
        +    def function_version(self) -> Optional[str]: ...
        +    @property
        +    def failure(self) -> Optional[JobFailureInfo]: ...
        +    @property
             def progress(self) -> Optional[dict[str, Any]]: ...
             @property
             def paused(self) -> bool: ...
        @@ -465,11 +576,27 @@ class JobFailureInfo:
             @property
             def message(self) -> Optional[str]: ...
             @property
        +    def traceback(self) -> Optional[str]:
        +        """User-code traceback, possibly truncated by the server."""
        +        ...
        +    @property
             def retryable(self) -> Optional[bool]: ...
             @property
             def sql_job_id(self) -> Optional[str]: ...
         
         class JobDescription:
        +    @property
        +    def operation_id(self) -> Optional[str]: ...
        +    @property
        +    def attempt(self) -> Optional[int]: ...
        +    @property
        +    def retry_of(self) -> Optional[str]: ...
        +    @property
        +    def lifecycle_state(self) -> Optional[str]: ...
        +    @property
        +    def source_table_version(self) -> Optional[int]: ...
        +    @property
        +    def execution_epoch(self) -> Optional[int]: ...
             @property
             def job_id(self) -> str: ...
             @property
        @@ -494,6 +621,8 @@ class JobDescription:
         class SqlQuery:
             @property
             def id(self) -> UUID: ...
        +    @property
        +    def job_id(self) -> Optional[str]: ...
             async def describe(self) -> QueryDescription: ...
             async def reader(self) -> RecordBatchStream: ...
             async def cancel(self) -> None: ...
        @@ -502,6 +631,8 @@ class QueryDescription:
             @property
             def id(self) -> UUID: ...
             @property
        +    def job_id(self) -> Optional[str]: ...
        +    @property
             def status(self) -> str: ...
             @property
             def progress(self) -> Optional[float]: ...
        @@ -515,6 +646,7 @@ class Table:
             def _is_native(self) -> bool: ...
             def close(self) -> None: ...
             async def schema(self) -> pa.Schema: ...
        +    def schema_sync(self) -> pa.Schema: ...
             async def add(
                 self,
                 data: pa.RecordBatchReader,
        @@ -522,7 +654,14 @@ class Table:
                 progress: Optional[Any] = None,
                 write_parallelism: Optional[int] = None,
                 allow_external_blob_outside_bases: bool = False,
        +        retries: Optional[int] = None,
             ) -> AddResult: ...
        +    async def execute_merge_insert(
        +        self,
        +        data: pa.RecordBatchReader,
        +        parameters: Dict[str, Any],
        +        retries: Optional[int] = None,
        +    ) -> MergeResult: ...
             async def update(
                 self, updates: Dict[str, str], where: Optional[str]
             ) -> UpdateResult: ...
        @@ -542,6 +681,9 @@ class Table:
                     LabelList,
                     Fm,
                     NGram,
        +            ZoneMap,
        +            RTree,
        +            ScalarPlugin,
                     FTS,
                 ],
                 replace: Optional[bool],
        @@ -549,6 +691,7 @@ class Table:
                 *,
                 name: Optional[str],
                 train: Optional[bool],
        +        exist_ok: bool = False,
             ): ...
             async def create_index_async(
                 self,
        @@ -565,6 +708,9 @@ class Table:
                     LabelList,
                     Fm,
                     NGram,
        +            ZoneMap,
        +            RTree,
        +            ScalarPlugin,
                     FTS,
                 ],
                 replace: Optional[bool],
        @@ -572,14 +718,37 @@ class Table:
                 *,
                 name: Optional[str],
                 train: Optional[bool],
        +        exist_ok: bool = False,
             ) -> Job: ...
             async def list_versions(self) -> List[Dict[str, Any]]: ...
             async def version(self) -> int: ...
        +    async def delta(
        +        self,
        +        from_version: Union[int, str],
        +        to_version: Optional[Union[int, str]] = None,
        +    ) -> TableDelta: ...
             async def checkout(self, version: Union[int, str]): ...
             async def checkout_latest(self): ...
        +    async def _checkout_current(self) -> Table: ...
             async def restore(self, version: Optional[Union[int, str]] = None): ...
             async def prewarm_index(self, index_name: str) -> None: ...
             async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ...
        +    async def explain_prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[pa.RecordBatch] = None,
        +    ) -> str: ...
        +    async def prewarm_data_async(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[pa.RecordBatch] = None,
        +    ) -> Job: ...
             async def list_indices(self) -> list[IndexConfig]: ...
             async def tokenize(
                 self,
        @@ -598,41 +767,138 @@ class Table:
                 columns: list[tuple[str, str]],
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> AddColumnsResult: ...
             async def add_function_columns(
                 self,
        -        application_json: str,
        -        output_name: Optional[str],
        +        bindings: list[tuple[str, Optional[str]]],
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> AddColumnsResult: ...
             async def refresh_column(
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[dict[str, int]] = None,
        +        planning_workers: Optional[dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
                 gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[str] = None,
        +        error_policy: Optional[str] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> RefreshColumnResult: ...
             async def refresh_column_async(
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[dict[str, int]] = None,
        +        planning_workers: Optional[dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
                 gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[str] = None,
        +        error_policy: Optional[str] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> Job: ...
        +    async def resume_refresh(self, job_id: str) -> Job: ...
             async def function_errors(
                 self,
                 job_id: Optional[str] = None,
                 column: Optional[str] = None,
                 limit: Optional[int] = None,
        +        history: bool = False,
        +        page_token: Optional[str] = None,
             ) -> FunctionErrors: ...
        +    async def quarantine_function_errors(
        +        self,
        +        column: str,
        +        *,
        +        quarantined: bool = True,
        +        job_id: Optional[str] = None,
        +        error_type: Optional[str] = None,
        +        after_attempts: Optional[int] = None,
        +    ) -> int: ...
        +    async def function_provenance(
        +        self,
        +        column: str,
        +        *,
        +        limit: Optional[int] = None,
        +        version: Optional[int] = None,
        +    ) -> str: ...
        +    async def column_statuses(
        +        self, column: Optional[str] = None
        +    ) -> list[FunctionColumnStatus]: ...
        +    async def column_status(self, column: str) -> FunctionColumnStatus: ...
        +    async def wait_column_fresh(
        +        self, column: str, timeout: Optional[timedelta] = None
        +    ) -> FunctionColumnStatus: ...
             async def refresh_materialized_view(
        -        self, source_version: Optional[int] = None, *, full: bool = False
        +        self,
        +        source_version: Optional[int] = None,
        +        *,
        +        full: bool = False,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> RefreshMaterializedViewResult: ...
             async def refresh_materialized_view_async(
        -        self, source_version: Optional[int] = None, *, full: bool = False
        +        self,
        +        source_version: Optional[int] = None,
        +        *,
        +        full: bool = False,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> Job: ...
             async def materialized_view_definition(self) -> str: ...
             async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ...
        @@ -642,6 +908,11 @@ class Table:
             async def update_field_metadata(
                 self, updates: list[dict[str, Any]]
             ) -> UpdateFieldMetadataResult: ...
        +    async def cleanup_async(self, min_age_seconds: Optional[int] = None) -> Job: ...
        +    async def explain_cleanup(self, min_age_seconds: Optional[int] = None) -> str: ...
        +    async def compact_async(
        +        self, compaction_options: Optional[Dict[str, Any]] = None
        +    ) -> Job: ...
             async def optimize(
                 self,
                 *,
        @@ -677,7 +948,12 @@ class Table:
             def take_row_ids(self, row_ids: list[int]) -> TakeQuery: ...
             async def blob_columns(self) -> list[str]: ...
             async def fetch_blobs(
        -        self, column: str, row_ids: list[int]
        +        self,
        +        column: str,
        +        row_ids: list[int],
        +        *,
        +        version: Optional[int] = None,
        +        snapshot_identity: Optional[str] = None,
             ) -> pa.LargeBinaryArray: ...
             async def fetch_blob_ranges(
                 self,
        @@ -685,15 +961,23 @@ class Table:
                 requests: Sequence[Sequence[int]],
             ) -> pa.LargeBinaryArray: ...
             async def fetch_blob_files(
        -        self, column: str, row_ids: list[int]
        +        self,
        +        column: str,
        +        row_ids: list[int],
        +        buffer_size: Optional[int] = None,
        +        *,
        +        version: Optional[int] = None,
        +        snapshot_identity: Optional[str] = None,
             ) -> list[Optional[BlobFile]]: ...
        -    async def open_blob_file(self, descriptor: str) -> BlobFile: ...
        +    async def open_blob_file(
        +        self, descriptor: str, buffer_size: Optional[int] = None
        +    ) -> BlobFile: ...
             def vector_search(self) -> VectorQuery: ...
         
         class Tags:
             async def list(self) -> Dict[str, Tag]: ...
             async def get_version(self, tag: str) -> int: ...
        -    async def create(self, tag: str, version: int): ...
        +    async def create(self, tag: str, version: Optional[int] = None): ...
             async def delete(self, tag: str): ...
             async def update(self, tag: str, version: int): ...
         
        @@ -704,6 +988,8 @@ class Branches:
                 name: str,
                 from_ref: Optional[str] = None,
                 from_version: Optional[int] = None,
        +        *,
        +        from_tag: Optional[str] = None,
             ) -> Table: ...
             async def checkout(self, name: str, version: Optional[int] = None) -> Table: ...
             async def delete(self, name: str) -> None: ...
        @@ -764,11 +1050,26 @@ class RecordBatchStream:
             def __aiter__(self) -> "RecordBatchStream": ...
             async def __anext__(self) -> pa.RecordBatch: ...
         
        +class SyncRecordBatchStream:
        +    @property
        +    def schema(self) -> pa.Schema: ...
        +    def __iter__(self) -> "SyncRecordBatchStream": ...
        +    def __next__(self) -> pa.RecordBatch: ...
        +
         class ColumnOrdering(TypedDict):
             column_name: str
             ascending: bool
             nulls_first: bool
         
        +class TableDelta:
        +    def begin_version(self) -> int: ...
        +    def end_version(self) -> int: ...
        +    async def inserted_rows(self) -> RecordBatchStream: ...
        +    async def updated_rows(self) -> RecordBatchStream: ...
        +    async def upserted_rows(self) -> RecordBatchStream: ...
        +    async def deleted_row_ids(self) -> RecordBatchStream: ...
        +    async def list_transactions(self) -> List[Dict[str, Any]]: ...
        +
         class Query:
             def where(self, filter: str): ...
             def where_expr(self, expr: PyExpr): ...
        @@ -784,10 +1085,20 @@ class Query:
             def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ...
             def nearest_to_text(self, query: dict) -> FTSQuery: ...
             def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
        +    def scan_in_order(self, ordered: bool): ...
             async def output_schema(self) -> pa.Schema: ...
             async def execute(
                 self, max_batch_length: Optional[int], timeout: Optional[timedelta]
             ) -> RecordBatchStream: ...
        +    def execute_sync(
        +        self, max_batch_length: Optional[int], timeout: Optional[timedelta]
        +    ) -> SyncRecordBatchStream: ...
        +    async def execute_to_reader(
        +        self, max_batch_length: Optional[int], timeout: Optional[timedelta]
        +    ) -> pa.RecordBatchReader: ...
        +    def execute_to_reader_sync(
        +        self, max_batch_length: Optional[int], timeout: Optional[timedelta]
        +    ) -> pa.RecordBatchReader: ...
             async def explain_plan(self, verbose: Optional[bool]) -> str: ...
             async def analyze_plan(
                 self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
        @@ -797,9 +1108,13 @@ class Query:
         class TakeQuery:
             def select(self, columns: List[str]): ...
             def with_row_id(self): ...
        +    def preserve_order(self): ...
             def use_rte(self, enable: bool): ...
             async def output_schema(self) -> pa.Schema: ...
             async def execute(self) -> RecordBatchStream: ...
        +    async def execute_to_reader(
        +        self, max_batch_length: Optional[int], timeout: Optional[timedelta]
        +    ) -> pa.RecordBatchReader: ...
             async def explain_plan(self, verbose: Optional[bool]) -> str: ...
             async def analyze_plan(
                 self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
        @@ -821,10 +1136,17 @@ class FTSQuery:
             def add_query_vector(self, query_vec: pa.Array) -> None: ...
             def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ...
             def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
        +    async def count_rows(self) -> int: ...
             async def output_schema(self) -> pa.Schema: ...
             async def execute(
                 self, max_batch_length: Optional[int], timeout: Optional[timedelta]
             ) -> RecordBatchStream: ...
        +    async def execute_to_reader(
        +        self, max_batch_length: Optional[int], timeout: Optional[timedelta]
        +    ) -> pa.RecordBatchReader: ...
        +    def execute_to_reader_sync(
        +        self, max_batch_length: Optional[int], timeout: Optional[timedelta]
        +    ) -> pa.RecordBatchReader: ...
             async def explain_plan(self, verbose: Optional[bool]) -> str: ...
             async def analyze_plan(
                 self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
        @@ -834,6 +1156,12 @@ class FTSQuery:
         class VectorQuery:
             async def output_schema(self) -> pa.Schema: ...
             async def execute(self) -> RecordBatchStream: ...
        +    async def execute_to_reader(
        +        self, max_batch_length: Optional[int], timeout: Optional[timedelta]
        +    ) -> pa.RecordBatchReader: ...
        +    def execute_to_reader_sync(
        +        self, max_batch_length: Optional[int], timeout: Optional[timedelta]
        +    ) -> pa.RecordBatchReader: ...
             def where(self, filter: str): ...
             def where_expr(self, expr: PyExpr): ...
             def select(self, columns: List[Tuple[str, str]]): ...
        @@ -893,6 +1221,8 @@ class PyQueryRequest:
             limit: Optional[int]
             offset: Optional[int]
             take_offsets: Optional[List[int]]
        +    take_row_ids: Optional[List[int]]
        +    preserve_order: Optional[bool]
             filter: Optional[Union[str, bytes]]
             full_text_search: Optional[FullTextQuery]
             select: Optional[Union[str, List[str]]]
        @@ -916,6 +1246,7 @@ class PyQueryRequest:
             postfilter: Optional[bool]
             norm: Optional[str]
             order_by: Optional[List[ColumnOrdering]]
        +    scan_in_order: Optional[bool]
         
         class CompactionStats:
             fragments_removed: int
        @@ -1003,9 +1334,16 @@ class RefreshColumnResult:
             version: int
         
         class FunctionErrorRecord:
        +    first_seen_at_millis: Optional[int]
        +    last_seen_at_millis: Optional[int]
        +    quarantined: bool
        +    input: Optional[str]
        +    attempts: Optional[int]
             job_id: str
        +    attempt_job_id: Optional[str]
             fragment_id: int
             row_offset: Optional[int]
        +    row_id: Optional[int]
             row_address: Optional[int]
             column: str
             function: str
        @@ -1013,6 +1351,8 @@ class FunctionErrorRecord:
             table_version: int
             error_type: str
             error_message: str
        +    traceback: Optional[str]
        +    """User-code traceback, possibly truncated by the server."""
             created_at_millis: int
         
         class FunctionErrorFragment:
        @@ -1022,10 +1362,54 @@ class FunctionErrorFragment:
             rows_recorded: int
         
         class FunctionErrors:
        +    workflow_version: Optional[int]
        +    error_groups_json: str
        +    @property
        +    def page_token(self) -> Optional[str]: ...
             records: list[FunctionErrorRecord]
             fragments: list[FunctionErrorFragment]
             truncated: bool
         
        +class FunctionColumnVersionStatus:
        +    name: str
        +    namespace_path: list[str]
        +    object_id: str
        +    location: str
        +    version: str
        +    manifest_digest: str
        +
        +class FunctionColumnLastRefreshJob:
        +    job_id: str
        +    state: str
        +    automatic: Optional[bool]
        +    completed_at_millis: Optional[int]
        +    failure: Optional[JobFailureInfo]
        +
        +class FunctionColumnAutoRefreshStatus:
        +    enabled: bool
        +    interval_seconds: Optional[int]
        +    active_job_id: Optional[str]
        +    state: str
        +    failure_streak: int
        +    effective_cooldown_millis: Optional[int]
        +    blocked_reason: Optional[str]
        +    next_run_at_millis: Optional[int]
        +    next_run_at_reason: Optional[str]
        +
        +class FunctionColumnStatus:
        +    column: str
        +    binding_id: str
        +    function: FunctionColumnVersionStatus
        +    table_version: int
        +    rows: int
        +    fresh: int
        +    stale: int
        +    never_computed: int
        +    failed: int
        +    last_refresh_job: Optional[FunctionColumnLastRefreshJob]
        +    last_failure_job: Optional[FunctionColumnLastRefreshJob]
        +    auto_refresh: FunctionColumnAutoRefreshStatus
        +
         class RefreshMaterializedViewResult:
             @staticmethod
             def from_json(value: str) -> RefreshMaterializedViewResult: ...
        @@ -1054,7 +1438,12 @@ class AsyncPermutationBuilder:
                 seed: Optional[int] = None,
             ) -> "AsyncPermutationBuilder": ...
             def split_hash(
        -        self, columns: List[str], split_weights: List[int], *, discard_weight: int = 0
        +        self,
        +        columns: List[str],
        +        split_weights: List[int],
        +        *,
        +        discard_weight: Optional[int] = None,
        +        split_names: Optional[List[str]] = None,
             ) -> "AsyncPermutationBuilder": ...
             def split_sequential(
                 self,
        @@ -1077,6 +1466,14 @@ class AsyncPermutationBuilder:
                 self, seed: Optional[int], clump_size: Optional[int]
             ) -> "AsyncPermutationBuilder": ...
             def filter(self, filter: str) -> "AsyncPermutationBuilder": ...
        +    def persist(
        +        self,
        +        db: Connection,
        +        table_name: str,
        +        *,
        +        namespace_path: Optional[List[str]] = None,
        +        mode: str = "create",
        +    ) -> "AsyncPermutationBuilder": ...
             async def execute(self) -> Table: ...
         
         def async_permutation_builder(
        @@ -1117,6 +1514,7 @@ async def connect_catalog(
             sql_host_override: Optional[str] = None,
             read_consistency_interval: Optional[float] = None,
             oauth_config: Optional[Any] = None,
        +    storage_options: Optional[dict[str, str]] = None,
         ) -> Catalog: ...
         
         class NameListing:
        @@ -1198,3 +1596,6 @@ class AuthzObject:
             ) -> AuthzObject: ...
             def __str__(self) -> str: ...
             def __repr__(self) -> str: ...
        +
        +def validate_function_retry_policy(json: str) -> None: ...
        +def _validate_conda_requirement(requirement: str) -> None: ...
        diff --git a/python/python/lancedb/background_loop.py b/python/python/lancedb/background_loop.py
        index 9e1fdfbd8..7e55e708b 100644
        --- a/python/python/lancedb/background_loop.py
        +++ b/python/python/lancedb/background_loop.py
        @@ -13,22 +13,51 @@ class BackgroundEventLoop:
             A background event loop that can run futures.
         
             Used to bridge sync and async code, without messing with users event loops.
        +
        +    The loop and its thread are created by the first call to :meth:`run`, not
        +    by constructing this object, so importing lancedb does not leave an idle
        +    background thread behind.
             """
         
             def __init__(self):
        -        self._start()
        +        self.loop: asyncio.AbstractEventLoop | None = None
        +        self.thread: threading.Thread | None = None
        +        self._start_lock = threading.Lock()
         
        -    def _start(self):
        -        self.loop = asyncio.new_event_loop()
        -        self.thread = threading.Thread(
        -            target=self.loop.run_forever,
        -            name="LanceDBBackgroundEventLoop",
        -            daemon=True,
        -        )
        -        self.thread.start()
        +    def _start(self) -> asyncio.AbstractEventLoop:
        +        loop = self.loop
        +        if loop is not None:
        +            return loop
        +        with self._start_lock:
        +            loop = self.loop
        +            if loop is not None:
        +                return loop
        +            loop = asyncio.new_event_loop()
        +            thread = threading.Thread(
        +                target=loop.run_forever,
        +                name="LanceDBBackgroundEventLoop",
        +                daemon=True,
        +            )
        +            thread.start()
        +            # Publish the loop first and the thread last. Callers that reach
        +            # _start while this is in progress wait on _start_lock, so they
        +            # cannot observe a half-initialized loop/thread pair.
        +            self.loop = loop
        +            self.thread = thread
        +            return loop
        +
        +    def _reset_after_fork(self):
        +        # Threads do not survive fork(). Reset to the unstarted state without
        +        # calling into the inherited loop or thread: the thread is gone, and
        +        # it may have held _start_lock when the fork happened. A fresh lock
        +        # lets the child start a new loop on its first run().
        +        self.loop = None
        +        self.thread = None
        +        self._start_lock = threading.Lock()
         
             def run(self, future):
        -        concurrent_future = asyncio.run_coroutine_threadsafe(future, self.loop)
        +        loop = self._start()
        +        concurrent_future = asyncio.run_coroutine_threadsafe(future, loop)
                 try:
                     return concurrent_future.result()
                 except BaseException:
        @@ -60,12 +89,15 @@ _FORK_WARNED = False
         
         
         def _reset_after_fork():
        -    # Threads do not survive fork(), so the asyncio loop in LOOP.thread is
        -    # dead in the child. Re-initialize the singleton in place so existing
        +    # Threads do not survive fork(), so the loop in LOOP.thread is dead in
        +    # the child. Reset the singleton in place so existing
             # `from .background_loop import LOOP` references in other modules see
        -    # the new state. The Rust-side tokio runtime is reset analogously by a
        -    # pthread_atfork hook installed in the _lancedb extension.
        -    LOOP._start()
        +    # the unstarted state and create a fresh loop on their first run(). Do
        +    # not restart it here: the child may never use LanceDB, and the at-fork
        +    # handler must not touch the vanished thread or acquire inherited locks.
        +    # The Rust-side tokio runtime is reset analogously by a pthread_atfork
        +    # hook installed in the _lancedb extension.
        +    LOOP._reset_after_fork()
             # The embedding executor's worker threads are dead in the child as well.
             # Replace it with a fresh pool (threads are spawned lazily, so this is
             # cheap); we don't shut down the old one, since joining its dead workers
        diff --git a/python/python/lancedb/catalog.py b/python/python/lancedb/catalog.py
        index 338be98b8..5b3b0509c 100644
        --- a/python/python/lancedb/catalog.py
        +++ b/python/python/lancedb/catalog.py
        @@ -3,13 +3,17 @@
         
         """Remote catalogs manage databases."""
         
        -from functools import cached_property
        +import os
        +import warnings
        +from concurrent.futures import ThreadPoolExecutor
         from datetime import timedelta
        +from functools import cached_property
         from typing import Any, AsyncIterator, Iterator, Optional, Union
         
         from . import _lancedb
         from .background_loop import LOOP
         from .authz import AsyncAuthorization, Authorization
        +from .common import URI, sanitize_uri
         from .db import AsyncConnection, DBConnection
         from .remote import ClientConfig, OAuthConfig
         from .remote.db import RemoteDBConnection
        @@ -163,12 +167,14 @@ class Catalog:
                 client_config=None,
                 sql_host_override: Optional[str] = None,
                 oauth_config: Optional[OAuthConfig] = None,
        +        storage_options: Optional[dict[str, str]] = None,
             ):
                 self._inner = inner
                 self._api_key = api_key
                 self._client_config = client_config
                 self._sql_host_override = sql_host_override
                 self._oauth_config = oauth_config
        +        self._storage_options = storage_options
         
             @cached_property
             def authz(self) -> Authorization:
        @@ -198,6 +204,7 @@ class Catalog:
                     self._client_config,
                     self._oauth_config,
                     self._sql_host_override,
        +            self._storage_options,
                 )
         
             def list_databases(
        @@ -227,28 +234,71 @@ class Catalog:
         
         
         async def connect_catalog_async(
        -    endpoint: str,
        +    uri: Optional[URI] = None,
             *,
             api_key: Optional[str] = None,
        -    client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
        +    region: Optional[str] = None,
        +    host_override: Optional[str] = None,
             sql_host_override: Optional[str] = None,
             read_consistency_interval: Optional[timedelta] = None,
        +    client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
        +    storage_options: Optional[dict[str, str]] = None,
        +    session: Optional[_lancedb.Session] = None,
        +    manifest_enabled: bool = False,
        +    namespace_client_properties: Optional[dict[str, str]] = None,
             oauth_config: Optional[OAuthConfig] = None,
         ) -> AsyncCatalog:
        -    """Connect to an HTTP(S) server's root catalog.
        +    """Connect to a server's root catalog using database connection settings.
        +
        +    ``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise
        +    ``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with
        +    [connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's
        +    database is ignored and requests target the root catalog.
        +
        +    ``region`` is ignored with a warning when supplied. Catalog connections use
        +    the explicit endpoint rather than a region-derived Cloud (legacy) endpoint.
        +    ``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable.
        +    Embedded-only ``session``, ``manifest_enabled`` and
        +    ``namespace_client_properties`` are not supported.
         
             Root requests omit database-selection headers. API key, client configuration,
        -    OAuth, and table read consistency settings are inherited by opened databases.
        +    OAuth, storage options, and table read consistency settings are inherited by
        +    opened databases.
             Database names containing slashes remain single logical names.
             Set ``sql_host_override`` to the SQL service endpoint to execute SQL through
             returned connections when the catalog endpoint uses HTTPS.
             """
        +    if region is not None:
        +        warnings.warn(
        +            "region is ignored by connect_catalog_async; the catalog endpoint "
        +            "is selected by host_override or uri.",
        +            UserWarning,
        +            stacklevel=2,
        +        )
        +    for name, value in (
        +        ("session", session),
        +        ("manifest_enabled", manifest_enabled or None),
        +        ("namespace_client_properties", namespace_client_properties),
        +    ):
        +        if value is not None:
        +            raise NotImplementedError(
        +                f"{name} is not supported for catalog connections"
        +            )
        +    endpoint = host_override if host_override is not None else uri
        +    if endpoint is None:
        +        raise ValueError("uri or host_override is required for catalog connections")
             if isinstance(client_config, dict):
                 client_config = ClientConfig(**client_config)
             if client_config is None:
                 client_config = ClientConfig()
        +    if (
        +        api_key is None
        +        and oauth_config is None
        +        and client_config.header_provider is None
        +    ):
        +        api_key = os.environ.get("LANCEDB_API_KEY")
             inner = await _lancedb.connect_catalog(
        -        endpoint,
        +        sanitize_uri(endpoint),
                 api_key=api_key,
                 client_config=client_config,
                 sql_host_override=sql_host_override,
        @@ -258,32 +308,115 @@ async def connect_catalog_async(
                     else None
                 ),
                 oauth_config=oauth_config,
        +        storage_options=storage_options,
             )
             return AsyncCatalog(inner)
         
         
         def connect_catalog(
        -    endpoint: str,
        +    uri: Optional[URI] = None,
             *,
             api_key: Optional[str] = None,
        -    client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
        +    region: Optional[str] = None,
        +    host_override: Optional[str] = None,
             sql_host_override: Optional[str] = None,
             read_consistency_interval: Optional[timedelta] = None,
        +    request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None,
        +    client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
        +    storage_options: Optional[dict[str, str]] = None,
        +    session: Optional[_lancedb.Session] = None,
        +    manifest_enabled: bool = False,
        +    namespace_client_impl: Optional[str] = None,
        +    namespace_client_properties: Optional[dict[str, str]] = None,
        +    namespace_client_pushdown_operations: Optional[list[str]] = None,
             oauth_config: Optional[OAuthConfig] = None,
        +    **kwargs: Any,
         ) -> Catalog:
        -    """Connect synchronously to an HTTP(S) server's root catalog.
        +    """Connect synchronously to a root catalog using database connection settings.
         
             See [connect_catalog_async][lancedb.connect_catalog_async] for options.
        +    The inputs match [connect][lancedb.connect]; ``region`` is ignored with a
        +    warning when supplied. Namespace client options and embedded session settings
        +    are not supported. ``request_thread_pool`` is deprecated and unused, as in
        +    ``connect``.
             Local filesystem and object-store catalogs are not supported.
        +
        +    Examples
        +    --------
        +    ```python
        +    settings = {"api_key": "secret", "host_override": "https://my-server.example"}
        +    catalog = lancedb.connect_catalog("db://analytics", **settings)
        +    db = lancedb.connect("db://analytics", **settings)
        +    ```
             """
        +    unknown_kwargs = {
        +        key: value
        +        for key, value in kwargs.items()
        +        if key not in ("connection_timeout", "read_timeout")
        +    }
        +    if unknown_kwargs:
        +        raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}")
        +    for name, value in (
        +        ("namespace_client_impl", namespace_client_impl),
        +        ("namespace_client_pushdown_operations", namespace_client_pushdown_operations),
        +    ):
        +        if value is not None:
        +            raise NotImplementedError(
        +                f"{name} is not supported for catalog connections"
        +            )
        +    if region is not None:
        +        warnings.warn(
        +            "region is ignored by connect_catalog; the catalog endpoint "
        +            "is selected by host_override or uri.",
        +            UserWarning,
        +            stacklevel=2,
        +        )
        +    if request_thread_pool is not None:
        +        warnings.warn(
        +            "request_thread_pool is no longer used and will be removed in "
        +            "a future release.",
        +            DeprecationWarning,
        +            stacklevel=2,
        +        )
        +    if isinstance(client_config, dict):
        +        client_config = ClientConfig(**client_config)
        +    if client_config is None:
        +        client_config = ClientConfig()
        +    for name, field in (
        +        ("connection_timeout", "connect_timeout"),
        +        ("read_timeout", "read_timeout"),
        +    ):
        +        if kwargs.get(name) is not None:
        +            warnings.warn(
        +                f"{name} is deprecated and will be removed in a future release. "
        +                f"Please use client_config.timeout_config.{field} instead.",
        +                DeprecationWarning,
        +                stacklevel=2,
        +            )
        +            setattr(
        +                client_config.timeout_config,
        +                field,
        +                timedelta(seconds=kwargs[name]),
        +            )
        +    if (
        +        api_key is None
        +        and oauth_config is None
        +        and client_config.header_provider is None
        +    ):
        +        api_key = os.environ.get("LANCEDB_API_KEY")
             return Catalog(
                 LOOP.run(
                     connect_catalog_async(
        -                endpoint,
        +                uri,
                         api_key=api_key,
        +                host_override=host_override,
                         client_config=client_config,
                         sql_host_override=sql_host_override,
                         read_consistency_interval=read_consistency_interval,
        +                storage_options=storage_options,
        +                session=session,
        +                manifest_enabled=manifest_enabled,
        +                namespace_client_properties=namespace_client_properties,
                         oauth_config=oauth_config,
                     )
                 ),
        @@ -291,4 +424,5 @@ def connect_catalog(
                 client_config=client_config,
                 sql_host_override=sql_host_override,
                 oauth_config=oauth_config,
        +        storage_options=storage_options,
             )
        diff --git a/python/python/lancedb/cleanup.py b/python/python/lancedb/cleanup.py
        new file mode 100644
        index 000000000..8e4fd448c
        --- /dev/null
        +++ b/python/python/lancedb/cleanup.py
        @@ -0,0 +1,92 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +"""Results of durable remote version cleanup."""
        +
        +from dataclasses import dataclass, fields
        +import json
        +from typing import Optional
        +
        +
        +@dataclass(frozen=True)
        +class CleanupResult:
        +    """Version-deletion outcome, excluding best-effort auxiliary sweeps.
        +
        +    Unknown totals after retry/recovery are None, never fabricated zeroes.
        +    Completion does not guarantee that every orphaned file was reclaimed.
        +    """
        +
        +    format_version: int
        +    min_age_seconds: int
        +    statistics_complete: bool
        +    old_versions: Optional[int] = None
        +    bytes_removed: Optional[int] = None
        +    failed_deletes: Optional[int] = None
        +
        +    @classmethod
        +    def from_json(cls, raw: str) -> "CleanupResult":
        +        """Decode the versioned contract, preserving unknown measurements."""
        +        value = json.loads(raw)
        +        if (
        +            not isinstance(value, dict)
        +            or type(value.get("format_version")) is not int
        +            or value["format_version"] != 1
        +        ):
        +            raise ValueError("unsupported cleanup result format")
        +        if type(value.get("statistics_complete")) is not bool:
        +            raise ValueError("invalid cleanup result statistics_complete")
        +        for key in (
        +            "min_age_seconds",
        +            "old_versions",
        +            "bytes_removed",
        +            "failed_deletes",
        +        ):
        +            count = value.get(key)
        +            if count is None and key != "min_age_seconds":
        +                continue
        +            if type(count) is not int or count < 0:
        +                raise ValueError(f"invalid cleanup result {key}")
        +        counts = [value.get("old_versions"), value.get("bytes_removed")]
        +        if not value["statistics_complete"] and value.get("failed_deletes") is not None:
        +            raise ValueError("inconsistent cleanup failed-deletion measurement")
        +        if (
        +            value["statistics_complete"] and any(count is None for count in counts)
        +        ) or (
        +            not value["statistics_complete"]
        +            and any(count is not None for count in counts)
        +        ):
        +            raise ValueError("inconsistent cleanup result statistics")
        +        names = {field.name for field in fields(cls)}
        +        return cls(**{key: item for key, item in value.items() if key in names})
        +
        +
        +@dataclass(frozen=True)
        +class CleanupPlan:
        +    """Read-only version-deletion estimates, excluding auxiliary sweeps.
        +
        +    No job or deletion snapshot is reserved. Execution plans current state again.
        +    """
        +
        +    format_version: int
        +    source_version: int
        +    min_age_seconds: int
        +    cutoff_millis: int
        +    versions_to_remove: int
        +    bytes_to_remove: int
        +
        +    @classmethod
        +    def from_json(cls, raw: str) -> "CleanupPlan":
        +        value = json.loads(raw)
        +        if not isinstance(value, dict) or value.get("format_version") != 1:
        +            raise ValueError("unsupported cleanup preview format")
        +        names = {field.name for field in fields(cls)}
        +        for name in names:
        +            item = value.get(name)
        +            if type(item) is not int or (name != "cutoff_millis" and item < 0):
        +                raise ValueError(f"invalid cleanup preview {name}")
        +        return cls(**{key: item for key, item in value.items() if key in names})
        +
        +
        +def _validate_min_age_seconds(value: Optional[int]) -> None:
        +    if value is not None and (type(value) is not int or value < 0):
        +        raise ValueError("min_age_seconds must be a nonnegative integer or None")
        diff --git a/python/python/lancedb/compaction.py b/python/python/lancedb/compaction.py
        new file mode 100644
        index 000000000..823b0a281
        --- /dev/null
        +++ b/python/python/lancedb/compaction.py
        @@ -0,0 +1,37 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +"""Results of durable remote compaction jobs."""
        +
        +from dataclasses import dataclass, fields
        +import json
        +from typing import Optional
        +
        +
        +@dataclass(frozen=True)
        +class CompactionResult:
        +    """Actual committed outcome of one remote compaction invocation.
        +
        +    ``rows_failed`` counts planned live rows that were not committed, including
        +    partial progress. ``more_work`` means a bounded run left eligible work for
        +    another invocation. File/fragment counts are None if an older worker did
        +    not report them; they are never inferred from unrelated table versions.
        +    File counts include deletion files as well as data files.
        +    """
        +
        +    partial_commit: bool
        +    rows_succeeded: int
        +    rows_failed: int
        +    completion_percentage: float
        +    more_work: bool = False
        +    files_added: Optional[int] = None
        +    files_removed: Optional[int] = None
        +    fragments_added: Optional[int] = None
        +    fragments_removed: Optional[int] = None
        +
        +    @classmethod
        +    def from_json(cls, raw: str) -> "CompactionResult":
        +        """Decode a server result, ignoring additive fields from newer servers."""
        +        value = json.loads(raw)
        +        names = {field.name for field in fields(cls)}
        +        return cls(**{key: item for key, item in value.items() if key in names})
        diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py
        index 2cf438e72..61dafc855 100644
        --- a/python/python/lancedb/db.py
        +++ b/python/python/lancedb/db.py
        @@ -11,6 +11,7 @@ from pathlib import Path
         from dataclasses import asdict
         import json
         import sys
        +import warnings
         from typing import (
             TYPE_CHECKING,
             Any,
        @@ -57,8 +58,9 @@ from lance_namespace import (
         from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
         
         from . import __version__
        +from .server_info import ServerInfo
         from ._lancedb import _append_doc_url, connect as lancedb_connect  # type: ignore
        -from .functions import FunctionVersion, UdfDefinition
        +from .functions import FunctionVersion, FunctionDefinition
         from .graph import (
             AsyncPropertyGraph,
             EdgeTable,
        @@ -66,7 +68,7 @@ from .graph import (
             PropertyGraph,
             _definition_json,
         )
        -from .job import AsyncJob, Job, _typed_job
        +from .job import AsyncJob, Job, _opened_job, _typed_job
         from .storage_integration import SecretReference, StorageIntegrationInfo
         from .sql import AsyncQuery as AsyncSqlQuery
         from .sql import Query as SqlQuery
        @@ -77,6 +79,7 @@ from .materialized_view import (
             MaterializedViewSource,
             SelectArg,
             normalize_select,
        +    _validate_create_materialized_view,
         )
         from .secrets import (
             EnvVarSecret,
        @@ -115,6 +118,7 @@ from .namespace_utils import (
             _normalize_drop_namespace_mode,
             _normalize_drop_namespace_behavior,
         )
        +from .resources import _resource_options
         
         
         def _view_description(
        @@ -139,6 +143,50 @@ def _view_description(
             )
         
         
        +def _normalize_function_version(version: Optional[Union[int, str]]) -> Optional[str]:
        +    if version is None:
        +        return None
        +    if isinstance(version, bool):
        +        raise TypeError("version must be an int, str, or None")
        +    if isinstance(version, int):
        +        return str(version)
        +    if isinstance(version, str):
        +        return version
        +    raise TypeError("version must be an int, str, or None")
        +
        +
        +def _function_registration_decoder():
        +    """Parse a registration result and emit its server warnings once.
        +
        +    The warnings come from the scalar environment or, for a multiarchitecture
        +    image, each measured platform entry. They are part of the registration job
        +    result, not a new client-side package policy. Catalog get/list readbacks
        +    use ``FunctionVersion.from_json`` directly and therefore do not replay
        +    them.
        +    """
        +    warned = False
        +
        +    def decode(payload: str) -> FunctionVersion:
        +        nonlocal warned
        +        version = FunctionVersion.from_json(payload)
        +        if not warned:
        +            environments = [
        +                environment
        +                for environment in (
        +                    version.resolved_environment,
        +                    *version.resolved_environments.values(),
        +                )
        +                if environment is not None
        +            ]
        +            for environment in environments:
        +                for message in environment.warnings:
        +                    warnings.warn(message, UserWarning, stacklevel=3)
        +            warned = True
        +        return version
        +
        +    return decode
        +
        +
         class DBConnection(EnforceOverrides):
             """An active LanceDB connection interface.
         
        @@ -309,6 +357,9 @@ class DBConnection(EnforceOverrides):
             def table_exists(self, table_id: List[str]) -> bool:
                 """Check if a table exists.
         
        +        Use this method instead of checking membership in
        +        ``list_tables().tables``, which contains only one page of table names.
        +
                 Parameters
                 ----------
                 table_id: List[str]
        @@ -318,12 +369,20 @@ class DBConnection(EnforceOverrides):
                 Returns
                 -------
                 bool
        -            True if the table exists, False otherwise.
        +            True if the table exists, False if it is not found.
        +            Other errors, including permission errors, are propagated.
         
                 Raises
                 ------
                 NotImplementedError
        -            If the connection type does not support namespace operations.
        +            If the connection type does not support table existence checks.
        +
        +        Examples
        +        --------
        +        >>> def check_table(conn):
        +        ...     root_exists = conn.table_exists(["events"])
        +        ...     nested_exists = conn.table_exists(["analytics", "events"])
        +        ...     return root_exists, nested_exists
                 """
                 raise NotImplementedError(
                     "Namespace operations are not supported for this connection type"
        @@ -335,7 +394,11 @@ class DBConnection(EnforceOverrides):
                 page_token: Optional[str] = None,
                 limit: Optional[int] = None,
             ) -> TableListing:
        -        """List tables in this database, one page at a time.
        +        """Iterate over all tables in this database, fetching pages as needed.
        +
        +        ``list_tables().tables`` contains only the first page (100 names by
        +        default). Use ``list(list_tables())`` to collect all names, or
        +        ``table_exists([name])`` to check whether a particular table exists.
         
                 Parameters
                 ----------
        @@ -400,10 +463,17 @@ class DBConnection(EnforceOverrides):
                 azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
                 azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
                 azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
        +        azure_storage_account_access_key_secret: Optional[
        +            Union[str, SecretReference]
        +        ] = None,
                 gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
                 huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
             ) -> StorageIntegrationInfo:
        +        """Register storage access, preserving existing configuration with
        +        ``exist_ok=True``. Existing names are errors by default.
        +        """
                 raise NotImplementedError
         
             def describe_storage_integration(
        @@ -441,6 +511,8 @@ class DBConnection(EnforceOverrides):
                 storage_options: Optional[Dict[str, str]] = None,
                 data_storage_version: Optional[str] = None,
                 enable_v2_manifest_paths: Optional[bool] = None,
        +        initial_bases: Optional[List[Any]] = None,
        +        allow_external_blob_outside_bases: bool = False,
             ) -> Table:
                 """Create a [Table][lancedb.table.Table] in the database.
         
        @@ -504,6 +576,23 @@ class DBConnection(EnforceOverrides):
                 enable_v2_manifest_paths: optional, bool, default False
                     Deprecated.  Set `storage_options` when connecting to the database and set
                     `new_table_enable_v2_manifest_paths` in the options.
        +        initial_bases: list, optional
        +            Storage bases to register in the table's manifest in the same
        +            commit that creates it, so a create with data stays atomic. Each
        +            entry can be a [BasePath][lancedb.schema.BasePath], a dict with
        +            `path`, `name`, `is_dataset_root`, and `id` keys, or a
        +            `lance.DatasetBasePath`. Blob URIs that fall under a registered
        +            base are stored relative to it; other URIs need
        +            `allow_external_blob_outside_bases=True`. `None` and an empty
        +            list are equivalent. When supplying IDs for multiple bases, use
        +            distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
        +            describes the pinned-Lance limitation.
        +        allow_external_blob_outside_bases: bool, default False
        +            Store blob URIs that do not fall under a registered base. The row
        +            keeps a reference, so the objects have to stay readable. Set
        +            `initial_bases` instead when the URIs share a registered prefix.
        +            Defaults to rejecting such URIs. The opt-in applies only to the
        +            initial data; a later `add()` must enable it again.
                 Returns
                 -------
                 LanceTable
        @@ -669,17 +758,27 @@ class DBConnection(EnforceOverrides):
             def create_materialized_view(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: SelectArg = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
        +        exist_ok: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> MaterializedView:
                 """Define a materialized view named ``name`` over the table ``source``.
         
        +        ``exist_ok=True`` preserves an existing view's definition, data and
        +        refresh settings without refreshing it. Existing names error by default.
        +
                 LanceDB Embedded creation and refresh require a source build with the
                 ``experimental-functions`` Cargo feature. Published packages leave it
                 disabled; LanceDB Enterprise operations remain available.
        @@ -693,8 +792,12 @@ class DBConnection(EnforceOverrides):
                 ----------
                 name: str
                     The name of the view.
        -        source: str
        -            The name of the source table.
        +        source: str, optional
        +            The name of the source table. Required when ``query`` is omitted.
        +        query: str, optional
        +            The complete defining SQL query, including any GROUP BY or FROM
        +            Function. Mutually exclusive with ``source``, ``select``, ``where``
        +            and ``limit``. Supported query shapes depend on the backend.
                 select: list or dict, optional
                     The view's columns: column names, ``(alias, SQL expression)``
                     pairs, or a dict of the same. Omitting it selects every source
        @@ -713,10 +816,32 @@ class DBConnection(EnforceOverrides):
                     Positive, finite refresh interval in seconds in LanceDB Enterprise.
                     When omitted, the server determines when to refresh.
         
        +        total_cpu_millis: int, optional
        +            Default total CPU budget in millicores for initial population and
        +            refreshes. Overrides Function defaults. LanceDB Enterprise only.
        +        total_memory_bytes: int, optional
        +            Default total memory budget in bytes. LanceDB Enterprise only.
        +        total_gpu_count: int, optional
        +            Default total GPU budget across workers. LanceDB Enterprise only.
        +
                 Returns
                 -------
                 MaterializedView
        +
        +        Examples
        +        --------
        +        >>> view = db.create_materialized_view(  # doctest: +SKIP
        +        ...     "events_by_kind",
        +        ...     query="SELECT kind, count(*) AS n FROM events GROUP BY kind",
        +        ... )
                 """
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 raise NotImplementedError(
                     _append_doc_url(
                         "materialized views are not supported on this connection type",
        @@ -727,17 +852,27 @@ class DBConnection(EnforceOverrides):
             def create_materialized_view_async(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: SelectArg = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
        +        exist_ok: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> Job[None]:
                 """Submit materialized-view creation and return its job.
         
        +        ``exist_ok=True`` preserves an existing view without refreshing it.
        +        A skipped creation returns a completed job without a registry job ID.
        +
                 The job may already be complete in LanceDB Embedded. In LanceDB
                 Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL
                 server and the returned ``id`` is the registry job ID. That ID can be
        @@ -748,6 +883,13 @@ class DBConnection(EnforceOverrides):
                 Servers without early registry-handle support return a connection-scoped
                 query job instead. Its ID cannot be reopened with :meth:`open_job`.
                 """
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 raise NotImplementedError(
                     _append_doc_url(
                         "materialized views are not supported on this connection type",
        @@ -921,7 +1063,7 @@ class DBConnection(EnforceOverrides):
         
             def __contains__(self, name: str) -> bool:
                 """Return whether the root namespace contains the named table."""
        -        return name in self._all_table_names()
        +        return self.table_exists([name])
         
             def namespace_client(self) -> LanceNamespace:
                 """Get the equivalent namespace client for this connection.
        @@ -958,12 +1100,18 @@ class DBConnection(EnforceOverrides):
         
             def create_function(
                 self,
        -        definition: UdfDefinition,
        +        definition: FunctionDefinition,
                 *,
                 secrets: Optional[Sequence[EnvVarSecret]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
        +        refresh_lock: bool = False,
        +        progress: Any = False,
             ) -> FunctionVersion:
        -        """Build and register a scalar Python UDF, then return its version.
        +        """Build and register a scalar Python function, then return its version.
        +
        +        ``exist_ok=True`` returns the existing named Function version unchanged.
        +        By default, registration retains its existing version-creation behavior.
         
                 The server builds the OCI image and registers the completed artifact.
                 This is the blocking counterpart of :meth:`create_function_async`.
        @@ -971,8 +1119,8 @@ class DBConnection(EnforceOverrides):
         
                 Parameters
                 ----------
        -        definition : UdfDefinition
        -            A callable decorated with [udf][lancedb.udf].
        +        definition : FunctionDefinition
        +            A callable decorated with [function][lancedb.function].
                 secrets : sequence of EnvVarSecret, optional
                     One [EnvVarSecret][lancedb.secrets.EnvVarSecret] per credential the
                     Function needs, each naming a Secret and the environment variable
        @@ -981,38 +1129,65 @@ class DBConnection(EnforceOverrides):
                 namespace_path : list of str, optional
                     The namespace holding the Function. None or an empty list is the
                     root namespace.
        +        refresh_lock : bool, default False
        +            Ask the server to resolve a fresh environment lock instead of
        +            reusing the published version's lock.
        +        progress : bool, callable, or tqdm-like object, default False
        +            Display lifecycle state and elapsed time, or receive structured
        +            snapshots through a callback. See [Job.wait][lancedb.job.Job.wait].
        +
        +        When the registration job resolves, each resolved-environment warning
        +        reported by the server is emitted as a Python ``UserWarning``. Catalog
        +        reads do not replay those registration warnings.
         
                 Examples
                 --------
                 ```python
        -        db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"])
        +        db.create_secret("model-api-key", os.environ["MODEL_API_KEY"])
                 db.create_function(
                     analyze_caption,
                     secrets=[
                         EnvVarSecret(
        -                    secret_name="openai-prod", env_variable="OPENAI_API_KEY"
        +                    secret_name="model-api-key", env_variable="MODEL_API_KEY"
                         )
                     ],
                 )
                 ```
                 """
        -        return self.create_function_async(
        -            definition, secrets=secrets, namespace_path=namespace_path
        -        ).wait()
        +        job = self.create_function_async(
        +            definition,
        +            secrets=secrets,
        +            exist_ok=exist_ok,
        +            namespace_path=namespace_path,
        +            refresh_lock=refresh_lock,
        +        )
        +        if progress is False or progress is None:
        +            return job.wait()
        +        return job.wait(progress=progress)
         
             def create_function_async(
                 self,
        -        definition: UdfDefinition,
        +        definition: FunctionDefinition,
                 *,
                 secrets: Optional[Sequence[EnvVarSecret]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
        +        refresh_lock: bool = False,
             ) -> Job[FunctionVersion]:
        -        """Submit a scalar Python UDF for building and registration.
        +        """Submit a scalar Python function for building and registration.
        +
        +        ``exist_ok=True`` preserves an existing named version and its metadata.
        +        The default retains the existing version-creation behavior.
         
                 The server-side job builds the OCI image, then registers the completed
                 artifact. The returned job has type ``query`` and the SQL query UUID as
                 its ID. Waiting on it returns the immutable Function version.
                 LanceDB Embedded connections raise ``NotImplementedError``.
        +
        +        ``refresh_lock`` asks the server to resolve a fresh environment lock
        +        instead of reusing the published version's lock. Waiting on the job
        +        emits the server's resolved-environment warnings as Python warnings;
        +        reading the same version later does not repeat them.
                 """
                 raise NotImplementedError(
                     _append_doc_url(
        @@ -1026,10 +1201,15 @@ class DBConnection(EnforceOverrides):
                 self,
                 name: str,
                 *,
        -        version: str,
        +        version: Optional[Union[int, str]] = None,
                 namespace_path: Optional[List[str]] = None,
             ) -> FunctionVersion:
        -        """Open one exact immutable Function version from the remote catalog."""
        +        """Open an immutable Function version from the remote catalog.
        +
        +        ``version`` may be an integer or string. When omitted, the server
        +        resolves the latest currently visible revision and returns that exact
        +        immutable version.
        +        """
                 raise NotImplementedError(
                     _append_doc_url(
                         "Function catalog operations are not supported "
        @@ -1085,7 +1265,9 @@ class DBConnection(EnforceOverrides):
                 Returns True when the revision was removed and False for a repeated drop
                 or a missing name. A revision never published under an existing name is
                 an error. Dropping the last visible revision releases the name and
        -        schedules physical cleanup in the background. Use
        +        schedules physical cleanup in the background. When the remote server
        +        reports dependent warnings, they are emitted as ``UserWarning`` before
        +        this method returns. Use
                 :meth:`drop_function_async` to
                 access the query job, whose completion confirms catalog removal of the
                 revision. Local connections raise NotImplementedError.
        @@ -1123,14 +1305,24 @@ class DBConnection(EnforceOverrides):
                 )
         
             def create_secret(
        -        self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        value: str,
        +        *,
        +        exist_ok: bool = False,
        +        namespace_path: Optional[List[str]] = None,
             ) -> None:
                 """Create a named Secret in this database.
         
        -        Fails if the name is taken, so a create never silently becomes a
        -        rotation. Nothing reads the value back: it is bound to a Function by
        +        Fails if the name is taken unless ``exist_ok=True``, which leaves the
        +        existing value unchanged. Use :meth:`alter_secret` to rotate a Secret.
        +        Nothing reads the value back: it is bound to a Function by
                 name and resolved by the service when that Function runs. Local
                 connections raise ``NotImplementedError``.
        +
        +        Examples
        +        --------
        +        >>> db.create_secret("api-key", "credential", exist_ok=True)  # doctest: +SKIP
                 """
                 raise NotImplementedError(
                     _append_doc_url(
        @@ -1213,7 +1405,12 @@ class DBConnection(EnforceOverrides):
                 )
         
             def create_view(
        -        self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        query: str,
        +        *,
        +        exist_ok: bool = False,
        +        namespace_path: Optional[List[str]] = None,
             ) -> ViewDescription:
                 """Create a view: a named query the database plans on every read.
         
        @@ -1221,9 +1418,10 @@ class DBConnection(EnforceOverrides):
                 is refused now rather than at the first read. A view holds no rows, and
                 its readers see its sources as they are at read time.
         
        -        There is no replace: a name already taken is an error, and changing a
        -        view is a drop followed by a create. LanceDB Embedded connections raise
        -        ``NotImplementedError``.
        +        A name already taken is an error unless ``exist_ok=True``, which returns
        +        the existing view's stored query and schema without changing them.
        +        Changing a view is a drop followed by a create. LanceDB Embedded
        +        connections raise ``NotImplementedError``.
         
                 >>> import lancedb
                 >>> db = lancedb.connect("db://my_database")  # doctest: +SKIP
        @@ -1415,6 +1613,12 @@ class DBConnection(EnforceOverrides):
                 specification, result, failure and event history, so there is no
                 separate connection-level call for any of them.
         
        +        For a column refresh, ``wait()`` returns a
        +        [RefreshColumnResult][lancedb.functions.RefreshColumnResult], including
        +        when the refresh was started through SQL. Other job types return
        +        ``None`` from ``wait()``; their persisted result is available through
        +        ``job.result()`` after ``job.checkout_latest()``.
        +
                 Raises `JobNotFoundError` when the server has no such job, the way
                 `open_table` does for a missing table.
                 """
        @@ -1425,6 +1629,22 @@ class DBConnection(EnforceOverrides):
                     )
                 )
         
        +    def server_info(self) -> ServerInfo:
        +        """Return the responding server's build and Function runtime information.
        +
        +        This call submits no query, Function, or job. The response is a
        +        JSON-compatible dictionary, convenient to include in a bug report::
        +
        +            info = db.server_info()
        +            print(info["query_node"])  # release, git_sha, build_date
        +
        +        Requires System Usage permission. Embedded connections and older
        +        servers without this endpoint raise ``NotImplementedError``.
        +        Different calls can reach different builds during a rolling upgrade.
        +        Configured images do not identify the version of a running job.
        +        """
        +        raise NotImplementedError("Server build discovery requires a remote connection")
        +
             def list_gpu_classes(self) -> List[GpuClass]:
                 """List the operator-configured Function GPU classes.
         
        @@ -1444,13 +1664,39 @@ class DBConnection(EnforceOverrides):
                 )
         
             def list_jobs(
        -        self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
        +        self,
        +        *,
        +        page_token: Optional[str] = None,
        +        page_limit: Optional[int] = None,
        +        table: Optional[str] = None,
        +        namespace_path: Optional[List[str]] = None,
        +        state: Optional[
        +            Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
        +        ] = None,
        +        job_type: Optional[str] = None,
        +        job_types: Optional[List[str]] = None,
        +        created_at_gte_millis: Optional[int] = None,
        +        created_at_lt_millis: Optional[int] = None,
             ) -> Listing[JobInfo]:
        -        """List server-side jobs across the database's tables.
        +        """List server-side jobs, optionally filtered before pagination.
         
        -        Returns a lazy iterator. ``page_limit`` limits each request, not the total;
        -        ``page_token`` resumes from a saved token. Requests and errors occur during
        -        iteration. See [pagination state][lancedb.listing.AsyncListing].
        +        ``table`` names a table in ``namespace_path`` (the root by default).
        +        Listings include all branches of the table. A namespace filter requires
        +        ``table``.
        +        ``state`` uses registry states such as ``in_progress``, ``succeeded``,
        +        ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
        +        ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
        +        Creation-time bounds are Unix milliseconds, inclusive at
        +        ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
        +
        +        Returns a lazy iterator. ``page_limit`` limits each request, not the total.
        +        Resume a ``page_token`` with the same filters. Requests and errors occur
        +        during iteration. See [pagination state][lancedb.listing.AsyncListing].
        +
        +        For example, to inspect up to five jobs without fetching all history::
        +
        +            jobs = db.list_jobs(table="events", page_limit=5)
        +            first_five = jobs[:5]
                 """
                 raise NotImplementedError(
                     _append_doc_url(
        @@ -1507,17 +1753,26 @@ class DBConnection(EnforceOverrides):
                 *,
                 default_namespace_path: Optional[List[str]] = None,
                 parameters: Optional[QueryParameters] = None,
        +        timeout: Optional[timedelta] = None,
        +        read_timeout: Optional[timedelta] = None,
        +        cancel_on_drop: bool = False,
             ) -> pa.RecordBatchReader:
                 """Execute SQL and return a blocking Arrow reader.
         
                 This submits through :meth:`execute_query_async` and waits until the
                 initial result stream is readable. It does not wait for the full query
        -        to finish.
        +        to finish. A statement that ran as a server-side SQL job exposes the
        +        durable Job Registry id in the reader schema metadata under
        +        ``x-lancedb-sql-job-id``. Use :meth:`execute_query_async` when the
        +        query handle itself is needed.
                 """
                 return self.execute_query_async(
                     query,
                     default_namespace_path=default_namespace_path,
                     parameters=parameters,
        +            timeout=timeout,
        +            read_timeout=read_timeout,
        +            cancel_on_drop=cancel_on_drop,
                 ).reader()
         
             def execute_query_async(
        @@ -1526,6 +1781,9 @@ class DBConnection(EnforceOverrides):
                 *,
                 default_namespace_path: Optional[List[str]] = None,
                 parameters: Optional[QueryParameters] = None,
        +        timeout: Optional[timedelta] = None,
        +        read_timeout: Optional[timedelta] = None,
        +        cancel_on_drop: bool = False,
             ) -> SqlQuery:
                 """Start executing SQL and return its query handle.
         
        @@ -1544,13 +1802,30 @@ class DBConnection(EnforceOverrides):
                         parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10],
                     )
         
        -        Parameters are supported in queries, not in DDL or DML. With or
        -        without parameters, the server chooses whether to stream rows on the
        +        Parameters are supported in queries and, on compatible Enterprise servers,
        +        scalar filter values in ``PREWARM`` and ``EXPLAIN PREWARM``. Support for
        +        other statement types depends on the server.
        +
        +        With or without parameters, the server chooses whether to stream rows on the
                 initial call or return a polling continuation. The reader follows
                 either path transparently. Dropping an unread handle or its reader
        -        stops a directly streamed query; deferred execution requires explicit
        -        cancellation. Open ``reader()`` directly: a streamed query needs its
        -        reader to make progress and reports ``running`` until the stream ends.
        +        stops a directly streamed query. Set ``cancel_on_drop=True`` to also
        +        attempt cancellation of deferred Flight execution when its unread handle
        +        or reader is dropped. By default, deferred queries can be detached.
        +        Open ``reader()`` directly: a streamed query needs its reader to make
        +        progress and reports ``running`` until the stream ends.
        +        Once a server-side SQL job exists, ``describe().job_id`` exposes its
        +        durable Job Registry id while the query is still running. This is
        +        separate from the connection-scoped query ``id``.
        +
        +        ``timeout`` limits submission and result consumption together, starting
        +        when the query is submitted. It also applies before a reader is opened.
        +        ``read_timeout`` overrides the connection's limit for each server read.
        +        Both accept ``datetime.timedelta``. On expiry or a failed result read,
        +        the SDK stops reading and attempts to cancel Flight execution.
        +        Cancellation on drop is best effort and requires the connection's runtime
        +        to remain alive. Durable server-side jobs require explicit
        +        ``cancel_job(query.job_id)`` regardless of these options.
         
                 LanceDB Embedded connections do not support SQL.
                 """
        @@ -1736,11 +2011,40 @@ class LanceDBConnection(DBConnection):
                         "manifest_enabled": self._manifest_enabled,
                         "namespace_client_properties": self._namespace_client_properties,
                         "read_consistency_interval_seconds": (
        -                    rci.total_seconds() if rci else None
        +                    rci.total_seconds() if rci is not None else None
                         ),
                     }
                 )
         
        +    def _pickle_state(self) -> str:
        +        """Serialize this connection for pickle-based workers."""
        +        if self._session is not None:
        +            raise TypeError(
        +                "Cannot pickle a LanceDBConnection created with a Session; "
        +                "Session objects are not serializable. Create the Session in "
        +                "each worker process instead."
        +            )
        +        if self.uri.startswith("memory://"):
        +            raise TypeError(
        +                "Cannot pickle an in-memory LanceDBConnection because its tables "
        +                "exist only in this process. Pickle a LanceTable instead to "
        +                "export its data, or connect to a persistent URI."
        +            )
        +        return self.serialize()
        +
        +    def __getstate__(self) -> dict[str, str]:
        +        return {"serialized": self._pickle_state()}
        +
        +    def __setstate__(self, state: dict[str, str]) -> None:
        +        from . import deserialize_conn
        +
        +        connection = deserialize_conn(state["serialized"], for_worker=True)
        +        if not isinstance(connection, LanceDBConnection):
        +            raise TypeError(
        +                "Serialized connection did not reconstruct a LanceDBConnection"
        +            )
        +        self.__dict__.update(connection.__dict__)
        +
             async def _async_get_table_names(self, start_after: Optional[str], limit: int):
                 conn = AsyncConnection(await lancedb_connect(self.uri))
                 return await conn.table_names(start_after=start_after, limit=limit)
        @@ -1823,6 +2127,10 @@ class LanceDBConnection(DBConnection):
             ) -> DescribeNamespaceResponse:
                 return LOOP.run(self._conn.describe_namespace(namespace_path=namespace_path))
         
        +    @override
        +    def table_exists(self, table_id: List[str]) -> bool:
        +        return LOOP.run(self._conn.table_exists(table_id))
        +
             @override
             def list_tables(
                 self,
        @@ -1830,7 +2138,11 @@ class LanceDBConnection(DBConnection):
                 page_token: Optional[str] = None,
                 limit: Optional[int] = None,
             ) -> TableListing:
        -        """List tables in this database, one page at a time.
        +        """Iterate over all tables in this database, fetching pages as needed.
        +
        +        The ``tables`` attribute contains only the current page (100 names by
        +        default). Iterate over the listing to visit all pages, or use
        +        ``table_exists([name])`` to check for a particular table.
         
                 Parameters
                 ----------
        @@ -1868,7 +2180,9 @@ class LanceDBConnection(DBConnection):
                 """Get the names of all tables in the database. The names are sorted.
         
                 .. deprecated::
        -            Use :meth:`list_tables` instead, which provides proper pagination support.
        +            Iterate over :meth:`list_tables` to get all names, or use
        +            :meth:`table_exists` to check for a particular table. The listing's
        +            ``tables`` attribute contains only one page.
         
                 Parameters
                 ----------
        @@ -1888,7 +2202,8 @@ class LanceDBConnection(DBConnection):
                 import warnings
         
                 warnings.warn(
        -            "table_names() is deprecated, use list_tables() instead",
        +            "table_names() is deprecated, iterate list_tables() for all names "
        +            "or use table_exists([name]) to check existence",
                     DeprecationWarning,
                     stacklevel=2,
                 )
        @@ -1916,6 +2231,8 @@ class LanceDBConnection(DBConnection):
                 storage_options: Optional[Dict[str, str]] = None,
                 data_storage_version: Optional[str] = None,
                 enable_v2_manifest_paths: Optional[bool] = None,
        +        initial_bases: Optional[List[Any]] = None,
        +        allow_external_blob_outside_bases: bool = False,
             ) -> LanceTable:
                 """Create a table in the database.
         
        @@ -1946,6 +2263,8 @@ class LanceDBConnection(DBConnection):
                     storage_options=storage_options,
                     data_storage_version=data_storage_version,
                     enable_v2_manifest_paths=enable_v2_manifest_paths,
        +            initial_bases=initial_bases,
        +            allow_external_blob_outside_bases=allow_external_blob_outside_bases,
                 )
                 return tbl
         
        @@ -1957,6 +2276,7 @@ class LanceDBConnection(DBConnection):
                 namespace_path: Optional[List[str]] = None,
                 storage_options: Optional[Dict[str, str]] = None,
                 index_cache_size: Optional[int] = None,
        +        location: Optional[str] = None,
                 branch: Optional[str] = None,
                 version: Optional[int] = None,
             ) -> LanceTable:
        @@ -1969,6 +2289,10 @@ class LanceDBConnection(DBConnection):
                 namespace_path: List[str], optional
                     The namespace to open the table from.  When non-empty, the
                     table is resolved through the directory namespace client.
        +        location: str, optional
        +            The explicit location (URI) of the table. If provided, the table will be
        +            opened from this location instead of deriving it from the database URI
        +            and table name.
                 branch: str, optional
                     If provided, open a handle scoped to this branch instead of the
                     default branch. Reads and writes operate in the branch's context.
        @@ -2002,6 +2326,7 @@ class LanceDBConnection(DBConnection):
                         namespace_path=namespace_path,
                         storage_options=storage_options,
                         index_cache_size=index_cache_size,
        +                location=location,
                     )
                 except (RuntimeError, ValueError) as e:
                     if namespace_path and (
        @@ -2023,17 +2348,27 @@ class LanceDBConnection(DBConnection):
             def create_materialized_view(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: SelectArg = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
        +        exist_ok: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> MaterializedView:
                 """Define a materialized view named ``name`` over the table ``source``.
         
        +        ``exist_ok=True`` preserves an existing view's definition, data and
        +        refresh settings without refreshing it. Existing names error by default.
        +
                 LanceDB Embedded creation and refresh require a source build with the
                 ``experimental-functions`` Cargo feature. Published packages leave it
                 disabled; LanceDB Enterprise operations remain available.
        @@ -2055,16 +2390,30 @@ class LanceDBConnection(DBConnection):
                 >>> view.table.count_rows()  # doctest: +SKIP
                 1
                 """
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 LOOP.run(
                     self._conn.create_materialized_view(
                         name,
                         source,
        +                query=query,
                         select=select,
                         where=where,
                         limit=limit,
                         with_no_data=with_no_data,
        +                exist_ok=exist_ok,
                         auto_refresh_enabled=auto_refresh_enabled,
                         auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                total_gpu_count=total_gpu_count,
        +                gpu_class=gpu_class,
        +                gpu_count=gpu_count,
                     )
                 )
                 return MaterializedView(self.open_table(name))
        @@ -2073,25 +2422,46 @@ class LanceDBConnection(DBConnection):
             def create_materialized_view_async(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: SelectArg = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
        +        exist_ok: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> Job[None]:
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 job = LOOP.run(
                     self._conn.create_materialized_view_async(
                         name,
                         source,
        +                query=query,
                         select=select,
                         where=where,
                         limit=limit,
                         with_no_data=with_no_data,
        +                exist_ok=exist_ok,
                         auto_refresh_enabled=auto_refresh_enabled,
                         auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                total_gpu_count=total_gpu_count,
        +                gpu_class=gpu_class,
        +                gpu_count=gpu_count,
                     )
                 )
                 return Job(job)
        @@ -2147,6 +2517,7 @@ class LanceDBConnection(DBConnection):
                 source_version: Optional[int] = None,
                 source_tag: Optional[str] = None,
                 is_shallow: bool = True,
        +        exist_ok: bool = False,
             ) -> LanceTable:
                 """Clone a table from a source table.
         
        @@ -2171,6 +2542,8 @@ class LanceDBConnection(DBConnection):
                 is_shallow: bool, default True
                     Whether to perform a shallow clone (True) or deep clone (False).
                     Currently only shallow clone is supported.
        +        exist_ok: bool, default False
        +            Return the existing target unchanged instead of cloning over it.
         
                 Returns
                 -------
        @@ -2186,6 +2559,7 @@ class LanceDBConnection(DBConnection):
                         source_version=source_version,
                         source_tag=source_tag,
                         is_shallow=is_shallow,
        +                exist_ok=exist_ok,
                     )
                 )
                 return LanceTable.open(
        @@ -2284,14 +2658,20 @@ class LanceDBConnection(DBConnection):
             @override
             def create_function_async(
                 self,
        -        definition: UdfDefinition,
        +        definition: FunctionDefinition,
                 *,
                 secrets: Optional[Sequence[EnvVarSecret]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
        +        refresh_lock: bool = False,
             ) -> Job[FunctionVersion]:
                 job = LOOP.run(
                     self._conn.create_function_async(
        -                definition, secrets=secrets, namespace_path=namespace_path
        +                definition,
        +                secrets=secrets,
        +                exist_ok=exist_ok,
        +                namespace_path=namespace_path,
        +                refresh_lock=refresh_lock,
                     )
                 )
                 return Job(job)
        @@ -2301,9 +2681,10 @@ class LanceDBConnection(DBConnection):
                 self,
                 name: str,
                 *,
        -        version: str,
        +        version: Optional[Union[int, str]] = None,
                 namespace_path: Optional[List[str]] = None,
             ) -> FunctionVersion:
        +        version = _normalize_function_version(version)
                 return LOOP.run(
                     self._conn.get_function(
                         name, version=version, namespace_path=namespace_path
        @@ -2376,8 +2757,12 @@ class LanceDBConnection(DBConnection):
                 azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
                 azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
                 azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
        +        azure_storage_account_access_key_secret: Optional[
        +            Union[str, SecretReference]
        +        ] = None,
                 gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
                 huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
             ) -> StorageIntegrationInfo:
                 return LOOP.run(
        @@ -2393,8 +2778,10 @@ class LanceDBConnection(DBConnection):
                         azure_tenant_id_secret=azure_tenant_id_secret,
                         azure_client_id_secret=azure_client_id_secret,
                         azure_client_secret_secret=azure_client_secret_secret,
        +                azure_storage_account_access_key_secret=azure_storage_account_access_key_secret,
                         gcp_credentials_json_secret=gcp_credentials_json_secret,
                         huggingface_token_secret=huggingface_token_secret,
        +                exist_ok=exist_ok,
                         namespace_path=namespace_path,
                     )
                 )
        @@ -2433,9 +2820,18 @@ class LanceDBConnection(DBConnection):
         
             @override
             def create_secret(
        -        self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        value: str,
        +        *,
        +        exist_ok: bool = False,
        +        namespace_path: Optional[List[str]] = None,
             ) -> None:
        -        LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
        +        LOOP.run(
        +            self._conn.create_secret(
        +                name, value, exist_ok=exist_ok, namespace_path=namespace_path
        +            )
        +        )
         
             @override
             def alter_secret(
        @@ -2479,10 +2875,17 @@ class LanceDBConnection(DBConnection):
         
             @override
             def create_view(
        -        self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        query: str,
        +        *,
        +        exist_ok: bool = False,
        +        namespace_path: Optional[List[str]] = None,
             ) -> ViewDescription:
                 return LOOP.run(
        -            self._conn.create_view(name, query, namespace_path=namespace_path)
        +            self._conn.create_view(
        +                name, query, exist_ok=exist_ok, namespace_path=namespace_path
        +            )
                 )
         
             @override
        @@ -2584,16 +2987,52 @@ class LanceDBConnection(DBConnection):
         
             @override
             def list_jobs(
        -        self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
        +        self,
        +        *,
        +        page_token: Optional[str] = None,
        +        page_limit: Optional[int] = None,
        +        table: Optional[str] = None,
        +        namespace_path: Optional[List[str]] = None,
        +        state: Optional[
        +            Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
        +        ] = None,
        +        job_type: Optional[str] = None,
        +        job_types: Optional[List[str]] = None,
        +        created_at_gte_millis: Optional[int] = None,
        +        created_at_lt_millis: Optional[int] = None,
             ) -> Listing[JobInfo]:
        -        """List server-side jobs across the database's tables.
        +        """List server-side jobs, optionally filtered before pagination.
         
        -        Returns a lazy iterator. ``page_limit`` limits each request, not the total;
        -        ``page_token`` resumes from a saved token. Requests and errors occur during
        -        iteration. See [pagination state][lancedb.listing.AsyncListing].
        +        ``table`` names a table in ``namespace_path`` (the root by default).
        +        Listings include all branches of the table. A namespace filter requires
        +        ``table``.
        +        ``state`` uses registry states such as ``in_progress``, ``succeeded``,
        +        ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
        +        ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
        +        Creation-time bounds are Unix milliseconds, inclusive at
        +        ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
        +
        +        Returns a lazy iterator. ``page_limit`` limits each request, not the total.
        +        Resume a ``page_token`` with the same filters. Requests and errors occur
        +        during iteration. See [pagination state][lancedb.listing.AsyncListing].
        +
        +        For example, to inspect up to five jobs without fetching all history::
        +
        +            jobs = db.list_jobs(table="events", page_limit=5)
        +            first_five = jobs[:5]
                 """
                 return Listing(
        -            self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
        +            self._conn.list_jobs(
        +                page_token=page_token,
        +                page_limit=page_limit,
        +                table=table,
        +                namespace_path=namespace_path,
        +                state=state,
        +                job_type=job_type,
        +                job_types=job_types,
        +                created_at_gte_millis=created_at_gte_millis,
        +                created_at_lt_millis=created_at_lt_millis,
        +            )
                 )
         
             @override
        @@ -2851,6 +3290,9 @@ class AsyncConnection(object):
             async def table_exists(self, table_id: List[str]) -> bool:
                 """Check if a table exists.
         
        +        Use this method instead of checking membership in an awaited listing's
        +        ``tables`` attribute, which contains only one page of table names.
        +
                 Parameters
                 ----------
                 table_id: List[str]
        @@ -2876,7 +3318,11 @@ class AsyncConnection(object):
                 page_token: Optional[str] = None,
                 limit: Optional[int] = None,
             ) -> AsyncTableListing:
        -        """List tables in this database, one page at a time.
        +        """Iterate over all tables in this database, fetching pages as needed.
        +
        +        The ``tables`` attribute contains only the current page (100 names by
        +        default). Iterate over the listing to visit all pages, or use
        +        ``table_exists([name])`` to check for a particular table.
         
                 Parameters
                 ----------
        @@ -2915,7 +3361,9 @@ class AsyncConnection(object):
                 """List all tables in this database, in sorted order
         
                 .. deprecated::
        -            Use :meth:`list_tables` instead, which provides proper pagination support.
        +            Iterate over :meth:`list_tables` to get all names, or use
        +            :meth:`table_exists` to check for a particular table. The listing's
        +            ``tables`` attribute contains only one page.
         
                 Parameters
                 ----------
        @@ -2939,7 +3387,8 @@ class AsyncConnection(object):
                 import warnings
         
                 warnings.warn(
        -            "table_names() is deprecated, use list_tables() instead",
        +            "table_names() is deprecated, iterate list_tables() for all names "
        +            "or use table_exists([name]) to check existence",
                     DeprecationWarning,
                     stacklevel=2,
                 )
        @@ -2964,6 +3413,8 @@ class AsyncConnection(object):
                 embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None,
                 location: Optional[str] = None,
                 namespace_client: Optional[Any] = None,
        +        initial_bases: Optional[List[Any]] = None,
        +        allow_external_blob_outside_bases: bool = False,
             ) -> AsyncTable:
                 """Create an [AsyncTable][lancedb.table.AsyncTable] in the database.
         
        @@ -3021,6 +3472,23 @@ class AsyncConnection(object):
                     To enable stable row IDs (row IDs remain stable after compaction,
                     update, delete, and merges), set `new_table_enable_stable_row_ids`
                     to `"true"` in storage_options when connecting to the database.
        +        initial_bases: list, optional
        +            Storage bases to register in the table's manifest in the same
        +            commit that creates it, so a create with data stays atomic. Each
        +            entry can be a [BasePath][lancedb.schema.BasePath], a dict with
        +            `path`, `name`, `is_dataset_root`, and `id` keys, or a
        +            `lance.DatasetBasePath`. Blob URIs that fall under a registered
        +            base are stored relative to it; other URIs need
        +            `allow_external_blob_outside_bases=True`. `None` and an empty
        +            list are equivalent. When supplying IDs for multiple bases, use
        +            distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
        +            describes the pinned-Lance limitation.
        +        allow_external_blob_outside_bases: bool, default False
        +            Store blob URIs that do not fall under a registered base. The row
        +            keeps a reference, so the objects have to stay readable. Requires
        +            initial `data`; the opt-in applies only to that initial write, and
        +            a later `add()` must enable it again. Defaults to rejecting such
        +            URIs.
         
                 Returns
                 -------
        @@ -3132,6 +3600,25 @@ class AsyncConnection(object):
                 """
                 if namespace_path is None:
                     namespace_path = []
        +        if get_uri_scheme(self.uri) == "db":
        +            # The Enterprise create endpoint has no way to express either
        +            # option. Reject before sanitizing or reading `data`, and do not
        +            # point at a local-only or remote `add` path.
        +            if initial_bases:
        +                raise NotImplementedError(
        +                    "initial_bases is not supported for table creation in "
        +                    "LanceDB Enterprise"
        +                )
        +            if allow_external_blob_outside_bases:
        +                raise NotImplementedError(
        +                    "allow_external_blob_outside_bases is not supported for table "
        +                    "creation in LanceDB Enterprise"
        +                )
        +        if data is None and allow_external_blob_outside_bases:
        +            raise ValueError(
        +                "allow_external_blob_outside_bases requires initial data; "
        +                "pass it to add() for later writes"
        +            )
                 metadata = None
         
                 if embedding_functions is not None:
        @@ -3178,6 +3665,7 @@ class AsyncConnection(object):
                         storage_options=storage_options,
                         location=location,
                         namespace_client=namespace_client,
        +                initial_bases=initial_bases,
                     )
                 else:
                     data = data_to_reader(data, schema)
        @@ -3189,6 +3677,8 @@ class AsyncConnection(object):
                         storage_options=storage_options,
                         location=location,
                         namespace_client=namespace_client,
        +                initial_bases=initial_bases,
        +                allow_external_blob_outside_bases=allow_external_blob_outside_bases,
                     )
         
                 return AsyncTable(new_table)
        @@ -3285,26 +3775,49 @@ class AsyncConnection(object):
             async def create_materialized_view(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: SelectArg = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
        +        exist_ok: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> AsyncMaterializedView:
                 """Define a materialized view named ``name`` over the table ``source``.
         
        +        ``exist_ok=True`` preserves an existing view's definition, data and
        +        refresh settings without refreshing it. Existing names error by default.
        +
                 LanceDB Embedded creation and refresh require a source build with the
                 ``experimental-functions`` Cargo feature. Published packages leave it
                 disabled; LanceDB Enterprise operations remain available.
                 See
                 [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view].
                 """
        -        source, native_options = await self._materialized_view_source(
        -            source, select, where, limit
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
                 )
        +        _validate_create_materialized_view(source, query, select, where, limit)
        +        if source is not None:
        +            source, native_options = await self._materialized_view_source(
        +                source, select, where, limit
        +            )
        +        else:
        +            native_options = {}
        +        if query is not None:
        +            native_options["query"] = query
                 inner = await self._inner.create_materialized_view(
                     name,
                     source,
        @@ -3312,33 +3825,62 @@ class AsyncConnection(object):
                     filter=where,
                     limit=limit,
                     with_no_data=with_no_data,
        +            exist_ok=exist_ok,
                     auto_refresh_enabled=auto_refresh_enabled,
                     auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +            total_cpu_millis=total_cpu_millis,
        +            total_memory_bytes=total_memory_bytes,
        +            total_gpu_count=total_gpu_count,
                     **native_options,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
                 )
                 return AsyncMaterializedView(AsyncTable(inner))
         
             async def create_materialized_view_async(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: SelectArg = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
        +        exist_ok: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> AsyncJob[None]:
                 """Submit materialized-view creation and return its job.
         
        +        ``exist_ok=True`` preserves an existing view without refreshing it.
        +        A skipped creation returns a completed job without a registry job ID.
        +
                 Wait for the returned job before opening or querying the view. In LanceDB
                 Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id``
                 identifies that query on this connection.
                 """
        -        source, native_options = await self._materialized_view_source(
        -            source, select, where, limit
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
                 )
        +        _validate_create_materialized_view(source, query, select, where, limit)
        +        if source is not None:
        +            source, native_options = await self._materialized_view_source(
        +                source, select, where, limit
        +            )
        +        else:
        +            native_options = {}
        +        if query is not None:
        +            native_options["query"] = query
                 inner = await self._inner.create_materialized_view_async(
                     name,
                     source,
        @@ -3346,9 +3888,15 @@ class AsyncConnection(object):
                     filter=where,
                     limit=limit,
                     with_no_data=with_no_data,
        +            exist_ok=exist_ok,
                     auto_refresh_enabled=auto_refresh_enabled,
                     auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +            total_cpu_millis=total_cpu_millis,
        +            total_memory_bytes=total_memory_bytes,
        +            total_gpu_count=total_gpu_count,
                     **native_options,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
                 )
                 return AsyncJob(inner)
         
        @@ -3424,6 +3972,7 @@ class AsyncConnection(object):
                 source_version: Optional[int] = None,
                 source_tag: Optional[str] = None,
                 is_shallow: bool = True,
        +        exist_ok: bool = False,
             ) -> AsyncTable:
                 """Clone a table from a source table.
         
        @@ -3448,6 +3997,8 @@ class AsyncConnection(object):
                 is_shallow: bool, default True
                     Whether to perform a shallow clone (True) or deep clone (False).
                     Currently only shallow clone is supported.
        +        exist_ok: bool, default False
        +            Return the existing target unchanged instead of cloning over it.
         
                 Returns
                 -------
        @@ -3462,6 +4013,7 @@ class AsyncConnection(object):
                     source_version=source_version,
                     source_tag=source_tag,
                     is_shallow=is_shallow,
        +            exist_ok=exist_ok,
                 )
                 return AsyncTable(table)
         
        @@ -3563,7 +4115,13 @@ class AsyncConnection(object):
                 """Open a server-side job by id. See
                 [DBConnection.open_job][lancedb.db.DBConnection.open_job].
                 """
        -        return AsyncJob(await self._inner.open_job(job_id))
        +        return _opened_job(await self._inner.open_job(job_id))
        +
        +    async def server_info(self) -> ServerInfo:
        +        """Read the responding server's build information. See
        +        [DBConnection.server_info][lancedb.db.DBConnection.server_info].
        +        """
        +        return json.loads(await self._inner.server_info())
         
             async def list_gpu_classes(self) -> List[GpuClass]:
                 """List configured Function GPU classes. See
        @@ -3573,12 +4131,17 @@ class AsyncConnection(object):
         
             async def create_function_async(
                 self,
        -        definition: UdfDefinition,
        +        definition: FunctionDefinition,
                 *,
                 secrets: Optional[Sequence[EnvVarSecret]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
        +        refresh_lock: bool = False,
             ) -> AsyncJob[FunctionVersion]:
        -        """Submit a scalar Python UDF for building and registration.
        +        """Submit a scalar Python function for building and registration.
        +
        +        ``exist_ok=True`` preserves an existing named version and its metadata.
        +        The default retains the existing version-creation behavior.
         
                 The server-side job builds the OCI image, then registers the completed
                 artifact. The returned job has type ``query`` and the SQL query UUID as
        @@ -3588,23 +4151,31 @@ class AsyncConnection(object):
                 the environment variable its value arrives in. ``namespace_path`` is
                 the namespace the Function is registered in; None or an empty list is
                 the root. LanceDB Embedded connections raise ``NotImplementedError``.
        +        ``refresh_lock`` asks the server to resolve a fresh environment lock
        +        instead of reusing the published version's lock.
                 """
        -        if not isinstance(definition, UdfDefinition):
        -            raise TypeError("create_function_async requires a @udf definition")
        -        request = definition.bind_secrets(secrets)
        +        if not isinstance(definition, FunctionDefinition):
        +            raise TypeError("create_function_async requires a @function definition")
        +        request = definition.bind_secrets(secrets).with_refresh_lock(refresh_lock)
                 inner = await self._inner.create_function_async(
        -            request.to_canonical_json(), namespace_path
        +            request.to_canonical_json(), namespace_path, exist_ok=exist_ok
                 )
        -        return _typed_job(inner, FunctionVersion.from_json)
        +        return _typed_job(inner, _function_registration_decoder())
         
             async def get_function(
                 self,
                 name: str,
                 *,
        -        version: str,
        +        version: Optional[Union[int, str]] = None,
                 namespace_path: Optional[List[str]] = None,
             ) -> FunctionVersion:
        -        """Open one exact immutable Function version from the remote catalog."""
        +        """Open an immutable Function version from the remote catalog.
        +
        +        ``version`` may be an integer or string. When omitted, the server
        +        resolves the latest currently visible revision and returns that exact
        +        immutable version.
        +        """
        +        version = _normalize_function_version(version)
                 return FunctionVersion.from_json(
                     await self._inner.get_function(name, version, namespace_path)
                 )
        @@ -3647,9 +4218,29 @@ class AsyncConnection(object):
                 Returns True when the requested revision was removed and False for a
                 repeated drop or a missing name. A revision never published under an
                 existing name is an error. Only the last visible revision's removal
        -        releases the name and schedules background object cleanup.
        +        releases the name and schedules background object cleanup. When the
        +        remote server reports a warning, it is emitted as ``UserWarning``
        +        before this method returns, subject to the standard ``warnings``
        +        filters. A warnings-as-errors setting can therefore raise after the
        +        catalog removal; it does not roll back the drop. Older servers that
        +        omit the warning field remain silent.
                 """
        -        return await self._inner.drop_function(name, version, namespace_path)
        +        dropped, drop_warnings = await self._drop_function_with_warnings(
        +            name, version, namespace_path
        +        )
        +        for warning in drop_warnings:
        +            warnings.warn(warning, UserWarning, stacklevel=2)
        +        return dropped
        +
        +    async def _drop_function_with_warnings(
        +        self,
        +        name: str,
        +        version: str,
        +        namespace_path: Optional[List[str]] = None,
        +    ) -> Tuple[bool, List[str]]:
        +        return await self._inner._drop_function_with_warnings(
        +            name, version, namespace_path
        +        )
         
             async def drop_function_async(
                 self,
        @@ -3685,8 +4276,12 @@ class AsyncConnection(object):
                 azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
                 azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
                 azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
        +        azure_storage_account_access_key_secret: Optional[
        +            Union[str, SecretReference]
        +        ] = None,
                 gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
                 huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
             ) -> StorageIntegrationInfo:
                 """Register cloud storage access using database-owned credential Secrets.
        @@ -3694,19 +4289,27 @@ class AsyncConnection(object):
                 ``namespace_path`` follows Secret naming rules. A SecretReference can name
                 another database; a string names a root Secret in this database.
                 For Azure, set ``storage_provider="AZURE"``, ``azure_storage_account``,
        -        and Secret references for tenant ID, client ID and client secret.
        +        and either ``azure_storage_account_access_key_secret`` or the three
        +        Secret references for tenant ID, client ID and client secret.
                 For GCP, set ``storage_provider="GCP"`` and ``gcp_credentials_json_secret``
                 to a Secret containing the application credentials JSON file content.
                 For Hugging Face, set ``storage_provider="HUGGINGFACE"`` and
                 optionally set ``huggingface_token_secret`` to a Secret containing the
                 token; omitting it selects anonymous access at the default rate limits.
                 Registration returns setup instructions without verifying storage access.
        +
        +        ``exist_ok=True`` returns the stored configuration unchanged when the
        +        integration exists, preserving its provider, prefix and credential
        +        bindings. Existing names are errors by default.
                 """
        -        azure_options = (
        +        azure_service_principal = (
                     azure_tenant_id_secret,
                     azure_client_id_secret,
                     azure_client_secret_secret,
                 )
        +        azure_options = azure_service_principal + (
        +            azure_storage_account_access_key_secret,
        +        )
                 if storage_provider != "HUGGINGFACE" and huggingface_token_secret is not None:
                     raise ValueError(
                         "Hugging Face options require storage_provider HUGGINGFACE"
        @@ -3742,12 +4345,17 @@ class AsyncConnection(object):
                     ):
                         raise ValueError("GCP integrations cannot contain AWS or Azure options")
                 elif storage_provider == "AZURE":
        -            if not azure_storage_account or any(
        -                value is None for value in azure_options
        -            ):
        +            if not azure_storage_account:
        +                raise ValueError("Azure integrations require azure_storage_account")
        +            valid_credentials = (
        +                all(value is None for value in azure_service_principal)
        +                if azure_storage_account_access_key_secret is not None
        +                else all(value is not None for value in azure_service_principal)
        +            )
        +            if not valid_credentials:
                         raise ValueError(
        -                    "Azure requires a storage account and "
        -                    "all three credential Secret references"
        +                    "Specify either azure_storage_account_access_key_secret or "
        +                    "all three Azure service principal Secret references"
                         )
                     if any(
                         value is not None
        @@ -3804,11 +4412,16 @@ class AsyncConnection(object):
                     "azure_tenant_id_secret": reference(azure_tenant_id_secret),
                     "azure_client_id_secret": reference(azure_client_id_secret),
                     "azure_client_secret_secret": reference(azure_client_secret_secret),
        +            "azure_storage_account_access_key_secret": reference(
        +                azure_storage_account_access_key_secret
        +            ),
                     "gcp_credentials_json_secret": reference(gcp_credentials_json_secret),
                     "huggingface_token_secret": reference(huggingface_token_secret),
                     "aws_access_key_id_secret": reference(aws_access_key_id_secret),
                     "aws_secret_access_key_secret": reference(aws_secret_access_key_secret),
                 }
        +        if exist_ok:
        +            request["exist_ok"] = True
                 info = await self._inner.create_storage_integration(
                     validate_secret_name(name),
                     json.dumps(request),
        @@ -3854,17 +4467,30 @@ class AsyncConnection(object):
                 )
         
             async def create_secret(
        -        self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        value: str,
        +        *,
        +        exist_ok: bool = False,
        +        namespace_path: Optional[List[str]] = None,
             ) -> None:
                 """Create a named Secret in this database.
         
        -        Fails if the name is taken, so a create never silently becomes a
        -        rotation. Nothing reads the value back.
        +        Fails if the name is taken unless ``exist_ok=True``, which leaves the
        +        existing value unchanged. Use :meth:`alter_secret` to rotate a Secret.
        +        Nothing reads the value back.
        +
        +        Examples
        +        --------
        +        >>> await db.create_secret(  # doctest: +SKIP
        +        ...     "api-key", "credential", exist_ok=True
        +        ... )
                 """
                 await self._inner.create_secret(
                     validate_secret_name(name),
                     value,
                     list(validate_namespace_path(namespace_path)),
        +            exist_ok=exist_ok,
                 )
         
             async def alter_secret(
        @@ -3925,7 +4551,12 @@ class AsyncConnection(object):
                 )
         
             async def create_view(
        -        self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        query: str,
        +        *,
        +        exist_ok: bool = False,
        +        namespace_path: Optional[List[str]] = None,
             ) -> ViewDescription:
                 """Create a view: a named query the database plans on every read.
         
        @@ -3933,7 +4564,9 @@ class AsyncConnection(object):
                 [DBConnection.create_view][lancedb.DBConnection.create_view].
                 """
                 return _view_description(
        -            await self._inner.create_view(name, query, list(namespace_path or []))
        +            await self._inner.create_view(
        +                name, query, list(namespace_path or []), exist_ok=exist_ok
        +            )
                 )
         
             async def describe_view(
        @@ -4056,16 +4689,56 @@ class AsyncConnection(object):
                 )
         
             def list_jobs(
        -        self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
        +        self,
        +        *,
        +        page_token: Optional[str] = None,
        +        page_limit: Optional[int] = None,
        +        table: Optional[str] = None,
        +        namespace_path: Optional[List[str]] = None,
        +        state: Optional[
        +            Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
        +        ] = None,
        +        job_type: Optional[str] = None,
        +        job_types: Optional[List[str]] = None,
        +        created_at_gte_millis: Optional[int] = None,
        +        created_at_lt_millis: Optional[int] = None,
             ) -> AsyncListing[JobInfo]:
        -        """List server-side jobs across the database's tables.
        +        """List server-side jobs, optionally filtered before pagination.
         
        -        Returns a lazy iterator. ``page_limit`` limits each request, not the total;
        -        ``page_token`` resumes from a saved token. Requests and errors occur during
        -        iteration. See [pagination state][lancedb.listing.AsyncListing].
        +        ``table`` names a table in ``namespace_path`` (the root by default).
        +        Listings include all branches of the table. A namespace filter requires
        +        ``table``.
        +        ``state`` uses registry states such as ``in_progress``, ``succeeded``,
        +        ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
        +        ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
        +        Creation-time bounds are Unix milliseconds, inclusive at
        +        ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
        +
        +        Returns a lazy iterator. ``page_limit`` limits each request, not the total.
        +        Resume a ``page_token`` with the same filters. Requests and errors occur
        +        during iteration. See [pagination state][lancedb.listing.AsyncListing].
        +
        +        For example, to inspect up to five jobs without fetching all history::
        +
        +            jobs = db.list_jobs(table="events", page_limit=5)
        +            first_five = []
        +            async for job in jobs:
        +                first_five.append(job)
        +                if len(first_five) == 5:
        +                    break
                 """
                 return AsyncListing(
        -            self._inner.list_jobs(page_token=page_token, page_limit=page_limit)
        +            self._inner.list_jobs(
        +                page_token=page_token,
        +                page_limit=page_limit,
        +                table=table,
        +                namespace_path=namespace_path,
        +                state=state,
        +                job_type=job_type,
        +                job_types=job_types,
        +                created_at_gte_millis=created_at_gte_millis,
        +                created_at_lt_millis=created_at_lt_millis,
        +            )
                 )
         
             async def cancel_job(self, job_id: str) -> bool:
        @@ -4100,17 +4773,26 @@ class AsyncConnection(object):
                 *,
                 default_namespace_path: Optional[List[str]] = None,
                 parameters: Optional[QueryParameters] = None,
        +        timeout: Optional[timedelta] = None,
        +        read_timeout: Optional[timedelta] = None,
        +        cancel_on_drop: bool = False,
             ) -> AsyncRecordBatchReader:
                 """Execute SQL and return an asynchronous Arrow reader.
         
                 This submits through :meth:`execute_query_async` and waits until the
                 initial result stream is readable. It does not wait for the full query
        -        to finish.
        +        to finish. A statement that ran as a server-side SQL job exposes the
        +        durable Job Registry id in the reader schema metadata under
        +        ``x-lancedb-sql-job-id``. Use :meth:`execute_query_async` when the
        +        query handle itself is needed.
                 """
                 submitted = await self.execute_query_async(
                     query,
                     default_namespace_path=default_namespace_path,
                     parameters=parameters,
        +            timeout=timeout,
        +            read_timeout=read_timeout,
        +            cancel_on_drop=cancel_on_drop,
                 )
                 return await submitted.reader()
         
        @@ -4120,6 +4802,9 @@ class AsyncConnection(object):
                 *,
                 default_namespace_path: Optional[List[str]] = None,
                 parameters: Optional[QueryParameters] = None,
        +        timeout: Optional[timedelta] = None,
        +        read_timeout: Optional[timedelta] = None,
        +        cancel_on_drop: bool = False,
             ) -> AsyncSqlQuery:
                 """Start executing SQL and return its query handle.
         
        @@ -4127,6 +4812,11 @@ class AsyncConnection(object):
                 references. The namespace defaults to ``["public"]``. ``parameters``
                 binds values to ``$1`` / ``$name`` placeholders; see
                 [DBConnection.execute_query_async][lancedb.db.DBConnection.execute_query_async].
        +        ``timeout`` covers submission through result consumption, including
        +        time before opening a reader. ``read_timeout`` limits each server read.
        +        ``cancel_on_drop=True`` also attempts to cancel deferred Flight execution
        +        when its unread handle or reader is dropped. See the synchronous method
        +        above for cancellation and durable-job behavior.
                 LanceDB Embedded connections raise ``NotImplementedError``.
                 """
                 return AsyncSqlQuery(
        @@ -4134,6 +4824,9 @@ class AsyncConnection(object):
                         query,
                         default_namespace_path=default_namespace_path,
                         parameters=to_parameter_batch(parameters),
        +                timeout=timeout,
        +                read_timeout=read_timeout,
        +                cancel_on_drop=cancel_on_drop,
                     )
                 )
         
        diff --git a/python/python/lancedb/embeddings/__init__.py b/python/python/lancedb/embeddings/__init__.py
        index 679407610..437454408 100644
        --- a/python/python/lancedb/embeddings/__init__.py
        +++ b/python/python/lancedb/embeddings/__init__.py
        @@ -9,7 +9,7 @@ from .base import (
             TextEmbeddingFunction,
             UntrustedEmbeddingConfigError,
         )
        -from .bedrock import BedRockText
        +from .bedrock import BedrockImage, BedRockText
         from .cohere import CohereEmbeddingFunction
         from .gemini_text import GeminiText
         from .instructor import InstructorEmbeddingFunction
        @@ -45,6 +45,7 @@ __all__ = [
             "NvidiaEmbeddings",
             "OpenClipEmbeddings",
             "BedRockText",
        +    "BedrockImage",
             "CohereEmbeddingFunction",
             "GeminiText",
             "GteEmbeddings",
        diff --git a/python/python/lancedb/embeddings/bedrock.py b/python/python/lancedb/embeddings/bedrock.py
        index dc93a2da9..4456f943b 100644
        --- a/python/python/lancedb/embeddings/bedrock.py
        +++ b/python/python/lancedb/embeddings/bedrock.py
        @@ -2,21 +2,66 @@
         # SPDX-FileCopyrightText: Copyright The LanceDB Authors
         
         
        +import base64
        +import io
         import json
         from functools import cached_property
        -from typing import List, Union
        +from pathlib import Path
        +from typing import TYPE_CHECKING, List, Literal, Union
         
         import numpy as np
         from pydantic import ConfigDict
         
         from ..util import attempt_import_or_raise
        -from .base import TextEmbeddingFunction
        +from .base import EmbeddingFunction, TextEmbeddingFunction
         from .registry import register
        -from .utils import TEXT
        +from .utils import IMAGES, TEXT, retry_with_exponential_backoff
        +
        +if TYPE_CHECKING:
        +    from PIL.Image import Image
        +
        +
        +class _BedrockEmbeddingFunction(EmbeddingFunction):
        +    name: str
        +    region: str = "us-east-1"
        +
        +    model_config = ConfigDict(ignored_types=(cached_property,))
        +
        +    def _invoke_model(self, body: str, *, max_retries: int = 0) -> dict:
        +        invoke = self.client.invoke_model
        +        if max_retries > 0:
        +            invoke = retry_with_exponential_backoff(invoke, max_retries=max_retries)
        +        response = invoke(
        +            body=body,
        +            modelId=self.name,
        +            accept="application/json",
        +            contentType="application/json",
        +        )
        +        return json.loads(response["body"].read())
        +
        +    @cached_property
        +    def client(self):
        +        """The boto3 Bedrock Runtime client."""
        +        boto3 = attempt_import_or_raise("boto3")
        +        return self._runtime_client(boto3.Session())
        +
        +    def _runtime_client(self, session, **credentials):
        +        botocore = attempt_import_or_raise("botocore")
        +        retry_config = botocore.config.Config(
        +            region_name=self.region,
        +            # The embedding function handles retries.
        +            retries={"max_attempts": 0, "mode": "standard"},
        +        )
        +        return session.client(
        +            service_name="bedrock-runtime",
        +            config=retry_config,
        +            region_name=self.region,
        +            **credentials,
        +        )
         
         
         @register("bedrock-text")
        -class BedRockText(TextEmbeddingFunction):
        +class BedRockText(_BedrockEmbeddingFunction, TextEmbeddingFunction):
             """
             Parameters
             ----------
        @@ -59,14 +104,35 @@ class BedRockText(TextEmbeddingFunction):
             """
         
             name: str = "amazon.titan-embed-text-v1"
        -    region: str = "us-east-1"
             assumed_role: Union[str, None] = None
             profile_name: Union[str, None] = None
             role_session_name: str = "lancedb-embeddings"
             source_input_type: str = "search_document"
             query_input_type: str = "search_query"
         
        -    model_config = ConfigDict(ignored_types=(cached_property,))
        +    @cached_property
        +    def client(self):
        +        """The boto3 Bedrock Runtime client."""
        +        boto3 = attempt_import_or_raise("boto3")
        +        session = (
        +            boto3.Session(region_name=self.region, profile_name=self.profile_name)
        +            if self.profile_name
        +            else boto3.Session()
        +        )
        +        if not self.assumed_role:
        +            return self._runtime_client(session)
        +
        +        sts = session.client("sts")
        +        credentials = sts.assume_role(
        +            RoleArn=self.assumed_role,
        +            RoleSessionName=self.role_session_name,
        +        )["Credentials"]
        +        return self._runtime_client(
        +            session,
        +            aws_access_key_id=credentials["AccessKeyId"],
        +            aws_secret_access_key=credentials["SecretAccessKey"],
        +            aws_session_token=credentials["SessionToken"],
        +        )
         
             def ndims(self):
                 # return len(self._generate_embedding("test"))
        @@ -145,16 +211,7 @@ class BedRockText(TextEmbeddingFunction):
                 body = json.dumps(input_body)
         
                 try:
        -            # invoke bedrock API
        -            response = self.client.invoke_model(
        -                body=body,
        -                modelId=self.name,
        -                accept="application/json",
        -                contentType="application/json",
        -            )
        -
        -            # format output based on provider
        -            response_body = json.loads(response.get("body").read())
        +            response_body = self._invoke_model(body)
                     if provider == "cohere":
                         return response_body.get("embeddings")[0]
                     else:
        @@ -170,50 +227,155 @@ class BedRockText(TextEmbeddingFunction):
                         """
                     raise ValueError(f"Error raised by boto3 client: {e}. \n {help_txt}")
         
        -    @cached_property
        -    def client(self):
        -        """Create a boto3 client for Amazon Bedrock service
         
        -        Returns
        -        -------
        -        boto3.client
        -            The boto3 client for Amazon Bedrock service
        -        """
        -        botocore = attempt_import_or_raise("botocore")
        -        boto3 = attempt_import_or_raise("boto3")
        +@register("bedrock-image")
        +class BedrockImage(_BedrockEmbeddingFunction):
        +    """Embed images and search them by text or Pillow image using Amazon Bedrock.
         
        -        session_kwargs = {"region_name": self.region}
        -        client_kwargs = {**session_kwargs}
        +    Install `boto3` and `pillow` to use this embedding function. Use a binary
        +    source column (`bytes`) for encoded image bytes or a string
        +    source column (`str`) for file paths readable by the process that adds rows.
        +    Pillow detects the image format from the file contents. Null source values
        +    produce null embeddings.
         
        -        if self.profile_name:
        -            session_kwargs["profile_name"] = self.profile_name
        +    Both models accept PNG and JPEG sources. `cohere.embed-v4:0` also accepts
        +    WebP and GIF. For queries, pass a text string or a Pillow image. Images
        +    used as queries are encoded in RGB PNG format before calling Bedrock. With
        +    [AsyncTable.search][lancedb.table.AsyncTable.search], pass
        +    `query_type="vector"` for Pillow image queries.
         
        -        retry_config = botocore.config.Config(
        -            region_name=self.region,
        -            retries={
        -                "max_attempts": 0,  # disable this as retries retries are handled
        -                "mode": "standard",
        -            },
        -        )
        -        session = (
        -            boto3.Session(**session_kwargs) if self.profile_name else boto3.Session()
        -        )
        -        if self.assumed_role:  # if not using default credentials
        -            sts = session.client("sts")
        -            response = sts.assume_role(
        -                RoleArn=str(self.assumed_role),
        -                RoleSessionName=self.role_session_name,
        +    This function uses the boto3 default credential chain configured by your
        +    application, including `AWS_PROFILE` or the application's IAM role.
        +
        +    Parameters
        +    ----------
        +    name : str, default "amazon.titan-embed-image-v1"
        +        Model ID to invoke on Amazon Bedrock. `amazon.titan-embed-image-v1`
        +        returns 1024 dimensions. `cohere.embed-v4:0` returns 1536 dimensions.
        +    region : str, default "us-east-1"
        +        AWS Region where the model is available.
        +    max_retries : int, default 7
        +        Maximum retries per Bedrock request. Set to `0` to disable retries.
        +
        +    Examples
        +    --------
        +    ```python
        +    from pathlib import Path
        +
        +    import lancedb
        +    from lancedb.embeddings import get_registry
        +    from lancedb.pydantic import LanceModel, Vector
        +    from PIL import Image
        +
        +    model = get_registry().get("bedrock-image").create()
        +
        +    class Photo(LanceModel):
        +        image: bytes = model.SourceField()
        +        vector: Vector(model.ndims()) = model.VectorField()
        +
        +    db = lancedb.connect("photos_db")
        +    table = db.create_table("photos", schema=Photo)
        +    table.add([{"image": Path("sunset.jpg").read_bytes()}])
        +
        +    matches = table.search("sunset over the ocean").limit(5).to_list()
        +    with Image.open("query.png") as query:
        +        similar = table.search(query).limit(5).to_list()
        +    ```
        +    """
        +
        +    # Table metadata can select a model and region. Credentials come from the
        +    # application, so reject settings such as a profile name or role ARN.
        +    model_config = ConfigDict(extra="forbid")
        +
        +    name: Literal["amazon.titan-embed-image-v1", "cohere.embed-v4:0"] = (
        +        "amazon.titan-embed-image-v1"
        +    )
        +
        +    def ndims(self) -> int:
        +        return 1024 if self.name == "amazon.titan-embed-image-v1" else 1536
        +
        +    def compute_source_embeddings(self, images: IMAGES) -> list[list[float] | None]:
        +        return self._embed_sources(images, max_retries=0)
        +
        +    def compute_query_embeddings(self, query: "str | Image") -> list[list[float]]:
        +        return self._embed_query(query, max_retries=0)
        +
        +    # A transient failure can retry its own request without replaying earlier
        +    # images or repeating local image encoding and response parsing.
        +    def compute_source_embeddings_with_retry(
        +        self, images: IMAGES, *args, **kwargs
        +    ) -> list[list[float] | None]:
        +        return self._embed_sources(images, max_retries=self.max_retries)
        +
        +    def compute_query_embeddings_with_retry(
        +        self, query: "str | Image", *args, **kwargs
        +    ) -> list[list[float]]:
        +        return self._embed_query(query, max_retries=self.max_retries)
        +
        +    def _embed_sources(
        +        self, images: IMAGES, *, max_retries: int
        +    ) -> list[list[float] | None]:
        +        values = [images] if isinstance(images, bytes) else self.sanitize_input(images)
        +        embeddings = []
        +        for image in values:
        +            if image is None:
        +                embeddings.append(None)
        +                continue
        +            image_bytes = Path(image).read_bytes() if isinstance(image, str) else image
        +            image_module = attempt_import_or_raise("PIL.Image", "pillow")
        +            with image_module.open(io.BytesIO(image_bytes)) as decoded:
        +                payload = self._image_payload(image_bytes, decoded.format)
        +            embeddings.append(
        +                self._embed(
        +                    payload, input_type="search_document", max_retries=max_retries
        +                )
                     )
        -            client_kwargs["aws_access_key_id"] = response["Credentials"]["AccessKeyId"]
        -            client_kwargs["aws_secret_access_key"] = response["Credentials"][
        -                "SecretAccessKey"
        -            ]
        -            client_kwargs["aws_session_token"] = response["Credentials"]["SessionToken"]
        +        return embeddings
         
        -        service_name = "bedrock-runtime"
        +    def _embed_query(
        +        self, query: "str | Image", *, max_retries: int
        +    ) -> list[list[float]]:
        +        if isinstance(query, str):
        +            payload = (
        +                {"inputText": query}
        +                if self.name == "amazon.titan-embed-image-v1"
        +                else {"texts": [query]}
        +            )
        +        else:
        +            image_module = attempt_import_or_raise("PIL.Image", "pillow")
        +            if not isinstance(query, image_module.Image):
        +                raise TypeError("Bedrock image queries must be text or a Pillow image")
        +            with io.BytesIO() as buffer:
        +                query.convert("RGB").save(buffer, format="PNG")
        +                payload = self._image_payload(buffer.getvalue(), "PNG")
        +        return [
        +            self._embed(payload, input_type="search_query", max_retries=max_retries)
        +        ]
         
        -        bedrock_client = session.client(
        -            service_name=service_name, config=retry_config, **client_kwargs
        -        )
        +    def _image_payload(self, image_bytes: bytes, image_format: str | None) -> dict:
        +        encoded = base64.b64encode(image_bytes).decode("ascii")
        +        if self.name == "amazon.titan-embed-image-v1":
        +            if image_format not in ("JPEG", "PNG"):
        +                raise ValueError(
        +                    "Titan Multimodal Embeddings accepts PNG and JPEG images"
        +                )
        +            return {"inputImage": encoded}
         
        -        return bedrock_client
        +        if image_format not in ("JPEG", "PNG", "WEBP", "GIF"):
        +            raise ValueError("Cohere Embed v4 accepts PNG, JPEG, WebP, and GIF images")
        +        return {"images": [f"data:image/{image_format.lower()};base64,{encoded}"]}
        +
        +    def _embed(
        +        self, payload: dict, *, input_type: str, max_retries: int
        +    ) -> list[float]:
        +        is_cohere = self.name == "cohere.embed-v4:0"
        +        if is_cohere:
        +            payload["input_type"] = input_type
        +            payload["embedding_types"] = ["float"]
        +
        +        response = self._invoke_model(json.dumps(payload), max_retries=max_retries)
        +        if is_cohere:
        +            return response["embeddings"]["float"][0]
        +        if response.get("message"):
        +            raise ValueError(response["message"])
        +        return response["embedding"]
        diff --git a/python/python/lancedb/embeddings/cohere.py b/python/python/lancedb/embeddings/cohere.py
        index 286f658ad..a885a3f6a 100644
        --- a/python/python/lancedb/embeddings/cohere.py
        +++ b/python/python/lancedb/embeddings/cohere.py
        @@ -3,27 +3,48 @@
         
         
         import os
        -from typing import ClassVar, List, Union
        +from functools import cached_property
        +from importlib.metadata import version
        +from typing import ClassVar, List, Literal, Optional, Union
        +from urllib.parse import urlsplit
         
         import numpy as np
        +from packaging.version import Version
        +from pydantic import Field, model_validator
         
         from ..util import attempt_import_or_raise
         from .base import TextEmbeddingFunction
         from .registry import register
        -from .utils import api_key_not_found_help, TEXT
        +from .utils import (
        +    TEXT,
        +    _get_http_status,
        +    api_key_not_found_help,
        +    retry_with_exponential_backoff,
        +)
        +
        +
        +_COHERE_V2_MIN_VERSION = "5.15.0"
        +_COHERE_V2_MAX_TEXTS = 96
        +
        +
        +def _is_redirect_error(error: Exception) -> bool:
        +    status = _get_http_status(error)
        +    return status is not None and 300 <= status < 400
         
         
         @register("cohere")
         class CohereEmbeddingFunction(TextEmbeddingFunction):
             """
        -    An embedding function that uses the Cohere API
        +    An embedding function for Cohere text models, including Cohere Embed v4
        +    deployed on Azure AI Foundry through the native Cohere Embed API v2.
         
        -    https://docs.cohere.com/docs/multilingual-language-models
        +    https://docs.cohere.com/v2/reference/embed
         
             Parameters
             ----------
             name : str, default "embed-multilingual-v3.0"
        -        The name of the model to use. List of acceptable models:
        +        The model name. For a custom ``base_url``, supply the deployed model name
        +        explicitly. The default Cohere API supports these models:
         
                     * embed-english-v3.0
                     * embed-multilingual-v3.0
        @@ -41,7 +62,24 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
                 The input type for the source column in the database
         
             query_input_type : str, default "search_query"
        -        The input type for the query column in the database
        +        The input type for the query column in the database.
        +
        +    base_url : str, optional
        +        Native Cohere API v2 base URL. For Foundry, use
        +        ``https://.services.ai.azure.com/providers/cohere``. The Cohere
        +        SDK appends ``/v2/embed``. This path requires ``cohere>=5.15.0`` and uses
        +        ``search_document`` and ``search_query`` for text retrieval.
        +
        +    output_dimension : int, optional
        +        Required with ``base_url``. Choose an output dimension supported by the
        +        deployed model. This also sets the vector column dimension.
        +
        +    api_key : str, optional
        +        Required with ``base_url``. Use a registry variable reference such as
        +        ``$var:foundry-cohere-key`` and set its value with ``registry.set_var``.
        +        To restore a table in a new process, set the variable again and trust
        +        the endpoint with
        +        [allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint].
         
             Notes
             -----
        @@ -89,8 +127,68 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
             source_input_type: str = "search_document"
             query_input_type: str = "search_query"
             client: ClassVar = None
        +    base_url: Optional[str] = None
        +    output_dimension: Optional[int] = Field(default=None, gt=0)
        +    api_key: Optional[str] = Field(default=None, repr=False)
        +
        +    @classmethod
        +    def create(cls, **kwargs):
        +        api_key = kwargs.get("api_key")
        +        if (
        +            isinstance(api_key, str)
        +            and api_key.startswith("$var:")
        +            and ":" in api_key[len("$var:") :]
        +        ):
        +            raise ValueError(
        +                "Cohere api_key must use a registry variable without a default"
        +            )
        +        return super().create(**kwargs)
        +
        +    @model_validator(mode="after")
        +    def _validate_endpoint_config(self):
        +        if self.base_url is None:
        +            if self.output_dimension is not None or self.api_key is not None:
        +                raise ValueError("Cohere output_dimension and api_key require base_url")
        +            return self
        +
        +        url = urlsplit(self.base_url)
        +        if (
        +            url.scheme not in ("http", "https")
        +            or not url.hostname
        +            or url.username is not None
        +            or url.query
        +            or url.fragment
        +        ):
        +            raise ValueError(
        +                "Cohere base_url must be an HTTP(S) URL without credentials, "
        +                "a query string, or a fragment"
        +            )
        +        if "name" not in self.model_fields_set or not self.name.strip():
        +            raise ValueError(
        +                "Set name to the deployed Cohere model when using base_url"
        +            )
        +        if self.output_dimension is None or not self.api_key:
        +            raise ValueError("Cohere base_url requires output_dimension and api_key")
        +        if (
        +            self.source_input_type != "search_document"
        +            or self.query_input_type != "search_query"
        +        ):
        +            raise ValueError(
        +                "Cohere base_url requires search_document for sources "
        +                "and search_query for queries"
        +            )
        +        return self
        +
        +    @staticmethod
        +    def sensitive_keys() -> List[str]:
        +        return ["api_key"]
        +
        +    def endpoints(self) -> List[str]:
        +        return [] if self.base_url is None else [self.base_url]
         
             def ndims(self):
        +        if self.output_dimension is not None:
        +            return self.output_dimension
                 # TODO: fix hardcoding
                 if self.name in [
                     "embed-english-v3.0",
        @@ -108,6 +206,8 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
                     raise ValueError(f"Model {self.name} not supported")
         
             def compute_query_embeddings(self, query: str, *args, **kwargs) -> List[np.array]:
        +        if self.base_url is not None:
        +            return self._embed_v2(query, "search_query")
                 return self.compute_source_embeddings(query, input_type=self.query_input_type)
         
             def compute_source_embeddings(self, texts: TEXT, *args, **kwargs) -> List[np.array]:
        @@ -128,6 +228,8 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
                 texts: list[str] or np.ndarray (of str)
                     The texts to embed
                 """
        +        if self.base_url is not None:
        +            return self._embed_v2(texts, "search_document")
                 self._init_client()
                 rs = CohereEmbeddingFunction.client.embed(
                     texts=texts, model=self.name, **kwargs
        @@ -135,6 +237,81 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
         
                 return [emb for emb in rs.embeddings]
         
        +    def compute_source_embeddings_with_retry(self, texts: TEXT, *args, **kwargs):
        +        if self.base_url is None:
        +            return super().compute_source_embeddings_with_retry(texts, *args, **kwargs)
        +        return self._embed_v2(texts, "search_document", max_retries=self.max_retries)
        +
        +    def compute_query_embeddings_with_retry(self, query: str, *args, **kwargs):
        +        if self.base_url is None:
        +            return super().compute_query_embeddings_with_retry(query, *args, **kwargs)
        +        return self._embed_v2(query, "search_query", max_retries=self.max_retries)
        +
        +    def _embed_v2(
        +        self,
        +        texts: TEXT,
        +        input_type: Literal["search_document", "search_query"],
        +        *,
        +        max_retries: int = 0,
        +    ) -> List[List[float]]:
        +        texts = self.sanitize_input(texts)
        +        if any(not isinstance(text, str) for text in texts):
        +            raise ValueError("Cohere API v2 text retrieval requires string inputs")
        +        if len(texts) == 0:
        +            return []
        +
        +        # Retry each HTTP request without resending earlier successful batches.
        +        # The client refuses redirects, so repeating a redirected request cannot help.
        +        request = self._v2_client.embed
        +        if max_retries > 0:
        +            request = retry_with_exponential_backoff(
        +                request, max_retries=max_retries, do_not_retry=_is_redirect_error
        +            )
        +        embeddings = []
        +        for start in range(0, len(texts), _COHERE_V2_MAX_TEXTS):
        +            batch = list(texts[start : start + _COHERE_V2_MAX_TEXTS])
        +            response = request(
        +                texts=batch,
        +                model=self.name,
        +                input_type=input_type,
        +                output_dimension=self.ndims(),
        +                embedding_types=["float"],
        +                request_options={"max_retries": 0},
        +            )
        +            vectors = response.embeddings.float
        +            if vectors is None or len(vectors) != len(batch):
        +                raise ValueError(
        +                    "Cohere API v2 returned an unexpected number of vectors"
        +                )
        +            if any(len(vector) != self.ndims() for vector in vectors):
        +                raise ValueError(
        +                    f"Cohere API v2 returned a vector with an unexpected dimension "
        +                    f"(expected {self.ndims()})"
        +                )
        +            embeddings.extend(vectors)
        +        return embeddings
        +
        +    @cached_property
        +    def _v2_client(self):
        +        cohere = attempt_import_or_raise(
        +            "cohere", mitigation=f"cohere>={_COHERE_V2_MIN_VERSION}"
        +        )
        +        if Version(version("cohere")) < Version(_COHERE_V2_MIN_VERSION):
        +            raise ImportError(
        +                f"Cohere base_url requires cohere>={_COHERE_V2_MIN_VERSION}"
        +            )
        +        httpx = attempt_import_or_raise("httpx")
        +        # Older SDK versions override the HTTPX client's timeout on each request.
        +        timeout = 300
        +        # The registry trusts only this endpoint. The SDK follows redirects by
        +        # default, including redirects that can resend the document or query.
        +        return cohere.ClientV2(
        +            base_url=self.base_url,
        +            api_key=self.api_key,
        +            timeout=timeout,
        +            httpx_client=httpx.Client(follow_redirects=False, timeout=timeout),
        +        )
        +
             def _init_client(self):
                 cohere = attempt_import_or_raise("cohere")
                 if CohereEmbeddingFunction.client is None:
        diff --git a/python/python/lancedb/embeddings/openai.py b/python/python/lancedb/embeddings/openai.py
        index 8592598cc..a8e652789 100644
        --- a/python/python/lancedb/embeddings/openai.py
        +++ b/python/python/lancedb/embeddings/openai.py
        @@ -99,8 +99,6 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
                 texts: list[str] or np.ndarray (of str)
                     The texts to embed
                 """
        -        openai = attempt_import_or_raise("openai")
        -
                 valid_texts = []
                 valid_indices = []
                 for idx, text in enumerate(texts):
        @@ -108,6 +106,11 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
                         valid_texts.append(text)
                         valid_indices.append(idx)
         
        +        if not valid_texts:
        +            return [None] * len(texts)
        +
        +        openai = attempt_import_or_raise("openai")
        +
                 # TODO retry, rate limit, token limit
                 def embed_batch(texts_batch, indices_batch):
                     kwargs = {
        diff --git a/python/python/lancedb/embeddings/utils.py b/python/python/lancedb/embeddings/utils.py
        index ff8fc6a18..a3f334d28 100644
        --- a/python/python/lancedb/embeddings/utils.py
        +++ b/python/python/lancedb/embeddings/utils.py
        @@ -242,6 +242,8 @@ def retry_with_exponential_backoff(
             jitter: bool = True,
             max_retries: int = 7,
             max_delay: float = 60,
        +    *,
        +    do_not_retry: Callable[[Exception], bool] | None = None,
         ):
             """Retry a function with exponential backoff.
         
        @@ -265,6 +267,7 @@ def retry_with_exponential_backoff(
                 max_retries (int): Maximum number of retries (default is 7).
                 max_delay (float): Maximum delay between two attempts, in seconds
                     (default is 60).
        +        do_not_retry: Optional predicate for additional permanent failures.
         
             Returns:
                 function: The decorated function.
        @@ -286,7 +289,9 @@ def retry_with_exponential_backoff(
                     except Exception as e:  # noqa: PERF203
                         # Don't retry permanent failures (e.g., OpenAI 401 or 404). They
                         # won't be fixed by retrying and would only delay the real error.
        -                if _is_non_retryable_error(e):
        +                if _is_non_retryable_error(e) or (
        +                    do_not_retry is not None and do_not_retry(e)
        +                ):
                             raise
         
                         num_retries += 1
        diff --git a/python/python/lancedb/expr.py b/python/python/lancedb/expr.py
        index f65fbd21a..b25e5d012 100644
        --- a/python/python/lancedb/expr.py
        +++ b/python/python/lancedb/expr.py
        @@ -29,6 +29,8 @@ from lancedb._lancedb import PyExpr, expr_col, expr_lit, expr_func
         
         __all__ = ["Expr", "col", "lit", "func"]
         
        +_NOT_LITERAL = object()
        +
         _STR_TO_PA_TYPE: dict = {
             "bool": pa.bool_(),
             "boolean": pa.bool_(),
        @@ -92,9 +94,16 @@ class Expr:
             # for dict keys / set membership.
             __hash__ = None  # type: ignore[assignment]
         
        -    def __init__(self, inner: PyExpr, *, column_path: str | None = None) -> None:
        +    def __init__(
        +        self,
        +        inner: PyExpr,
        +        *,
        +        column_path: str | None = None,
        +        literal_value: object = _NOT_LITERAL,
        +    ) -> None:
                 self._inner = inner
                 self._column_path = column_path
        +        self._literal_value = literal_value
         
             def __bool__(self) -> bool:
                 # An Expr describes a predicate that the query engine evaluates per row,
        @@ -301,14 +310,16 @@ def col(name: str) -> Expr:
             return Expr(expr_col(name), column_path=name)
         
         
        -def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> Expr:
        +def lit(
        +    value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
        +) -> Expr:
             """Create a literal (constant) value expression.
         
             Parameters
             ----------
             value:
                 A Python ``bool``, ``int``, ``float``, ``str``, ``bytes``, ``date``,
        -        ``datetime``, or ``Decimal``.
        +        ``datetime``, ``Decimal``, or ``None`` for SQL NULL.
         
             Examples
             --------
        @@ -316,10 +327,12 @@ def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) ->
             >>> col("price") * lit(1.1)
             Expr((price * 1.1))
             """
        -    if not isinstance(value, (bool, int, float, str, bytes, date, datetime, Decimal)):
        +    if value is not None and not isinstance(
        +        value, (bool, int, float, str, bytes, date, datetime, Decimal)
        +    ):
                 raise TypeError(f"Unsupported literal type: {type(value).__name__}")
         
        -    return Expr(expr_lit(value))
        +    return Expr(expr_lit(value), literal_value=value)
         
         
         def func(name: str, *args: ExprLike) -> Expr:
        diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py
        index ba2bbeba3..b2e4cb0eb 100644
        --- a/python/python/lancedb/functions.py
        +++ b/python/python/lancedb/functions.py
        @@ -16,25 +16,31 @@ import builtins
         import base64
         import functools
         import hashlib
        +import importlib.metadata
         import importlib.util
         import inspect
         import symtable
         import json
         import linecache
         import math
        +import os
         import re
         import sys
         import textwrap
         import types
         import warnings
         from collections.abc import Mapping, Sequence
        -from datetime import date, datetime
        +from datetime import date, datetime, timedelta
        +from decimal import Decimal
        +from pathlib import Path
         from typing import (
             Annotated,
             Any,
             Callable,
             Literal,
        +    NamedTuple,
             Optional,
        +    TYPE_CHECKING,
             Union,
             get_args,
             get_origin,
        @@ -43,6 +49,7 @@ from typing import (
         )
         
         import pyarrow as pa
        +from packaging.requirements import Requirement
         from pydantic import (
             AfterValidator,
             BaseModel,
        @@ -56,16 +63,16 @@ from pydantic import (
         from .schema import blob as _blob_field
         from .schema import is_blob_v2_field as _is_blob_v2_field
         from ._blob_reader import BlobReader
        +from ._blob_writer import BlobWriter, _BLOB_WRITER_METADATA_KEY, _mark_blob_writer
        +from ._lancedb import _validate_conda_requirement
         from .secrets import EnvVarSecret
        +from .resources import _validate_gpu_class_name
         
         _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1)
         _UInt32 = conint(strict=True, ge=0, le=2**32 - 1)
        +_PositiveUInt32 = conint(strict=True, ge=1, le=2**32 - 1)
         _UInt64 = conint(strict=True, ge=0, le=2**64 - 1)
        -_GPU_CLASS_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
        -_GPU_CLASS_ERROR = (
        -    "gpu_class must be a lowercase name of at most 63 letters, digits, or "
        -    "hyphens, and cannot start or end with a hyphen"
        -)
        +_PositiveUInt64 = conint(strict=True, ge=1, le=2**64 - 1)
         
         
         def _validate_gpu_wire_marker(value: Any) -> bool:
        @@ -74,16 +81,24 @@ def _validate_gpu_wire_marker(value: Any) -> bool:
             return True
         
         
        -def _normalize_gpu_marker(value: bool) -> Optional[bool]:
        -    if not isinstance(value, bool):
        +def _normalize_gpu_request(
        +    gpu: Optional[bool], gpu_class: Optional[str], gpu_count: Optional[int]
        +) -> tuple[Optional[bool], Optional[str], Optional[int]]:
        +    if gpu is not None and not isinstance(gpu, bool):
                 raise ValueError("gpu must be a boolean")
        -    return True if value else None
        -
        -
        -def _validate_gpu_class_name(value: Any) -> str:
        -    if not isinstance(value, str) or not _GPU_CLASS_NAME.fullmatch(value):
        -        raise ValueError(_GPU_CLASS_ERROR)
        -    return value
        +    if gpu is not True:
        +        if gpu_class is not None or gpu_count is not None:
        +            raise ValueError("gpu_class and gpu_count require gpu=True")
        +        return None, None, None
        +    if gpu_class is not None:
        +        gpu_class = _validate_gpu_class_name(gpu_class)
        +    if gpu_count is None:
        +        gpu_count = 1
        +    if isinstance(gpu_count, bool) or not isinstance(gpu_count, int):
        +        raise ValueError("gpu_count must be a positive integer")
        +    if not 1 <= gpu_count <= 2**32 - 1:
        +        raise ValueError("gpu_count must be between 1 and 4294967295")
        +    return True, gpu_class, gpu_count
         
         
         def _validate_batch_size(value: Any) -> Optional[int]:
        @@ -96,6 +111,22 @@ def _validate_batch_size(value: Any) -> Optional[int]:
             return value
         
         
        +def _validate_refresh_lock(value: Any) -> bool:
        +    if not isinstance(value, bool):
        +        raise ValueError("refresh_lock must be a boolean")
        +    return value
        +
        +
        +def _validate_max_concurrency(value: Any) -> Optional[int]:
        +    if value is None:
        +        return None
        +    if isinstance(value, bool) or not isinstance(value, int):
        +        raise ValueError("max_concurrency must be an integer")
        +    if not 1 <= value <= 2**32 - 1:
        +        raise ValueError("max_concurrency must be between 1 and 4294967295")
        +    return value
        +
        +
         def _validate_row_timeout(value: Any) -> Optional[float]:
             if value is None:
                 return None
        @@ -143,11 +174,15 @@ def _validate_literal(value):
                         "Function integer literal is outside the canonical JSON range"
                     )
             elif isinstance(value, Mapping):
        +        if not all(isinstance(key, str) for key in value):
        +            raise TypeError("Function literal object keys must be strings")
                 for child in value.values():
                     _validate_literal(child)
             elif isinstance(value, (list, tuple)):
                 for child in value:
                     _validate_literal(child)
        +    elif value is not None and not isinstance(value, (bool, str)):
        +        raise TypeError(f"unsupported Function literal type: {type(value).__name__}")
             return value
         
         
        @@ -178,7 +213,7 @@ class _RemoteValue(BaseModel):
                 known = {}
                 for name, field in self.__class__.model_fields.items():
                     value = getattr(self, name)
        -            if value is None:
        +            if value is None and not field.is_required():
                         continue
                     if not field.is_required():
                         default_factory = field.default_factory
        @@ -212,6 +247,45 @@ class _OpenRemoteValue(_RemoteValue):
                 return set((self.__pydantic_extra__ or {}).keys())
         
         
        +class FunctionRetryPolicy(_RemoteValue):
        +    """Bound retries of selected errors inside one Enterprise Function call.
        +
        +    ``max_attempts`` includes the first call. Matchers are alternatives;
        +    ``transient=True`` selects connection/timeouts, HTTP 429/503 and the
        +    provider codes ``SlowDown`` and ``ServiceUnavailable``. Exception names
        +    may be qualified, and subclasses and wrapped causes also match.
        +
        +    Backoff doubles with full jitter, bounded by ``max_backoff_seconds``.
        +    Retry-After above that bound ends retries. A failed batch is retried as
        +    one call: under ``skip``, exhaustion nulls every row in that call.
        +    Completed calls are never repeated. Only opt in when repeating partial
        +    work is safe; this does not make external side effects exactly once.
        +
        +    >>> policy = FunctionRetryPolicy(transient=True, max_attempts=3)
        +    >>> policy.max_attempts
        +    3
        +    >>> disabled = FunctionRetryPolicy(max_attempts=1)
        +    """
        +
        +    model_config = ConfigDict(extra="forbid", frozen=True)
        +
        +    max_attempts: Annotated[int, Field(strict=True)] = 3
        +    initial_backoff_seconds: Annotated[float, Field(strict=True)] = 0.2
        +    max_backoff_seconds: Annotated[float, Field(strict=True)] = 30.0
        +    exception_types: tuple[str, ...] = ()
        +    message_pattern: Optional[str] = None
        +    error_codes: tuple[str, ...] = ()
        +    transient: Annotated[bool, Field(strict=True)] = False
        +    honor_retry_after: Annotated[bool, Field(strict=True)] = True
        +
        +    @model_validator(mode="after")
        +    def _validate_policy(self):
        +        from ._lancedb import validate_function_retry_policy
        +
        +        validate_function_retry_policy(self.model_dump_json())
        +        return self
        +
        +
         class FunctionArtifact(_RemoteValue):
             """Content-addressed Python artifact identity."""
         
        @@ -257,13 +331,27 @@ class FunctionResultField(_OpenRemoteValue):
             nullable: bool
         
         
        +class _BlobWriterFieldStep(_RemoteValue):
        +    field: str
        +
        +
        +_BlobWriterPath = tuple[Union[_BlobWriterFieldStep, Literal["item"]], ...]
        +
        +
         class FunctionOutput(_OpenRemoteValue):
        -    """Scalar or ordered named-struct output; unknown kinds remain decodable."""
        +    """Scalar or ordered named-struct output; unknown kinds remain decodable.
        +
        +    A scalar output may be nullable. A named-struct output has no top-level
        +    nullability; its fields carry their own flags. Writer-capable outputs
        +    carry the paths of the declared Blob v2 leaves and use the corresponding
        +    ``scalar_blob_writer`` or ``named_struct_blob_writer`` kind.
        +    """
         
             kind: str
             arrow_type: Optional[str] = None
             nullable: Optional[bool] = None
             fields: tuple[FunctionResultField, ...] = ()
        +    blob_writer_paths: tuple[_BlobWriterPath, ...] = ()
         
         
         class SecretReference(_RemoteValue):
        @@ -317,6 +405,54 @@ class PythonEnvironmentSpec(_RemoteValue):
             image: Optional[str] = None
             system_packages: tuple[str, ...] = ()
         
        +    @model_validator(mode="before")
        +    @classmethod
        +    def _validate_registration_build(cls, value):
        +        if isinstance(value, Mapping):
        +            build = value.get("build")
        +            if build is not None and (not isinstance(build, Mapping) or build):
        +                raise TypeError(
        +                    "runtime.environment.build is unsupported "
        +                    "in typed Function registration"
        +                )
        +        return value
        +
        +
        +class PythonEnvironmentBuild(_RemoteValue):
        +    """Explicit primary package index URL reported on a Function version."""
        +
        +    index_url: str
        +
        +
        +class RequestedPythonEnvironment(PythonEnvironmentSpec):
        +    """Python environment metadata reported on a Function version.
        +
        +    ``build`` contains only the explicitly requested primary package index URL.
        +    An omitted ``build`` can still accompany extra indexes, other sources, or
        +    service defaults. See
        +    [ResolvedEnvironmentProvenance][lancedb.functions.ResolvedEnvironmentProvenance]
        +    for the sources reported by the build.
        +    """
        +
        +    build: Optional[PythonEnvironmentBuild] = None
        +
        +    @model_validator(mode="before")
        +    @classmethod
        +    def _validate_registration_build(cls, value):
        +        # Inspection accepts an authored model or a wire document with a build field.
        +        if isinstance(value, PythonEnvironmentSpec) and not isinstance(value, cls):
        +            return value._known_dict()
        +        return value
        +
        +    @field_validator("build", mode="before")
        +    @classmethod
        +    def _read_primary_index(cls, build):
        +        if isinstance(build, PythonEnvironmentBuild):
        +            return build
        +        if isinstance(build, Mapping) and isinstance(build.get("index_url"), str):
        +            return {"index_url": build["index_url"]}
        +        return None
        +
         
         _HUGGING_FACE_MODEL_REPO = re.compile(
             r"^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$"
        @@ -333,7 +469,7 @@ class HuggingFaceModel(_RemoteValue):
             snapshot before initialization, so the model can load without a revision
             argument or a Hugging Face Hub request::
         
        -        @udf(
        +        @function(
                     pip=["sentence-transformers==3.3.1"],
                     models=[HuggingFaceModel(
                         repo="sentence-transformers/all-MiniLM-L6-v2",
        @@ -381,8 +517,10 @@ class PythonRuntimeSpec(_RemoteValue):
         
             V1 supports ``kind="python"``. Newer runtime kinds remain readable, while
             their unknown payload fields are intentionally not retained by the client.
        -    ``kind="python_v2"`` requires ``gpu=True`` and may name an operator-defined
        -    ``gpu_class``.
        +    ``kind="python_v2"`` requires ``gpu=True``. Its ``gpu_class`` records the
        +    requested operator-defined class or ``"any"`` for any eligible class;
        +    omitting it also accepts any eligible class. It does not identify the
        +    hardware selected for execution.
             """
         
             kind: str
        @@ -391,6 +529,7 @@ class PythonRuntimeSpec(_RemoteValue):
             env: Optional[Mapping[str, str]] = None
             gpu: Optional[bool] = None
             gpu_class: Optional[str] = None
        +    gpus_per_worker: Optional[_PositiveUInt32] = None
         
             @model_validator(mode="before")
             @classmethod
        @@ -428,6 +567,8 @@ class PythonRuntimeSpec(_RemoteValue):
                         raise ValueError(
                             "python runtime with gpu_class requires kind='python_v2'"
                         )
        +            if self.gpus_per_worker is not None:
        +                raise ValueError("gpus_per_worker requires kind='python_v2'")
                 elif self.kind == "python_v2":
                     if self.python_version is None:
                         raise ValueError("python_v2 runtime requires python_version")
        @@ -441,17 +582,185 @@ class PythonRuntimeSpec(_RemoteValue):
                     object.__setattr__(self, "env", None)
                     object.__setattr__(self, "gpu", None)
                     object.__setattr__(self, "gpu_class", None)
        +            object.__setattr__(self, "gpus_per_worker", None)
                 return self
         
        +    @property
        +    def digest(self) -> str:
        +        """SHA-256 identity of the declared runtime, before building an image.
        +
        +        Covers Python version, environment sources, environment variables, and
        +        GPU settings. Package and system-package order is ignored; conda channel
        +        order is preserved. Compare an authored runtime's digest with
        +        ``runtime_digest`` on [FunctionVersion][lancedb.functions.FunctionVersion].
        +        A version's projected runtime fields can omit inputs from that digest.
        +        This identity covers declared inputs; the installed contents of unpinned
        +        dependencies and the deployment's default base image can vary.
        +        """
        +        if self.kind not in {"python", "python_v2"}:
        +            raise ValueError(f"cannot digest unknown runtime kind {self.kind!r}")
        +        value = self._known_dict()
        +        if not value.get("env"):
        +            value.pop("env", None)
        +        environment = value["environment"]
        +        for field in ("packages", "system_packages"):
        +            if field in environment:
        +                environment[field] = sorted(environment[field])
        +        encoded = json.dumps(
        +            value,
        +            ensure_ascii=False,
        +            allow_nan=False,
        +            sort_keys=True,
        +            separators=(",", ":"),
        +        ).encode("utf-8")
        +        return f"sha256:{hashlib.sha256(encoded).hexdigest()}"
        +
        +
        +class RequestedPythonRuntime(PythonRuntimeSpec):
        +    """Requested runtime metadata available during Function version inspection.
        +
        +    The build view contains only an explicit primary package index URL. Other
        +    sources can be present even when the build view is absent. Compare the
        +    server's ``FunctionVersion.runtime_digest`` with the digest of an authored
        +    runtime. The inspection view can omit inputs needed to reproduce that digest.
        +    """
        +
        +    environment: Optional[RequestedPythonEnvironment] = None
        +
        +    @model_validator(mode="before")
        +    @classmethod
        +    def _discard_unknown_runtime_payload(cls, value):
        +        if isinstance(value, PythonRuntimeSpec) and not isinstance(value, cls):
        +            value = value._known_dict()
        +        return super()._discard_unknown_runtime_payload(value)
        +
         
         class FunctionImage(_RemoteValue):
        -    """A complete OCI Function image identified by its exact manifest digest."""
        +    """A complete OCI Function image identified by its exact manifest digest.
        +
        +    ``describe()`` and the concise representation inspect the descriptor without
        +    walking Pydantic model internals. Missing metadata is ``None`` (unknown).
        +    The current service does not report image platforms, base image or byte size;
        +    these cannot be inferred from the client's platform or the manifest digest.
        +    The full descriptor remains available through ``descriptor``.
        +    """
         
             manifest_digest: str
             descriptor: Mapping[str, Any]
             source: bool
             models: tuple[HuggingFaceModel, ...] = ()
         
        +    def describe(self) -> dict[str, Any]:
        +        """Return concise image details without fetching registry content.
        +
        +        ``requires_gpu`` reflects a ``lance.cuda`` requirement in a v1
        +        descriptor, rather than promising compatibility with every GPU.
        +        ``platforms``, ``base_image`` and ``size_bytes`` are unavailable from
        +        the current wire contract and return ``None``.
        +
        +        Examples
        +        --------
        +        >>> print(fn.image.describe())  # doctest: +SKIP
        +        """
        +        python = self.descriptor.get("python")
        +        requires = self.descriptor.get("requires")
        +        capabilities = (
        +            requires.get("capabilities") if isinstance(requires, Mapping) else None
        +        )
        +        known_capabilities = (
        +            self.descriptor.get("format_version") == 1
        +            and isinstance(capabilities, (list, tuple))
        +            and all(isinstance(item, Mapping) for item in capabilities)
        +        )
        +        cuda = (
        +            next(
        +                (item for item in capabilities if item.get("type") == "lance.cuda"),
        +                None,
        +            )
        +            if known_capabilities
        +            else None
        +        )
        +        python_version = python.get("version") if isinstance(python, Mapping) else None
        +        cuda_toolkit = cuda.get("cuda_toolkit") if cuda is not None else None
        +        return {
        +            "manifest_digest": self.manifest_digest,
        +            "python_version": python_version
        +            if isinstance(python_version, str)
        +            else None,
        +            "requires_gpu": cuda is not None if known_capabilities else None,
        +            "cuda_toolkit": cuda_toolkit if isinstance(cuda_toolkit, str) else None,
        +            "platforms": None,
        +            "base_image": None,
        +            "size_bytes": None,
        +        }
        +
        +    def __repr_args__(self):
        +        for name, value in self.describe().items():
        +            if isinstance(value, str) and len(value) > 80:
        +                value = value[:77] + "..."
        +            yield name, value
        +
        +
        +class ResolvedPackage(_RemoteValue):
        +    """One installed Python distribution measured from a baked environment.
        +
        +    ``version`` is the complete version reported by package metadata,
        +    including local labels such as ``+cu130``. ``source`` is present only when
        +    the submitted lock retained a per-package source; absent means unknown, not
        +    an inferred index.
        +    """
        +
        +    name: str
        +    version: str
        +    source: Optional[str] = None
        +
        +
        +class ResolvedEnvironmentProvenance(_RemoteValue):
        +    """Sanitized source and accelerator provenance for a resolved environment.
        +
        +    ``configured_index_urls`` and ``configured_find_links`` record build
        +    inputs. ``resolved_indexes`` records indexes visible in the submitted lock,
        +    so a configured source is not by itself evidence that a package came from
        +    it. Empty lists and absent fields remain absent; the client does not
        +    synthesize them.
        +    """
        +
        +    configured_index_urls: tuple[str, ...] = ()
        +    configured_find_links: tuple[str, ...] = ()
        +    resolved_indexes: tuple[str, ...] = ()
        +    cuda_toolkit: Optional[str] = None
        +    torch_version: Optional[str] = None
        +
        +
        +class ResolvedEnvironment(_RemoteValue):
        +    """Actual installed distributions and registration warnings for one platform.
        +
        +    A missing value means its measurement is unknown, not an empty
        +    installed-package list. Versions are retained verbatim, including local
        +    labels; package ``source`` is retained only when the producer recorded it.
        +    """
        +
        +    packages: tuple[ResolvedPackage, ...]
        +    provenance: Optional[ResolvedEnvironmentProvenance] = None
        +    warnings: tuple[str, ...] = ()
        +
        +
        +class FunctionEnvironment(NamedTuple):
        +    """Requested and measured environment view for a Function version.
        +
        +    This is a view over
        +    [FunctionVersion.runtime][lancedb.functions.FunctionVersion.runtime]
        +    and
        +    [FunctionVersion.resolved_environment][lancedb.functions.FunctionVersion.resolved_environment].
        +    It adds no wire field and performs no second parse. ``requested`` is the
        +    server's view of the runtime requested at registration. ``resolved`` is
        +    measured data and is ``None`` when unknown. For per-platform multiarchitecture
        +    measurements, use ``FunctionVersion.environment_report``.
        +    """
        +
        +    requested: Optional[RequestedPythonRuntime]
        +    resolved: Optional[ResolvedEnvironment]
        +
         
         def _validate_object_version(value: str) -> str:
             if int(value) > 2**64 - 1:
        @@ -469,6 +778,12 @@ _ObjectVersion = Annotated[
         class FunctionVersion(_RemoteValue):
             """A pinned object revision, independent of its executable image digest.
         
        +    Unknown top-level fields from newer servers are accepted for forward
        +    decoding, but they are not exposed on this value and are omitted from
        +    ``to_canonical_json()``. Known fields retain their complete values, while
        +    unknown fields inside the open ``image.descriptor`` mapping remain
        +    available.
        +
             ``name`` and ``namespace_path`` are the Function's parts, as a
             [SecretReference][lancedb.functions.SecretReference] carries a Secret's;
             they are what [get_function][lancedb.db.DBConnection.get_function] takes.
        @@ -476,12 +791,38 @@ class FunctionVersion(_RemoteValue):
         
             ``source_digest`` identifies the registered source artifact, independently
             of the built ``image``. Compare it with
        -    ``udf_def.registration_request.artifact.digest`` to check whether a local
        -    [UdfDefinition][lancedb.functions.UdfDefinition] has the same source.
        +    ``definition.registration_request.artifact.digest`` to check whether a local
        +    [FunctionDefinition][lancedb.functions.FunctionDefinition] has the same source.
        +    It does not cover dependencies, environment variables, Python version, or
        +    GPU settings. Equal source digests alone do not mean a version can be reused.
             It is ``None`` when the server does not provide a source digest.
         
        -    ``gpu_class`` is the operator-defined GPU pool fixed into this Function
        -    version, or ``None`` when registration used the deployment default.
        +    ``runtime_digest`` identifies the declared environment inputs. Compare it
        +    with ``definition.registration_request.runtime.digest`` to check whether
        +    the local runtime matches. It is ``None`` for images built before runtime
        +    identity was exposed. A missing digest cannot establish a match. Reusing a
        +    version also requires matching the source and all other registration inputs,
        +    including signature, Secret bindings, models, and execution controls.
        +
        +    ``gpu_class`` records the default GPU pool for this Function version.
        +    Column/MV creation and refresh can override it independently of the
        +    per-worker ``gpu_count`` in the requested runtime.
        +
        +    ``batch_size``, ``max_concurrency``, ``row_timeout_seconds``, and
        +    ``result_stability`` retain the execution controls reported by the
        +    catalog. They are ``None`` for versions registered before the
        +    corresponding declaration.
        +
        +    ``runtime`` contains the requested runtime fields exposed by the SDK.
        +    The canonical runtime identity comes from ``runtime_digest``.
        +    ``resolved_environment`` is measured data for a single-platform image:
        +    actual package names and complete versions, optional per-package source,
        +    provenance, and registration warnings. ``resolved_environments`` is the
        +    corresponding map for a multiarchitecture image, keyed by OCI
        +    ``os/architecture``. It is never flattened into an aggregate package list.
        +    ``None`` or an empty map means the measurement is unknown. ``environment``
        +    is a convenience view with ``requested`` and ``resolved`` members over the
        +    same fields.
             """
         
             name: str
        @@ -491,18 +832,71 @@ class FunctionVersion(_RemoteValue):
             version: _ObjectVersion
             image: FunctionImage
             source_digest: Optional[str] = None
        +    runtime_digest: Optional[str] = None
             signature: FunctionSignature
             secret_bindings: tuple[SecretBinding, ...] = ()
             created_at_millis: int
             metadata: Mapping[str, str]
             disabled: bool
             gpu_class: Optional[str] = None
        +    batch_size: Optional[int] = None
        +    max_concurrency: Optional[int] = None
        +    total_cpu_millis: Optional[_PositiveUInt64] = None
        +    total_memory_bytes: Optional[_PositiveUInt64] = None
        +    total_gpu_count: Optional[_UInt32] = None
        +    row_timeout_seconds: Optional[float] = None
        +    result_stability: Optional[str] = None
        +    runtime: Optional[RequestedPythonRuntime] = None
        +    resolved_environment: Optional[ResolvedEnvironment] = None
        +    resolved_environments: Mapping[str, ResolvedEnvironment] = Field(
        +        default_factory=dict
        +    )
        +
        +    @field_validator("batch_size", mode="before")
        +    @classmethod
        +    def _validate_batch_size(cls, value):
        +        return _validate_batch_size(value)
        +
        +    @field_validator("max_concurrency", mode="before")
        +    @classmethod
        +    def _validate_max_concurrency(cls, value):
        +        return _validate_max_concurrency(value)
        +
        +    @field_validator("row_timeout_seconds", mode="before")
        +    @classmethod
        +    def _validate_row_timeout(cls, value):
        +        return _validate_row_timeout(value)
        +
        +    @property
        +    def environment(self) -> FunctionEnvironment:
        +        """Requested and measured environment without adding a second parser."""
        +        return FunctionEnvironment(
        +            requested=self.runtime,
        +            resolved=self.resolved_environment,
        +        )
        +
        +    @property
        +    def environment_report(self) -> Mapping[str, ResolvedEnvironment]:
        +        """Per-platform measured reports, keyed by OCI ``os/architecture``.
        +
        +        This is the same map as ``resolved_environments`` and is never
        +        flattened. Single-platform images use ``resolved_environment`` instead;
        +        an absent platform means its measurement is unknown.
        +        """
        +        return self.resolved_environments
         
             def __call__(self, **arguments: Any) -> FunctionApplication:
        -        """Bind this exact version to named table columns.
        +        """Bind this exact version to named table columns and constant inputs.
         
                 Every input must be a direct [lancedb.col][lancedb.expr.col]
        -        reference. A Function that declares initialization fields takes their
        +        reference or [lancedb.lit][lancedb.expr.lit] constant. Constants support
        +        integers, strings, booleans, and null; floating-point, binary and
        +        temporal literals are not in the canonical Function input contract.
        +        The Enterprise service must support literal bindings and validates
        +        constants against this exact version's input signature. To change a
        +        constant, redeclare the column using the same Function version.
        +
        +        A Function that declares initialization fields takes their
                 values as further keyword arguments; they are constants of this
                 binding, fixed for every row, and every instance the binding runs is
                 created with them. A non-nullable field without a default must be
        @@ -531,7 +925,7 @@ class FunctionVersion(_RemoteValue):
                 ...     "embedding": embed(text=col("body"), model="small", dimensions=512)
                 ... })
                 """
        -        from lancedb.expr import Expr
        +        from lancedb.expr import Expr, _NOT_LITERAL
         
                 parameters = tuple(parameter.name for parameter in self.signature.inputs)
                 fields = {field.name: field for field in self.signature.initialization}
        @@ -555,17 +949,27 @@ class FunctionVersion(_RemoteValue):
                 bindings = []
                 for parameter in parameters:
                     value = arguments[parameter]
        -            if not isinstance(value, Expr) or value._column_path is None:
        +            if isinstance(value, Expr) and value._literal_value is not _NOT_LITERAL:
        +                bindings.append(
        +                    ApplicationInput(
        +                        parameter=parameter,
        +                        kind="literal",
        +                        value=value._literal_value,
        +                    )
        +                )
        +            elif isinstance(value, Expr) and value._column_path is not None:
        +                bindings.append(
        +                    ApplicationInput(
        +                        parameter=parameter,
        +                        kind="column",
        +                        value={"path": value._column_path},
        +                    )
        +                )
        +            else:
                         raise TypeError(
        -                    f"Function input {parameter!r} must be a direct col(...) reference"
        +                    f"Function input {parameter!r} must be a direct col(...) reference "
        +                    "or lit(...) constant"
                         )
        -            bindings.append(
        -                ApplicationInput(
        -                    parameter=parameter,
        -                    kind="column",
        -                    value={"path": value._column_path},
        -                )
        -            )
                 initialization = {}
                 for name in fields:
                     if name in arguments:
        @@ -616,11 +1020,15 @@ def _initialization_value(name: str, value: Any) -> Any:
         
         
         class FunctionRegistrationRequest(_RemoteValue):
        -    """Stable remote registration envelope produced by :func:`udf`.
        +    """Stable remote registration envelope produced by :func:`function`.
         
             Credential values deliberately have no field here. The only secret-shaped
             thing a client sends is ``secret_bindings``: the name of a Secret the
             database already holds, which the remote service resolves at execution.
        +    ``refresh_lock`` is a per-registration action that leaves the Function's
        +    source and runtime identities unchanged. Its false default is omitted from
        +    canonical JSON. The typed registration API accepts authored runtimes and
        +    rejects nonempty ``runtime.environment.build`` settings.
             """
         
             name: str
        @@ -628,20 +1036,61 @@ class FunctionRegistrationRequest(_RemoteValue):
             signature: FunctionSignature
             runtime: PythonRuntimeSpec
             batch_size: Optional[int] = None
        +    max_concurrency: Optional[int] = None
        +    total_cpu_millis: Optional[_PositiveUInt64] = None
        +    total_memory_bytes: Optional[_PositiveUInt64] = None
        +    total_gpu_count: Optional[_UInt32] = None
             row_timeout_seconds: Optional[float] = None
        +    retry_policy: Optional[FunctionRetryPolicy] = None
             secret_bindings: tuple[SecretBinding, ...] = ()
             models: tuple[HuggingFaceModel, ...] = ()
        +    refresh_lock: bool = False
         
             @field_validator("batch_size", mode="before")
             @classmethod
             def _validate_batch_size(cls, value):
                 return _validate_batch_size(value)
         
        +    @field_validator("max_concurrency", mode="before")
        +    @classmethod
        +    def _validate_max_concurrency(cls, value):
        +        return _validate_max_concurrency(value)
        +
             @field_validator("row_timeout_seconds", mode="before")
             @classmethod
             def _validate_row_timeout(cls, value):
                 return _validate_row_timeout(value)
         
        +    @field_validator("refresh_lock", mode="before")
        +    @classmethod
        +    def _validate_refresh_lock(cls, value):
        +        return _validate_refresh_lock(value)
        +
        +    @field_validator("runtime", mode="before")
        +    @classmethod
        +    def _require_authored_runtime(cls, runtime):
        +        if isinstance(runtime, RequestedPythonRuntime) or (
        +            isinstance(runtime, PythonRuntimeSpec)
        +            and isinstance(runtime.environment, RequestedPythonEnvironment)
        +        ):
        +            raise TypeError(
        +                "Function version runtime metadata is for inspection only; "
        +                "register an authored @function definition"
        +            )
        +        return runtime
        +
        +    def to_canonical_json(self) -> str:
        +        """Encode the authored request for Function registration."""
        +        self._require_authored_runtime(self.runtime)
        +        return super().to_canonical_json()
        +
        +    def with_refresh_lock(self, refresh_lock: bool) -> FunctionRegistrationRequest:
        +        """Return this request with the registration-time refresh action set."""
        +        refresh_lock = _validate_refresh_lock(refresh_lock)
        +        if self.refresh_lock == refresh_lock:
        +            return self
        +        return self._copy(update={"refresh_lock": refresh_lock})
        +
         
         class FunctionVersionRef(_OpenRemoteValue):
             name: str
        @@ -718,7 +1167,7 @@ class FunctionApplication(_OpenRemoteValue):
         
             def rename(self, *, columns: Mapping[str, str]) -> FunctionApplication:
                 """Return a copy with result-field to table-column aliases."""
        -        if self.output.kind != "named_struct":
        +        if self.output.kind not in ("named_struct", "named_struct_blob_writer"):
                     raise ValueError("rename(columns=...) requires a named-struct application")
                 result_fields = {field.name for field in self.output.fields}
                 unknown = set(columns) - result_fields
        @@ -742,6 +1191,18 @@ class InputBinding(_RemoteValue):
             nullable: bool
         
         
        +class LiteralInputBinding(_RemoteValue):
        +    """Constant supplied to a Function parameter for every input row."""
        +
        +    parameter: str
        +    value: Any
        +
        +    @field_validator("value")
        +    @classmethod
        +    def _validate_value(cls, value):
        +        return _validate_literal(value)
        +
        +
         class OutputMapping(_RemoteValue):
             """One stable result-field mapping."""
         
        @@ -766,6 +1227,7 @@ class FunctionBinding(_RemoteValue):
             binding_id: str
             function: FunctionVersionRef
             inputs: tuple[InputBinding, ...]
        +    literal_inputs: tuple[LiteralInputBinding, ...] = ()
             outputs: tuple[OutputMapping, ...]
             assignment: Optional[AssignmentMapping] = None
             input_schema: Optional[Mapping[str, Any]] = None
        @@ -773,6 +1235,13 @@ class FunctionBinding(_RemoteValue):
             initialization: Optional[str] = None
             """Standard base64 of the validated one-row Arrow IPC initialization stream."""
         
        +    @model_validator(mode="after")
        +    def _validate_input_parameters(self):
        +        parameters = [input.parameter for input in (*self.inputs, *self.literal_inputs)]
        +        if len(parameters) != len(set(parameters)):
        +            raise ValueError("Function binding input parameters must be unique")
        +        return self
        +
             def initialization_row(self) -> Optional[dict[str, Any]]:
                 """The initialization values this binding creates instances with."""
                 if self.initialization is None:
        @@ -781,22 +1250,269 @@ class FunctionBinding(_RemoteValue):
                 return reader.read_all().to_pylist()[0]
         
         
        +class FunctionErrorGroup(_RemoteValue):
        +    """A grouped cause among returned Function failures."""
        +
        +    column: str
        +    error_type: str
        +    error_message: str
        +    rows_failed: _UInt64
        +
        +
        +class FunctionValueProvenance(_RemoteValue):
        +    """The Function version and job that produced one stored value."""
        +
        +    column: str
        +    job_id: str
        +    function_name: str
        +    function_version: str
        +    row_id: Optional[_UInt64] = None
        +    row_address: Optional[_UInt64] = None
        +    source_version: _UInt64
        +    published_version: _UInt64
        +
        +
        +class FunctionProvenance(_RemoteValue):
        +    """A bounded per-row producing-version listing for a table snapshot."""
        +
        +    records: tuple[FunctionValueProvenance, ...]
        +    truncated: bool = False
        +
        +
        +class _FunctionErrors:
        +    """Current Function failures, with grouped causes and source-row lookup.
        +
        +    Check ``truncated`` and ``fragments`` before treating a listing as complete.
        +    ``history=True`` on ``table.function_errors`` returns retained past records.
        +    """
        +
        +    def __init__(self, raw: Any, table: Any, *, history: bool = False):
        +        self._raw = raw
        +        self._table = table
        +        self._history = history
        +        self.records = raw.records
        +        self.fragments = raw.fragments
        +        self.truncated = raw.truncated
        +        self.page_token = getattr(raw, "page_token", None)
        +
        +    def __repr__(self) -> str:
        +        return repr(self._raw)
        +
        +    def as_sync(self, table: Any) -> FunctionErrors:
        +        return FunctionErrors(self._raw, table, history=self._history)
        +
        +    def summary(self) -> list[FunctionErrorGroup]:
        +        """Group returned failures by column, exception class, and message.
        +
        +        Raises when records are incomplete, so sampled counts cannot be mistaken
        +        for totals. Narrow the request by column or job, or raise its limit.
        +        """
        +        if (getattr(self._raw, "workflow_version", None) or 0) < 1:
        +            raise NotImplementedError(
        +                "The server does not support the current Function failure workflow"
        +            )
        +        if (
        +            self.truncated
        +            or self.fragments
        +            or any(
        +                record.row_offset is None and record.input is None
        +                for record in self.records
        +            )
        +        ):
        +            raise ValueError(
        +                "Function errors are incomplete; narrow the request or raise limit"
        +            )
        +        groups: dict[tuple[str, str, str], int] = {}
        +        for record in self.records:
        +            if record.row_offset is None and record.input is None:
        +                continue
        +            message = record.error_message
        +            if record.input is not None:
        +                message = message.split("\nSource input: ", 1)[0].split(
        +                    "\nFunction input ", 1
        +                )[0]
        +            key = (record.column, record.error_type, message)
        +            groups[key] = groups.get(key, 0) + 1
        +        return [
        +            FunctionErrorGroup(
        +                column=column, error_type=kind, error_message=message, rows_failed=count
        +            )
        +            for (column, kind, message), count in sorted(groups.items())
        +        ]
        +
        +    def _identities(self) -> dict[tuple[str, int], list[Any]]:
        +        if (getattr(self._raw, "workflow_version", None) or 0) < 1:
        +            raise NotImplementedError(
        +                "The server does not support the current Function failure workflow"
        +            )
        +        if self._history:
        +            raise ValueError(
        +                "Source-row lookup requires current failures; "
        +                "read retained history through records"
        +            )
        +        if self.truncated or self.fragments:
        +            raise ValueError(
        +                "Function errors are incomplete; narrow the request or raise limit"
        +            )
        +        result = {}
        +        for record in self.records:
        +            if record.input is not None or record.row_offset is None:
        +                raise ValueError(
        +                    "This error names a Function invocation; "
        +                    "inspect its input source identities"
        +                )
        +            identity = (
        +                record.row_id if record.row_id is not None else record.row_address
        +            )
        +            if identity is None:
        +                raise ValueError("This error has no source row identity")
        +            key = ("_rowid" if record.row_id is not None else "_rowaddr", identity)
        +            result.setdefault(key, []).append(record)
        +        return result
        +
        +    def _predicate(self, identities: dict[tuple[str, int], list[Any]]) -> str:
        +        clauses = []
        +        for field in ("_rowid", "_rowaddr"):
        +            selected = [identity for (kind, identity) in identities if kind == field]
        +            if selected:
        +                clauses.append(field + " IN (" + ",".join(map(str, selected)) + ")")
        +        return " OR ".join(clauses) if clauses else "false"
        +
        +    def _join_rows(
        +        self, rows: pa.Table, identities: dict[tuple[str, int], list[Any]]
        +    ) -> pa.Table:
        +        matches = []
        +        indices = []
        +        found = set()
        +        for index, (row_id, address) in enumerate(
        +            zip(rows.column("_rowid").to_pylist(), rows.column("_rowaddr").to_pylist())
        +        ):
        +            for key in (("_rowid", row_id), ("_rowaddr", address)):
        +                for record in identities.get(key, []):
        +                    found.add(key)
        +                    indices.append(index)
        +                    matches.append(record)
        +        if found != identities.keys():
        +            raise ValueError(
        +                "Some failed inputs are no longer addressable in this snapshot; "
        +                "refresh the error listing or use a historical snapshot"
        +            )
        +        rows = rows.take(pa.array(indices, type=pa.int64()))
        +        fields = [
        +            "column",
        +            "error_type",
        +            "error_message",
        +            "attempts",
        +            "function_version",
        +            "job_id",
        +            "first_seen_at_millis",
        +            "last_seen_at_millis",
        +            "quarantined",
        +        ]
        +        arrays = [
        +            pa.array([getattr(record, field) for record in matches]) for field in fields
        +        ]
        +        if "__function_error" in rows.column_names:
        +            raise ValueError("Source columns already contain __function_error")
        +        return rows.append_column(
        +            "__function_error", pa.StructArray.from_arrays(arrays, names=fields)
        +        )
        +
        +
        +class FunctionErrors(_FunctionErrors):
        +    """Current failures with grouped causes and synchronous source-row lookup."""
        +
        +    def rows(self, columns: Optional[list[str]] = None) -> pa.Table:
        +        """Return current failing inputs with a ``__function_error`` struct.
        +
        +        Row IDs come from the error records. The server joins stable identities
        +        correctly after compaction; callers need no physical-address arithmetic.
        +        """
        +        identities = self._identities()
        +        predicate = self._predicate(identities)
        +        query = (
        +            self._table.search()
        +            .where(predicate)
        +            .with_row_id(True)
        +            .with_row_address()
        +            .limit(max(1, len(identities)))
        +        )
        +        selected = list(self._table.schema.names if columns is None else columns)
        +        selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected)
        +        query = query.select(selected)
        +        return self._join_rows(query.to_arrow(), identities)
        +
        +
        +class AsyncFunctionErrors(_FunctionErrors):
        +    """Current Function failures returned by an asynchronous table."""
        +
        +    async def rows(self, columns: Optional[list[str]] = None) -> pa.Table:
        +        """Return current failing inputs with their ``__function_error`` metadata."""
        +        identities = self._identities()
        +        predicate = self._predicate(identities)
        +        query = (
        +            self._table.query()
        +            .where(predicate)
        +            .with_row_id()
        +            .with_row_address()
        +            .limit(max(1, len(identities)))
        +        )
        +        selected = list(
        +            (await self._table.schema()).names if columns is None else columns
        +        )
        +        selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected)
        +        query = query.select(selected)
        +        return self._join_rows(await query.to_arrow(), identities)
        +
        +
         class RefreshColumnResult(_RemoteValue):
             """Terminal result of an expression-backed or Function-backed refresh Job.
         
             LanceDB Embedded jobs produce this value in process. LanceDB Enterprise
             decodes the same value from the durable server-job terminal payload.
        +
        +    Row counters describe logical rows planned for this refresh, not user-code
        +    calls or retry attempts. ``rows_assigned`` counts rows successfully written
        +    with an output value, ``rows_failed`` counts rows whose computation failed,
        +    and ``rows_remaining`` counts planned rows neither assigned nor terminally
        +    skipped. Rows already counted in ``rows_failed`` are covered and are not
        +    counted again in ``rows_remaining``.
        +
        +    For example, a refresh over 2,001 logical rows that assigns 1,891 values and
        +    fails 110 rows reports ``rows_assigned=1,891``, ``rows_failed=110``, and
        +    ``rows_remaining=0``. Its failure-rate denominator is those 2,001 logical
        +    rows, not the number of execution attempts.
             """
         
             rows_assigned: _UInt64
        +    """Number of logical rows successfully assigned an output value by this
        +    refresh. Each row counts once, regardless of retry attempts, and failed rows
        +    are not included."""
        +
             rows_failed: _UInt64
        +    """Number of logical rows whose computation failed. Rows deferred because
        +    an input was not ready are not failures."""
        +
             rows_remaining: _UInt64
        +    """Number of planned logical rows neither assigned nor terminally skipped.
        +    Rows already counted in ``rows_failed`` are covered and are not counted
        +    again."""
        +
             source_version: _UInt64
        +    """Exact table version the refresh read."""
        +
             published_version: Optional[_UInt64] = None
        +    error_groups: tuple[FunctionErrorGroup, ...] = ()
        +    error_groups_truncated: bool = False
        +    """Table version made visible by the refresh, when one was published."""
         
             @property
             def rows_filled(self) -> int:
        -        """Deprecated compatibility alias for :attr:`rows_assigned`."""
        +        """Deprecated compatibility alias for :attr:`rows_assigned`.
        +
        +        The value is the same successful logical-row count; it does not count
        +        execution attempts.
        +        """
                 return self.rows_assigned
         
             @property
        @@ -838,6 +1554,7 @@ _GRAMMAR_PRIMITIVES = (
             (pa.date32(), "date32"),
             (pa.date64(), "date64"),
         )
        +_FUNCTION_TIMEUNITS = ("s", "ms", "us", "ns")
         
         
         def _canonical_arrow_type(
        @@ -877,32 +1594,38 @@ def _grammar_list_item(data_type: pa.DataType) -> Optional[str]:
             return _grammar_arrow_type(child.type)
         
         
        -def _validate_exact_arrow_field(field: pa.Field) -> None:
        +def _validate_exact_arrow_field(
        +    field: pa.Field, *, allow_blob_writer: bool = False
        +) -> None:
             if not field.name:
                 raise TypeError(
                     "unsupported Arrow type for Function signature: field names "
                     "must not be empty"
                 )
        -    if _is_blob_v2_field(field):
        +    metadata = field.metadata or {}
        +    is_blob = _is_blob_v2_field(field)
        +    if allow_blob_writer and _BLOB_WRITER_METADATA_KEY in metadata:
        +        if not is_blob or metadata[_BLOB_WRITER_METADATA_KEY] != b"true":
        +            raise TypeError("BlobWriter output requires a Blob v2 field marked true")
        +        metadata = {
        +            key: value
        +            for key, value in metadata.items()
        +            if key != _BLOB_WRITER_METADATA_KEY
        +        }
        +    if is_blob:
                 if not _has_supported_blob_v2_layout(field):
                     raise TypeError(
                         "unsupported Arrow type for Function signature: lance.blob.v2 "
                         f"requires a supported Blob storage layout, got {field}"
                     )
        -        metadata = {
        -            (key.decode() if isinstance(key, bytes) else key): (
        -                value.decode() if isinstance(value, bytes) else value
        -            )
        -            for key, value in (field.metadata or {}).items()
        -        }
                 if metadata and metadata != {
        -            _ARROW_EXTENSION_NAME_KEY: _BLOB_V2_EXTENSION_NAME
        +            _ARROW_EXTENSION_NAME_KEY.encode(): _BLOB_V2_EXTENSION_NAME.encode()
                 }:
                     raise TypeError(
                         "unsupported Arrow type for Function signature: lance.blob.v2 "
                         "field metadata must contain only its canonical extension marker"
                     )
        -    elif field.metadata:
        +    elif metadata:
                 raise TypeError(
                     "unsupported Arrow type for Function signature: field metadata "
                     f"is not supported, got {field}"
        @@ -961,7 +1684,7 @@ def _has_supported_blob_v2_layout(field: pa.Field) -> bool:
         
         def _canonical_arrow_field(field: pa.Field, *, collection_blobs: bool = False) -> str:
             """``collection_blobs`` admits Blob v2 under a list, which only outputs support."""
        -    _validate_exact_arrow_field(field)
        +    _validate_exact_arrow_field(field, allow_blob_writer=collection_blobs)
             if _is_blob_v2_field(field):
                 return _FUNCTION_BLOB_V2_TYPE
             return _canonical_arrow_type(field.type, collection_blobs=collection_blobs)
        @@ -1021,10 +1744,11 @@ def _exact_arrow_field(
             inside_collection: bool = False,
             collection_blobs: bool = False,
         ) -> dict[str, Any]:
        -    _validate_exact_arrow_field(field)
        -    if _is_blob_v2_field(field):
        -        if inside_collection and not collection_blobs:
        -            raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
        +    is_blob = _is_blob_v2_field(field)
        +    if is_blob and inside_collection and not collection_blobs:
        +        raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
        +    _validate_exact_arrow_field(field, allow_blob_writer=collection_blobs)
        +    if is_blob:
                 return {
                     "name": field.name,
                     "nullable": field.nullable,
        @@ -1054,6 +1778,33 @@ def _exact_arrow_type(
             for candidate, name in _GRAMMAR_PRIMITIVES:
                 if data_type == candidate:
                     return {"type": name}
        +    if pa.types.is_decimal128(data_type) or pa.types.is_decimal256(data_type):
        +        return {
        +            "type": (
        +                "decimal128" if pa.types.is_decimal128(data_type) else "decimal256"
        +            ),
        +            "length": data_type.precision * 1000 + data_type.scale,
        +        }
        +    if pa.types.is_timestamp(data_type):
        +        unit = data_type.unit
        +        if unit not in _FUNCTION_TIMEUNITS:
        +            raise TypeError(f"unsupported Function timestamp unit: {unit!r}")
        +        timezone = data_type.tz
        +        if timezone == "-":
        +            raise TypeError(
        +                "unsupported Function timestamp timezone: '-' is reserved for "
        +                "no timezone"
        +            )
        +        if unit == "us" and timezone is None:
        +            return {"type": "timestamp"}
        +        return {"type": f"timestamp:{unit}:{timezone if timezone is not None else '-'}"}
        +    if pa.types.is_duration(data_type):
        +        unit = data_type.unit
        +        if unit not in _FUNCTION_TIMEUNITS:
        +            raise TypeError(f"unsupported Function duration unit: {unit!r}")
        +        if unit == "us":
        +            return {"type": "duration"}
        +        return {"type": f"duration:{unit}"}
             if pa.types.is_struct(data_type):
                 fields = list(data_type)
                 names = [field.name for field in fields]
        @@ -1109,8 +1860,29 @@ def _exact_arrow_type(
                 if pa.types.is_fixed_size_list(data_type):
                     value["length"] = data_type.list_size
                 return value
        -    if pa.types.is_map(data_type) and _data_type_has_blob_v2(data_type):
        -        raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
        +    if pa.types.is_map(data_type):
        +        if data_type.keys_sorted:
        +            raise TypeError(
        +                "unsupported Arrow type for Function signature: map keys_sorted=true "
        +                "is not supported"
        +            )
        +        key_field = data_type.key_field
        +        if key_field.nullable or key_field.type != pa.string():
        +            raise TypeError(
        +                "unsupported Arrow type for Function signature: map keys must be "
        +                "non-nullable utf8"
        +            )
        +        if _data_type_has_blob_v2(data_type):
        +            raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
        +        return {
        +            "type": "map",
        +            "fields": [
        +                _exact_arrow_field(
        +                    data_type.field(0),
        +                    inside_collection=True,
        +                )
        +            ],
        +        }
             raise TypeError(f"unsupported Arrow type for Function signature: {data_type}")
         
         
        @@ -1139,9 +1911,15 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
                     raise TypeError(
                         "Annotated Function types require exactly one PyArrow DataType"
                     )
        -        # A struct value is written as a dict, which has no Arrow type of its
        -        # own; the Annotated metadata supplies it.
        -        if base is dict or get_origin(base) is dict:
        +        # A struct value is written as a dict, while Decimal and timedelta
        +        # carry no precision or unit of their own; the Annotated metadata
        +        # supplies those types.
        +        if (
        +            base is dict
        +            or get_origin(base) is dict
        +            or base is Decimal
        +            or base is timedelta
        +        ):
                     base_nullable = False
                 else:
                     _, base_nullable = _annotation_type(base)
        @@ -1167,7 +1945,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
             if annotation is date:
                 return pa.date32(), nullable
             if annotation is datetime:
        +        # Existing default: microsecond precision, no timezone. Other units
        +        # and timezones require Annotated or an explicit schema.
                 return pa.timestamp("us"), nullable
        +    if annotation is Decimal:
        +        raise TypeError(
        +            "Decimal Function annotations require precision and scale; use "
        +            "Annotated[Decimal, pyarrow.decimal128(precision, scale)], "
        +            "Annotated[Decimal, pyarrow.decimal256(precision, scale)], or an "
        +            "explicit schema"
        +        )
        +    if annotation is timedelta:
        +        raise TypeError(
        +            "timedelta Function annotations require an explicit unit; use "
        +            "Annotated[timedelta, pyarrow.duration(unit)] or an explicit schema"
        +        )
             if get_origin(annotation) is list:
                 arguments = get_args(annotation)
                 if len(arguments) != 1:
        @@ -1176,9 +1968,39 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
                 if value_nullable:
                     raise TypeError("nullable Function list elements are not supported")
                 return _list_of(value_type), nullable
        +    if get_origin(annotation) is dict:
        +        arguments = get_args(annotation)
        +        if len(arguments) != 2:
        +            raise TypeError(f"unsupported dict annotation: {annotation!r}")
        +        key_type, value_annotation = arguments
        +        if key_type is not str:
        +            raise TypeError("Function map keys must be str")
        +        value_type, value_nullable = _annotation_type(value_annotation)
        +        return (
        +            pa.map_(
        +                pa.string(),
        +                pa.field("value", value_type, nullable=value_nullable),
        +            ),
        +            nullable,
        +        )
             raise TypeError(f"unsupported Function annotation: {annotation!r}")
         
         
        +def _validate_callable(function: Any) -> None:
        +    if hasattr(function, "__wrapped__"):
        +        raise TypeError(
        +            "decorated wrappers are not supported; put caching inside the function "
        +            "body or use a class Function with a cache in __init__"
        +        )
        +    if inspect.isgeneratorfunction(function) or inspect.isasyncgenfunction(function):
        +        raise TypeError(
        +            "generator Functions are not supported; return a value instead of "
        +            "yielding, or return a list for multiple values"
        +        )
        +    if inspect.isfunction(function) and function.__name__ == "":
        +        raise TypeError("lambda Functions are not supported; use a named def instead")
        +
        +
         def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Parameter, ...]:
             parameters = tuple(inspect.signature(function).parameters.values())
             for parameter in parameters:
        @@ -1189,10 +2011,114 @@ def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Paramete
                 ):
                     raise TypeError("Function callables require named, non-variadic parameters")
                 if parameter.default is not inspect.Parameter.empty:
        -            raise TypeError("Function callable defaults are not supported")
        +            raise TypeError(
        +                f"Function callable defaults are not supported: {parameter.name!r}; "
        +                "move configuration parameters to a class Function's __init__ "
        +                "and pass them as binding-time initialization values"
        +            )
             return parameters
         
         
        +def _uses_blob_writer(annotation: Any) -> bool:
        +    return annotation is BlobWriter or any(
        +        _uses_blob_writer(argument) for argument in get_args(annotation)
        +    )
        +
        +
        +def _annotated_blob_writer_field(
        +    annotation: Any, name: str, field: Optional[pa.Field] = None
        +) -> pa.Field:
        +    """Infer a writer-bearing field or mark the matching leaf in an explicit field."""
        +    nullable = False
        +    arrow_type = None
        +    while True:
        +        origin = get_origin(annotation)
        +        if origin is Annotated:
        +            annotation, *metadata = get_args(annotation)
        +            types_ = [value for value in metadata if isinstance(value, pa.DataType)]
        +            if len(types_) != 1:
        +                raise TypeError(
        +                    "Annotated Function types require exactly one PyArrow DataType"
        +                )
        +            if arrow_type is None:
        +                arrow_type = types_[0]
        +        elif origin in (Union, types.UnionType):
        +            arguments = get_args(annotation)
        +            branches = tuple(arg for arg in arguments if arg is not type(None))
        +            nullable |= len(branches) != len(arguments)
        +            if len(branches) == 1:
        +                (annotation,) = branches
        +            elif frozenset(branches) == {BlobWriter, bytes}:
        +                annotation = BlobWriter
        +            else:
        +                raise TypeError(f"unsupported union annotation: {annotation!r}")
        +        else:
        +            break
        +
        +    if field is None and arrow_type is not None:
        +        field = pa.field(name, arrow_type, nullable=nullable)
        +    if annotation is BlobWriter:
        +        if field is None:
        +            return BlobWriter.field(name, nullable=nullable)
        +        if not _is_blob_v2_field(field):
        +            raise TypeError("BlobWriter output requires a Blob v2 field")
        +        _validate_exact_arrow_field(field, allow_blob_writer=True)
        +        return _mark_blob_writer(field)
        +    if get_origin(annotation) is list:
        +        (element,) = get_args(annotation)
        +        if field is None:
        +            child = _annotated_blob_writer_field(element, "item")
        +            return pa.field(name, pa.list_(child), nullable=nullable)
        +        if not (pa.types.is_list(field.type) or pa.types.is_large_list(field.type)):
        +            raise TypeError("a list of BlobWriter values requires a list output field")
        +        child = field.type.value_field
        +        child = _annotated_blob_writer_field(element, child.name, child)
        +        list_type = pa.large_list if pa.types.is_large_list(field.type) else pa.list_
        +        return field.with_type(list_type(child))
        +    raise TypeError(
        +        "BlobWriter return annotations require a BlobWriter or list of BlobWriter "
        +        "values. Use BlobWriter.field in the output schema for named results."
        +    )
        +
        +
        +def _writer_annotation_output(annotation, output_schema, *, vectorized: bool):
        +    if vectorized:
        +        arguments = get_args(annotation)
        +        origin = get_origin(annotation)
        +        if origin is list and len(arguments) == 1:
        +            (annotation,) = arguments
        +        elif origin is tuple and len(arguments) == 2 and arguments[1] is Ellipsis:
        +            annotation = arguments[0]
        +        else:
        +            raise TypeError(
        +                "vectorized BlobWriter Functions must annotate a row-aligned list "
        +                "or tuple of results"
        +            )
        +    if output_schema is None:
        +        return _annotated_blob_writer_field(annotation, "result")
        +    if isinstance(output_schema, pa.DataType):
        +        output_schema = pa.field("result", output_schema, nullable=False)
        +    if not isinstance(output_schema, pa.Field):
        +        raise TypeError("use BlobWriter.field in the output schema for named results")
        +    return _annotated_blob_writer_field(annotation, output_schema.name, output_schema)
        +
        +
        +def _blob_writer_paths(field: pa.Field) -> tuple[_BlobWriterPath, ...]:
        +    if _is_blob_v2_field(field):
        +        return ((),) if _BLOB_WRITER_METADATA_KEY in (field.metadata or {}) else ()
        +    if pa.types.is_struct(field.type):
        +        return tuple(
        +            (_BlobWriterFieldStep(field=child.name), *path)
        +            for child in field.type
        +            for path in _blob_writer_paths(child)
        +        )
        +    if pa.types.is_list(field.type) or pa.types.is_large_list(field.type):
        +        return tuple(
        +            ("item", *path) for path in _blob_writer_paths(field.type.value_field)
        +        )
        +    return ()
        +
        +
         def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutput:
             if isinstance(output, pa.Schema):
                 if output.metadata:
        @@ -1203,7 +2129,7 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp
                 and not _is_blob_v2_field(output)
                 and pa.types.is_struct(output.type)
             ):
        -        _validate_exact_arrow_field(output)
        +        _validate_exact_arrow_field(output, allow_blob_writer=True)
                 if output.nullable:
                     raise ValueError("Function output must be non-nullable")
                 fields = tuple(output.type)
        @@ -1219,32 +2145,39 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp
                     raise TypeError(
                         "output_schema must be a PyArrow DataType, Field, or Schema"
                     )
        -        _validate_exact_arrow_field(field)
        -        if field.nullable:
        -            raise ValueError("Function output must be non-nullable")
        +        arrow_type = _canonical_arrow_field(field, collection_blobs=True)
        +        if field.nullable and _is_blob_v2_field(field):
        +            raise ValueError("Blob v2 Function output must be non-nullable")
        +        paths = _blob_writer_paths(field)
                 return FunctionOutput(
        -            kind="scalar",
        -            arrow_type=_canonical_arrow_field(field, collection_blobs=True),
        -            nullable=False,
        +            kind="scalar_blob_writer" if paths else "scalar",
        +            arrow_type=arrow_type,
        +            nullable=field.nullable,
        +            blob_writer_paths=paths,
                 )
         
             if not fields:
                 raise ValueError("named-struct Function output must contain at least one field")
        -    for field in fields:
        -        _validate_exact_arrow_field(field)
             names = [field.name for field in fields]
             if len(set(names)) != len(names):
                 raise ValueError("Function output field names must be unique")
        +    results = tuple(
        +        FunctionResultField(
        +            name=field.name,
        +            arrow_type=_canonical_arrow_field(field, collection_blobs=True),
        +            nullable=field.nullable,
        +        )
        +        for field in fields
        +    )
        +    paths = tuple(
        +        (_BlobWriterFieldStep(field=field.name), *path)
        +        for field in fields
        +        for path in _blob_writer_paths(field)
        +    )
             return FunctionOutput(
        -        kind="named_struct",
        -        fields=tuple(
        -            FunctionResultField(
        -                name=field.name,
        -                arrow_type=_canonical_arrow_field(field, collection_blobs=True),
        -                nullable=field.nullable,
        -            )
        -            for field in fields
        -        ),
        +        kind="named_struct_blob_writer" if paths else "named_struct",
        +        fields=results,
        +        blob_writer_paths=paths,
             )
         
         
        @@ -1266,6 +2199,8 @@ def _infer_signature(
         
             def input_parameter(field):
                 annotation = annotations.get(field.name)
        +        if _uses_blob_writer(annotation):
        +            raise TypeError("BlobWriter is only supported in Function outputs")
                 if get_origin(annotation) in (Union, types.UnionType):
                     choices = [
                         value for value in get_args(annotation) if value is not type(None)
        @@ -1321,13 +2256,20 @@ def _infer_signature(
                 missing.append("return")
             if missing:
                 raise TypeError(f"missing Function annotations: {missing!r}")
        +    return_annotation = annotations.get("return")
        +    if _uses_blob_writer(return_annotation):
        +        output_schema = _writer_annotation_output(
        +            return_annotation,
        +            output_schema,
        +            vectorized=_is_vectorized_callable(function, method=method),
        +        )
             if output_schema is not None:
                 output = _function_output(output_schema)
             else:
        -        output_type, output_nullable = _annotation_type(annotations["return"])
        -        if output_nullable:
        -            raise ValueError("Function output must be non-nullable")
        -        output = _function_output(pa.field("result", output_type, nullable=False))
        +        output_type, output_nullable = _annotation_type(return_annotation)
        +        output = _function_output(
        +            pa.field("result", output_type, nullable=output_nullable)
        +        )
             if inputs is not None:
                 return FunctionSignature(inputs=inputs, output=output)
         
        @@ -1352,33 +2294,79 @@ def _infer_signature(
             return FunctionSignature(inputs=tuple(inputs), output=output)
         
         
        -def _is_udf_decorator(node: ast.expr) -> bool:
        +def _is_vectorized_callable(function: Callable[..., Any], *, method: bool) -> bool:
        +    parameters = _callable_parameters(function)
        +    if method:
        +        parameters = parameters[1:]
        +    annotations = get_type_hints(function, include_extras=True)
        +    annotated = tuple(annotations.get(parameter.name) for parameter in parameters)
        +    return (len(annotated) == 1 and annotated[0] is pa.RecordBatch) or (
        +        bool(annotated) and all(annotation is pa.Array for annotation in annotated)
        +    )
        +
        +
        +# Both spellings strip from packaged source; `udf` is the deprecated alias.
        +_DECORATOR_NAMES = frozenset({"function", "udf"})
        +
        +
        +def _is_function_decorator(node: ast.expr) -> bool:
             if isinstance(node, ast.Call):
                 node = node.func
        -    return (isinstance(node, ast.Name) and node.id == "udf") or (
        -        isinstance(node, ast.Attribute) and node.attr == "udf"
        +    return (isinstance(node, ast.Name) and node.id in _DECORATOR_NAMES) or (
        +        isinstance(node, ast.Attribute) and node.attr in _DECORATOR_NAMES
             )
         
         
        -def _literal_source(value: Any) -> str:
        -    if value is None or type(value) in (bool, int, str, bytes):
        -        return repr(value)
        -    if type(value) is float and math.isfinite(value):
        -        return repr(value)
        -    if type(value) is tuple:
        -        children = ", ".join(_literal_source(child) for child in value)
        -        if len(value) == 1:
        -            children += ","
        -        return f"({children})"
        -    raise TypeError(
        +# A captured value is inlined into the artifact source; larger data belongs in a
        +# table or a package resource.
        +_MAX_CAPTURED_SOURCE = 1024 * 1024
        +# Far below CPython's parser nesting limit.
        +_MAX_CAPTURED_DEPTH = 32
        +_CAPTURE_REMEDY = "Define this value inside the function or class body instead."
        +
        +
        +def _unsupported_capture(name: str, kind: str) -> TypeError:
        +    return TypeError(
                 "Function source references an unsupported global value of type "
        -        f"{type(value).__name__}"
        +        f"{kind} in {name!r}. Captured globals can be None, bool, int, str, "
        +        "bytes, or finite float values; tuples, lists, dicts, sets, or frozensets "
        +        "of supported values; PyArrow data types, fields, or schemas; or NumPy "
        +        "arrays or scalars of bool, integer, float16, float32, or float64 dtypes. "
        +        + _CAPTURE_REMEDY
             )
         
         
        +def _python_extension_type(data_type: pa.DataType) -> Optional[pa.ExtensionType]:
        +    """The first extension type within `data_type` whose class is defined in
        +    Python. IPC carries only its name, so it deserializes as the storage type
        +    wherever that class is not registered."""
        +    if isinstance(data_type, pa.ExtensionType):
        +        return data_type
        +    if isinstance(data_type, pa.BaseExtensionType):
        +        return _python_extension_type(data_type.storage_type)
        +    if isinstance(data_type, pa.DictionaryType):
        +        return _python_extension_type(data_type.value_type)
        +    for index in range(data_type.num_fields):
        +        found = _python_extension_type(data_type.field(index).type)
        +        if found is not None:
        +            return found
        +    return None
        +
        +
         _DYNAMIC_NAMESPACE_ACCESS = frozenset(
             {"globals", "locals", "vars", "eval", "exec", "compile", "__import__"}
         )
        +# Static diagnostic operations the packager can reconstruct. Anything else that
        +# reaches through a namespace-access module remains unrepresentable.
        +_APPROVED_NAMESPACE_ATTRIBUTES = {
        +    "sys": frozenset({"stderr", "version_info"}),
        +    "importlib.metadata": frozenset({"version"}),
        +}
        +_APPROVED_NAMESPACE_OPERATIONS = (
        +    "sys.stderr",
        +    "sys.version_info",
        +    "importlib.metadata.version",
        +)
         # Modules that hand out namespaces (`sys.modules`, `builtins`, importers,
         # introspection). The artifact's module namespace holds only the names it was
         # packaged with, so reaching around it cannot be represented.
        @@ -1387,21 +2375,176 @@ _NAMESPACE_MODULES = frozenset(
         )
         
         
        -def _namespace_acquisition(
        -    definition: ast.FunctionDef, references: set[str]
        -) -> list[str]:
        -    found = set(references & _DYNAMIC_NAMESPACE_ACCESS)
        +_NAMESPACE_HELPER_HINT = (
        +    "Move this code into an importable helper module supplied with code=, pip=, "
        +    "or conda=, then import and call the helper from the Function."
        +)
        +
        +
        +_APPROVED_NAMESPACE_HINT = (
        +    "The supported diagnostic operations are "
        +    + ", ".join(_APPROVED_NAMESPACE_OPERATIONS)
        +    + ". "
        +)
        +
        +
        +def _namespace_operation_error(operations: Sequence[str]) -> ValueError:
        +    label = operations[0] if len(operations) == 1 else list(operations)
        +    return ValueError(
        +        f"@function cannot package namespace operation {label!r}. "
        +        "The artifact's module namespace holds only the names it was packaged "
        +        "with, so references that reach around it cannot be represented. "
        +        + _APPROVED_NAMESPACE_HINT
        +        + _NAMESPACE_HELPER_HINT
        +    )
        +
        +
        +def _namespace_import_error(modules: Sequence[str]) -> ValueError:
        +    return ValueError(
        +        f"@function cannot package imports from namespace-access modules: {modules!r}. "
        +        f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) "
        +        "are blocked because they can access names outside the packaged "
        +        "Function's reconstructed module namespace. "
        +        + _APPROVED_NAMESPACE_HINT
        +        + _NAMESPACE_HELPER_HINT
        +    )
        +
        +
        +def _namespace_import_bindings(
        +    definition: Union[ast.FunctionDef, ast.ClassDef],
        +) -> tuple[dict[str, frozenset[str]], list[str], list[str]]:
        +    """Return approved diagnostic bindings and rejected imports.
        +
        +    A binding maps the local name an import creates to the attribute paths
        +    that may be read through it. Rejected modules and operations are kept
        +    separate so each error names the relevant rule.
        +    """
        +    bindings: dict[str, frozenset[str]] = {}
        +    blocked_modules: set[str] = set()
        +    blocked_operations: set[str] = set()
             for node in ast.walk(definition):
                 if isinstance(node, ast.Import):
        -            found.update(
        -                alias.name
        -                for alias in node.names
        -                if alias.name.split(".")[0] in _NAMESPACE_MODULES
        -            )
        -        elif isinstance(node, ast.ImportFrom) and node.module:
        -            if node.module.split(".")[0] in _NAMESPACE_MODULES:
        -                found.add(node.module)
        -    return sorted(found)
        +            for alias in node.names:
        +                root = alias.name.split(".")[0]
        +                if root not in _NAMESPACE_MODULES:
        +                    continue
        +                attributes = _APPROVED_NAMESPACE_ATTRIBUTES.get(alias.name)
        +                if attributes is None:
        +                    blocked_modules.add(alias.name)
        +                    continue
        +                if alias.asname:
        +                    name = alias.asname
        +                    bases = frozenset(f"{name}.{attribute}" for attribute in attributes)
        +                else:
        +                    name = root
        +                    module = alias.name if "." in alias.name else name
        +                    bases = frozenset(
        +                        f"{module}.{attribute}" for attribute in attributes
        +                    )
        +                bindings[name] = bindings.get(name, frozenset()) | bases
        +        elif (
        +            isinstance(node, ast.ImportFrom)
        +            and node.level == 0
        +            and node.module
        +            and node.module.split(".")[0] in _NAMESPACE_MODULES
        +        ):
        +            if node.module == "importlib":
        +                for alias in node.names:
        +                    if alias.name == "metadata":
        +                        name = alias.asname or "metadata"
        +                        bindings[name] = bindings.get(name, frozenset()) | frozenset(
        +                            {f"{name}.version"}
        +                        )
        +                    else:
        +                        blocked_modules.add("importlib")
        +                continue
        +            attributes = _APPROVED_NAMESPACE_ATTRIBUTES.get(node.module)
        +            if attributes is None:
        +                blocked_modules.add(node.module)
        +                continue
        +            for alias in node.names:
        +                if alias.name in attributes:
        +                    name = alias.asname or alias.name
        +                    bindings[name] = bindings.get(name, frozenset()) | frozenset({name})
        +                else:
        +                    blocked_operations.add(f"{node.module}.{alias.name}")
        +    return bindings, sorted(blocked_modules), sorted(blocked_operations)
        +
        +
        +def _namespace_binding_errors(
        +    definition: Union[ast.FunctionDef, ast.ClassDef],
        +    bindings: Mapping[str, frozenset[str]],
        +) -> list[str]:
        +    """Operations that read a diagnostic binding outside its approved paths."""
        +    if not bindings:
        +        return []
        +    parents: dict[ast.AST, ast.AST] = {}
        +    for node in ast.walk(definition):
        +        for child in ast.iter_child_nodes(node):
        +            parents[child] = node
        +    invalid: set[str] = set()
        +    for node in ast.walk(definition):
        +        if not isinstance(node, ast.Name):
        +            continue
        +        allowed = bindings.get(node.id)
        +        if allowed is None:
        +            continue
        +        if not isinstance(node.ctx, ast.Load):
        +            invalid.add(node.id)
        +            continue
        +        path = node.id
        +        current: ast.AST = node
        +        while True:
        +            parent = parents.get(current)
        +            if isinstance(parent, ast.Attribute) and parent.value is current:
        +                path = f"{path}.{parent.attr}"
        +                current = parent
        +                continue
        +            break
        +        if not any(path == base or path.startswith(f"{base}.") for base in allowed):
        +            invalid.add(path)
        +            continue
        +        if any(part.startswith("__") for part in path.split(".")[1:]):
        +            invalid.add(path)
        +    return sorted(invalid)
        +
        +
        +def _approved_global_namespace_binding(
        +    definition: Optional[Union[ast.FunctionDef, ast.ClassDef]],
        +    name: str,
        +    value: Any,
        +) -> Optional[str]:
        +    """The artifact import for an approved diagnostic global, if any."""
        +    if definition is None:
        +        return None
        +    if isinstance(value, types.ModuleType):
        +        if value is sys:
        +            bases = frozenset({f"{name}.stderr", f"{name}.version_info"})
        +            line = f"import sys as {name}"
        +        elif value is importlib.metadata:
        +            bases = frozenset({f"{name}.version"})
        +            line = f"import importlib.metadata as {name}"
        +        elif value is importlib and name == "importlib":
        +            # ``import importlib.metadata`` binds the top-level package name.
        +            bases = frozenset({"importlib.metadata.version"})
        +            line = "import importlib.metadata"
        +        else:
        +            return None
        +    elif value is sys.stderr:
        +        bases = frozenset({name})
        +        line = f"from sys import stderr as {name}"
        +    elif value is sys.version_info:
        +        bases = frozenset({name})
        +        line = f"from sys import version_info as {name}"
        +    elif value is importlib.metadata.version:
        +        bases = frozenset({name})
        +        line = f"from importlib.metadata import version as {name}"
        +    else:
        +        return None
        +    invalid = _namespace_binding_errors(definition, {name: bases})
        +    if invalid:
        +        raise _namespace_operation_error(invalid)
        +    return line
         
         
         def _module_references(module_source: str) -> set[str]:
        @@ -1421,7 +2564,7 @@ def _module_references(module_source: str) -> set[str]:
                     visit(child, found)
         
             found: set[str] = set()
        -    module = symtable.symtable(module_source, "", "exec")
        +    module = symtable.symtable(module_source, "", "exec")
             for symbol in module.get_symbols():
                 if (
                     symbol.is_referenced()
        @@ -1494,7 +2637,7 @@ def _definition_node(
                 )
             except (OSError, TypeError) as error:
                 raise ValueError(
        -            f"@udf requires inspectable Python source for {target.__qualname__!r}"
        +            f"@function requires inspectable Python source for {target.__qualname__!r}"
                 ) from error
             module = ast.parse(source)
             is_class = inspect.isclass(target)
        @@ -1509,15 +2652,16 @@ def _definition_node(
             ]
             if len(definitions) != 1 or isinstance(definitions[0], ast.AsyncFunctionDef):
                 raise ValueError(
        -            "@udf source must contain exactly one "
        +            "@function source must contain exactly one "
                     + ("class" if is_class else "synchronous function")
                 )
             definition = definitions[0]
             if entry:
                 if any(
        -            not _is_udf_decorator(decorator) for decorator in definition.decorator_list
        +            not _is_function_decorator(decorator)
        +            for decorator in definition.decorator_list
                 ):
        -            raise ValueError("@udf cannot package additional Python decorators")
        +            raise ValueError("@function cannot package additional Python decorators")
                 definition.decorator_list = []
             return definition
         
        @@ -1528,7 +2672,7 @@ def _definition_namespace(target: Any) -> Mapping[str, Any]:
                 module = sys.modules.get(target.__module__)
                 if module is None:
                     raise ValueError(
        -                f"@udf cannot resolve the module of {target.__qualname__!r}"
        +                f"@function cannot resolve the module of {target.__qualname__!r}"
                     )
                 namespace = vars(module)
                 environment = namespace.get("__builtins__", builtins)
        @@ -1543,7 +2687,7 @@ def _definition_namespace(target: Any) -> Mapping[str, Any]:
             # The artifact runs under the standard builtins; only the exact mapping is
             # provably equivalent (a subclass or copy can change lookups and hooks).
             if environment is not vars(builtins):
        -        raise ValueError("@udf cannot package a non-standard builtins environment")
        +        raise ValueError("@function cannot package a non-standard builtins environment")
             return namespace
         
         
        @@ -1557,7 +2701,7 @@ def _is_self_reference(target: Any, namespace: Mapping[str, Any], name: str) ->
                 return True
             # The decorator's own result is the one wrapper known to behave like
             # `target`; any other binding may differ from the packaged definition.
        -    return type(bound) is UdfDefinition and bound._function is target
        +    return type(bound) is FunctionDefinition and bound._function is target
         
         
         def _packaged_by_source(value: Any) -> bool:
        @@ -1570,13 +2714,36 @@ def _packaged_by_source(value: Any) -> bool:
             qualname = value.__qualname__
             if "<" in qualname or "." in qualname:
                 raise ValueError(
        -            f"@udf cannot package {qualname!r}: only module-level functions and "
        +            f"@function cannot package {qualname!r}: only module-level functions and "
                     "classes travel with a Function, not lambdas, closures, or nested "
                     "definitions"
                 )
             return True
         
         
        +def _validate_package_requirements(kind: str, packages: Sequence[str]) -> None:
        +    for index, package in enumerate(packages):
        +        field = f"{kind}[{index}]"
        +        if not isinstance(package, str):
        +            raise TypeError(f"{field} must be a string, got {package!r}")
        +        if not package or package != package.strip():
        +            raise ValueError(
        +                f"{field} requirement {package!r} must be non-empty and trimmed"
        +            )
        +        try:
        +            if kind == "conda":
        +                _validate_conda_requirement(package)
        +            else:
        +                candidate = package
        +                if re.match(r"^[A-Za-z][A-Za-z0-9+.-]*://", package):
        +                    candidate = f"dependency @ {package}"
        +                Requirement(candidate)
        +        except ValueError as error:
        +            raise ValueError(
        +                f"invalid {field} requirement {package!r}: {error}"
        +            ) from error
        +
        +
         def _requirement_name(requirement: str) -> str:
             requirement = requirement.rpartition("::")[2]
             match = _REQUIREMENT_NAME.match(requirement.strip())
        @@ -1632,12 +2799,31 @@ def _module_locations_for_name(module_name: str) -> tuple[str, ...]:
             return ()
         
         
        +def _blob_writer_annotation_source(annotation: Any, writer_name: str) -> str:
        +    if annotation is BlobWriter:
        +        return writer_name
        +    if annotation is type(None):
        +        return "None"
        +    if annotation is bytes:
        +        return "bytes"
        +    if annotation is Ellipsis:
        +        return "..."
        +    origin = get_origin(annotation)
        +    arguments = get_args(annotation)
        +    if origin is Annotated:
        +        return _blob_writer_annotation_source(arguments[0], writer_name)
        +    elements = [_blob_writer_annotation_source(arg, writer_name) for arg in arguments]
        +    if origin in (Union, types.UnionType):
        +        return " | ".join(elements)
        +    return f"{origin.__name__}[{', '.join(elements)}]"
        +
        +
         class _SourcePackager:
             """Builds the entry module of a Function artifact.
         
             The module holds the definition plus exactly the module-level names it
             references: modules as imports, importable classes and functions as
        -    imports, literals inline, and functions and classes defined in
        +    imports, captured values inline, and functions and classes defined in
             ``__main__`` by source, recursively, dependencies first.
             """
         
        @@ -1645,6 +2831,7 @@ class _SourcePackager:
                 self._code_modules = code_modules
                 self._requirements = requirements
                 self._imports: dict[str, str] = {}
        +        self._support_imports: dict[str, str] = {}
                 self._definitions: list[str] = []
                 self._packaged: set[int] = set()
                 self._names: dict[str, Any] = {}
        @@ -1653,8 +2840,13 @@ class _SourcePackager:
             def package(self, target: Any, signature: FunctionSignature) -> str:
                 entry = self._definition(target, entry=True, signature=signature)
                 parts = [_SOURCE_HEADER]
        -        if self._imports:
        -            parts.extend(["", *(self._imports[name] for name in sorted(self._imports))])
        +        # Captured values are rebuilt with the support modules, so those come first.
        +        imports = [
        +            *(self._support_imports[alias] for alias in sorted(self._support_imports)),
        +            *(self._imports[name] for name in sorted(self._imports)),
        +        ]
        +        if imports:
        +            parts.extend(["", *imports])
                 for definition in self._definitions:
                     parts.extend(["", definition])
                 parts.extend(["", entry, ""])
        @@ -1666,61 +2858,74 @@ class _SourcePackager:
                 definition = _definition_node(target, entry=entry)
                 if not inspect.isclass(target) and inspect.getclosurevars(target).nonlocals:
                     raise ValueError(
        -                "@udf cannot package functions that capture closure values"
        +                "@function cannot package functions that capture closure values"
                     )
                 namespace = _definition_namespace(target)
        -        reader_name = (
        -            self._blob_annotations(definition, signature, namespace)
        +        blob_bindings = (
        +            self._blob_annotations(target, definition, signature, namespace)
                     if signature is not None
        -            else None
        +            else {}
                 )
                 source = ast.unparse(definition)
                 references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n")
        -        dynamic = _namespace_acquisition(definition, references)
        +        dynamic = sorted(references & _DYNAMIC_NAMESPACE_ACCESS)
                 if dynamic:
                     raise ValueError(
        -                f"@udf cannot package dynamic namespace access: {dynamic!r}"
        +                f"@function cannot package dynamic namespace access: {dynamic!r}. "
        +                "These operations can access names outside the packaged "
        +                "Function's reconstructed module namespace. Reference dependencies "
        +                "explicitly. " + _NAMESPACE_HELPER_HINT
                     )
        +        namespace_bindings, blocked_modules, blocked_operations = (
        +            _namespace_import_bindings(definition)
        +        )
        +        if blocked_modules:
        +            raise _namespace_import_error(blocked_modules)
        +        if blocked_operations:
        +            raise _namespace_operation_error(blocked_operations)
        +        invalid_operations = _namespace_binding_errors(definition, namespace_bindings)
        +        if invalid_operations:
        +            raise _namespace_operation_error(invalid_operations)
                 self._warn_unshipped_direct_imports(definition)
                 self._packaged.add(id(target))
                 self._claim(target.__name__, ("definition", id(target)))
        -        if reader_name is not None:
        -            self._bind(reader_name, BlobReader)
        +        for name, blob_type in blob_bindings.items():
        +            self._bind(name, blob_type, definition=definition)
                 unresolved = []
                 for name in sorted(references):
                     if name == target.__name__:
                         if not _is_self_reference(target, namespace, name):
                             raise ValueError(
        -                        f"@udf cannot package {name!r}: the module binds that name "
        -                        "to another value, which the artifact's own definition "
        -                        "would shadow"
        +                        f"@function cannot package {name!r}: the module binds that "
        +                        "name to another value, which the artifact's own "
        +                        "definition would shadow"
                             )
                         continue
                     if name in namespace:
        -                self._bind(name, namespace[name])
        +                self._bind(name, namespace[name], definition=definition)
                     elif not hasattr(builtins, name):
                         unresolved.append(name)
                 if unresolved:
                     raise ValueError(
        -                f"@udf source contains unresolved global names: {unresolved!r}"
        +                f"@function source contains unresolved global names: {unresolved!r}"
                     )
                 return source
         
             def _blob_annotations(
                 self,
        +        target: Any,
                 definition: Union[ast.FunctionDef, ast.ClassDef],
                 signature: FunctionSignature,
                 namespace: Mapping[str, Any],
        -    ) -> Optional[str]:
        -        """Bind reader inputs to the worker type, including postponed aliases."""
        +    ) -> dict[str, type]:
        +        """Bind Blob annotations to worker types, including postponed aliases."""
                 readers = {
                     parameter.name: parameter
                     for parameter in signature.inputs
                     if parameter.blob_access == "reader"
                 }
        -        if not readers:
        -            return None
        -        call = definition
        +        if not readers and not signature.output.blob_writer_paths:
        +            return {}
                 if isinstance(definition, ast.ClassDef):
                     call = next(
                         (
        @@ -1730,54 +2935,95 @@ class _SourcePackager:
                         ),
                         None,
                     )
        -        if call is None:
        -            return None
        -        # Avoid shadowing globals used by the body or other packaged definitions.
        -        name = "_lance_blob_reader"
        -        while name in namespace or name in self._names or name == definition.name:
        -            name += "_"
        -        for argument in (*call.args.args, *call.args.kwonlyargs):
        -            if argument.arg in readers:
        -                annotation = name
        -                if readers[argument.arg].nullable:
        -                    annotation += " | None"
        -                argument.annotation = ast.parse(annotation, mode="eval").body
        -        return name
        +            if call is None:
        +                return {}
        +        else:
        +            call = definition
        +
        +        def alias(name: str) -> str:
        +            # Avoid shadowing globals used by the body or other definitions.
        +            while name in namespace or name in self._names or name == definition.name:
        +                name += "_"
        +            return name
        +
        +        bindings = {}
        +        if readers:
        +            name = alias("_lance_blob_reader")
        +            for argument in (*call.args.args, *call.args.kwonlyargs):
        +                if argument.arg in readers:
        +                    annotation = name
        +                    if readers[argument.arg].nullable:
        +                        annotation += " | None"
        +                    argument.annotation = ast.parse(annotation, mode="eval").body
        +            bindings[name] = BlobReader
        +        if signature.output.blob_writer_paths:
        +            method = inspect.isclass(target)
        +            callable_ = _class_call(target) if method else target
        +            annotations = get_type_hints(callable_, include_extras=True)
        +            if _is_vectorized_callable(callable_, method=method):
        +                name = alias("_lance_arrow")
        +                for argument in (*call.args.args, *call.args.kwonlyargs):
        +                    arrow_type = annotations.get(argument.arg)
        +                    if arrow_type is pa.Array or arrow_type is pa.RecordBatch:
        +                        argument.annotation = ast.parse(
        +                            f"{name}.{arrow_type.__name__}", mode="eval"
        +                        ).body
        +                bindings[name] = pa
        +            return_type = annotations.get("return")
        +            if _uses_blob_writer(return_type):
        +                name = alias("_lance_blob_writer")
        +                annotation = _blob_writer_annotation_source(return_type, name)
        +                call.returns = ast.parse(annotation, mode="eval").body
        +                bindings[name] = BlobWriter
        +        return bindings
         
             def _claim(self, name: str, meaning: Any) -> None:
                 claimed = self._names.setdefault(name, meaning)
                 if claimed != meaning:
                     raise ValueError(
        -                f"@udf cannot package {name!r}: packaged definitions bind that "
        +                f"@function cannot package {name!r}: packaged definitions bind that "
                         "name to different values"
                     )
         
        -    def _bind(self, name: str, value: Any) -> None:
        +    def _bind(
        +        self,
        +        name: str,
        +        value: Any,
        +        *,
        +        definition: Optional[Union[ast.FunctionDef, ast.ClassDef]] = None,
        +    ) -> None:
                 if _packaged_by_source(value):
                     if value.__name__ != name:
                         raise ValueError(
        -                    f"@udf packages {value.__qualname__!r} by source, so it must be "
        -                    f"referenced by its own name, not {name!r}"
        +                    f"@function packages {value.__qualname__!r} by source, so it "
        +                    f"must be referenced by its own name, not {name!r}"
                         )
                     if id(value) not in self._packaged:
                         self._definitions.append(self._definition(value, entry=False))
                     self._claim(name, ("definition", id(value)))
                     return
        -        line = self._global_source(name, value)
        +        line = self._global_source(name, value, definition=definition)
                 self._claim(name, line)
                 self._imports[name] = line
         
        -    def _global_source(self, name: str, value: Any) -> str:
        +    def _global_source(
        +        self,
        +        name: str,
        +        value: Any,
        +        *,
        +        definition: Optional[Union[ast.FunctionDef, ast.ClassDef]] = None,
        +    ) -> str:
                 """One module-level line that rebinds `name` to `value` in the artifact:
        -        an import for modules and importable classes/functions, a literal
        -        otherwise."""
        -        if value is BlobReader:
        -            return f"from lance_blob import BlobReader as {name}"
        +        an import for modules and importable classes/functions, a captured
        +        copy otherwise."""
        +        approved = _approved_global_namespace_binding(definition, name, value)
        +        if approved is not None:
        +            return approved
        +        if value is BlobReader or value is BlobWriter:
        +            return f"from lance_blob import {value.__name__} as {name}"
                 if isinstance(value, types.ModuleType):
                     if value.__name__.split(".")[0] in _NAMESPACE_MODULES:
        -                raise ValueError(
        -                    f"@udf cannot package dynamic namespace access: {value.__name__!r}"
        -                )
        +                raise _namespace_import_error([value.__name__])
                     try:
                         imported = importlib.import_module(value.__name__)
                     except ImportError:
        @@ -1805,12 +3051,157 @@ class _SourcePackager:
                     if imported is value:
                         self._require_importable(module_name)
                         return f"from {module_name} import {qualname} as {name}"
        -        return f"{name} = {_literal_source(value)}"
        +        return f"{name} = {self._captured_source(name, value)}"
        +
        +    def _captured_source(self, name: str, value: Any) -> str:
        +        """An expression that rebuilds a copy of the global `name`.
        +
        +        Literals and containers are written as Python literals, with set
        +        elements sorted by their source so the artifact does not depend on hash
        +        randomization. Arrow values are rebuilt from Arrow's IPC schema encoding
        +        and NumPy values from their dtype and elements.
        +        """
        +        remaining = _MAX_CAPTURED_SOURCE
        +        enclosing: set[int] = set()
        +
        +        def too_large() -> ValueError:
        +            return ValueError(
        +                f"Function global {name!r} is too large to capture: its source "
        +                f"exceeds {_MAX_CAPTURED_SOURCE} characters. Load large data inside "
        +                "the function or class body instead, for example from a table or a "
        +                "package resource shipped with code=."
        +            )
        +
        +        def charge(source: str, nested: Sequence[str] = ()) -> str:
        +            nonlocal remaining
        +            remaining -= len(source) - sum(map(len, nested))
        +            if remaining < 0:
        +                raise too_large()
        +            return source
        +
        +        def emit(value: Any) -> str:
        +            if value is None or type(value) in (bool, int, str, bytes):
        +                return charge(repr(value))
        +            if type(value) is float and math.isfinite(value):
        +                return charge(repr(value))
        +            if isinstance(value, (pa.DataType, pa.Field, pa.Schema)):
        +                return charge(self._arrow_source(name, value))
        +            numpy = sys.modules.get("numpy")
        +            if numpy is not None and (
        +                type(value) is numpy.ndarray or isinstance(value, numpy.generic)
        +            ):
        +                return emit_numpy(numpy, value)
        +            if type(value) in (tuple, list, dict, set, frozenset):
        +                return emit_container(value)
        +            raise _unsupported_capture(name, type(value).__name__)
        +
        +        def emit_numpy(numpy: types.ModuleType, value: Any) -> str:
        +            # These convert to exact Python values; longdouble stays a NumPy scalar.
        +            if value.dtype.kind not in "biuf" or value.dtype.type is numpy.longdouble:
        +                raise _unsupported_capture(
        +                    name, f"{type(value).__name__} with dtype {value.dtype}"
        +                )
        +            # Every element takes at least one character; check before tolist().
        +            if value.size > remaining:
        +                raise too_large()
        +            alias = self._support_module("numpy")
        +            dtype = repr(value.dtype.str)
        +            if isinstance(value, numpy.generic):
        +                item = emit(value.item())
        +                return charge(f"{alias}.dtype({dtype}).type({item})", (item,))
        +            if value.size == 0:
        +                return charge(
        +                    f"{alias}.array([], dtype={dtype}).reshape({value.shape!r})"
        +                )
        +            elements = emit(value.tolist())
        +            source = f"{alias}.array({elements}, dtype={dtype})"
        +            return charge(source, (elements,))
        +
        +        def emit_container(value: Any) -> str:
        +            if id(value) in enclosing:
        +                raise ValueError(
        +                    f"Function global {name!r} contains itself and cannot be "
        +                    "captured. " + _CAPTURE_REMEDY
        +                )
        +            if len(enclosing) == _MAX_CAPTURED_DEPTH:
        +                raise ValueError(
        +                    f"Function global {name!r} nests containers more than "
        +                    f"{_MAX_CAPTURED_DEPTH} levels deep and cannot be captured. "
        +                    + _CAPTURE_REMEDY
        +                )
        +            enclosing.add(id(value))
        +            if type(value) is dict:
        +                entries = [(emit(key), emit(child)) for key, child in value.items()]
        +                children = [part for entry in entries for part in entry]
        +                listed = ", ".join(f"{key}: {child}" for key, child in entries)
        +                source = f"{{{listed}}}"
        +            else:
        +                children = [emit(child) for child in value]
        +                if type(value) in (set, frozenset):
        +                    listed = ", ".join(sorted(children))
        +                else:
        +                    listed = ", ".join(children)
        +                if type(value) is tuple:
        +                    source = f"({listed},)" if len(children) == 1 else f"({listed})"
        +                elif type(value) is list:
        +                    source = f"[{listed}]"
        +                elif type(value) is set:
        +                    source = (
        +                        f"{{{listed}}}" if children else f"{self._builtin('set')}()"
        +                    )
        +                else:
        +                    items = f"{{{listed}}}" if children else ""
        +                    source = f"{self._builtin('frozenset')}({items})"
        +            enclosing.remove(id(value))
        +            return charge(source, children)
        +
        +        return emit(value)
        +
        +    def _arrow_source(
        +        self, name: str, value: Union[pa.DataType, pa.Field, pa.Schema]
        +    ) -> str:
        +        if isinstance(value, pa.Schema):
        +            schema, suffix = value, ""
        +        elif isinstance(value, pa.Field):
        +            schema, suffix = pa.schema([value]), ".field(0)"
        +        else:
        +            schema, suffix = pa.schema([pa.field("", value)]), ".field(0).type"
        +        for data_type in schema.types:
        +            extension = _python_extension_type(data_type)
        +            if extension is not None:
        +                raise TypeError(
        +                    f"Function global {name!r} uses the Arrow extension type "
        +                    f"{extension.extension_name!r}, which is defined in Python and "
        +                    "cannot be captured. " + _CAPTURE_REMEDY
        +                )
        +        alias = self._support_module("pyarrow")
        +        # Schema IPC keeps nullability, metadata, and nested fields exactly.
        +        data = schema.serialize().to_pybytes()
        +        return f"{alias}.ipc.read_schema({alias}.py_buffer({data!r})){suffix}"
        +
        +    def _support_module(self, module: str) -> str:
        +        """The artifact's private alias for a module that rebuilds captured
        +        values."""
        +        alias = f"_lancedb_{module}"
        +        if alias not in self._support_imports:
        +            self._require_importable(module)
        +            self._claim(alias, ("support", module))
        +            self._support_imports[alias] = f"import {module} as {alias}"
        +        return alias
        +
        +    def _builtin(self, name: str) -> str:
        +        """A builtin called by captured source, which the artifact must not
        +        rebind."""
        +        self._claim(name, ("builtin", name))
        +        return name
         
             def _require_importable(self, module_name: str) -> None:
        -        """Warn about an import the Function's environment likely cannot
        -        satisfy: a module that lives in a local source tree, is not shipped
        -        with ``code=``, and names no declared package.
        +        """Warn about an import the Function's environment may not be able to
        +        satisfy.
        +
        +        An unresolved module warns only when the Function declares no package
        +        dependencies. A local source module warns unless ``code=`` ships it or
        +        a declared requirement matches its top-level name.
         
                 A warning rather than an error: a distribution name need not match
                 the module it installs, so a declared package can still provide the
        @@ -1826,12 +3217,23 @@ class _SourcePackager:
                 ):
                     return
                 locations = _module_locations_for_name(top)
        +        if not locations:
        +            if not self._requirements:
        +                self._warned_imports.add(top)
        +                warnings.warn(
        +                    f"@function source imports {top!r}, which is unavailable in the "
        +                    "client environment and has no declared pip/conda dependencies. "
        +                    "Remote availability cannot be verified; declare the required "
        +                    "package or confirm that the base image provides it.",
        +                    UserWarning,
        +                )
        +            return
                 roots = _installed_roots()
        -        if not locations or any(location.startswith(roots) for location in locations):
        +        if any(location.startswith(roots) for location in locations):
                     return
                 self._warned_imports.add(top)
                 warnings.warn(
        -            f"@udf source imports {module_name!r} from {locations[0]}, a local "
        +            f"@function source imports {module_name!r} from {locations[0]}, a local "
                     "module the Function's environment may not be able to import; ship "
                     f"it with code=[{top}] or declare the package that provides it in "
                     "pip/conda",
        @@ -1855,18 +3257,12 @@ class _SourcePackager:
                         self._require_importable(node.module)
         
         
        -def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]:
        -    """The Python source files of the modules and packages in ``code=``,
        -    keyed by their path on the Function's import path.
        -
        -    Package resources are not part of the source artifact. Warn about files
        -    and excluded directories that the walk leaves behind instead of silently
        -    producing a Function that will fail later on the worker.
        -    """
        -    import os
        -    from pathlib import Path
        -
        +def _code_files(
        +    modules: Sequence[Any],
        +) -> tuple[dict[str, str], dict[str, str], frozenset[str]]:
        +    """Source and byte-preserving package resources on the Function import path."""
             files: dict[str, str] = {}
        +    resources: dict[str, str] = {}
             names: set[str] = set()
             for module in modules:
                 if not isinstance(module, types.ModuleType):
        @@ -1900,35 +3296,50 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]
                     sources = []
                     skipped = set()
                     for directory, subdirectories, filenames in os.walk(root):
        -                # Only importable modules travel: data files, caches, and
        -                # directories that are not identifiers cannot be imported.
                         kept = []
                         for child in sorted(subdirectories):
        -                    if child == "__pycache__":
        +                    path = Path(directory) / child
        +                    if child == "__pycache__" or child.startswith("."):
                                 continue
        -                    if _SOURCE_PATH_COMPONENT.fullmatch(child):
        +                    if not path.is_symlink() and re.fullmatch(
        +                        r"[A-Za-z0-9_][A-Za-z0-9_.-]*", child
        +                    ):
                                 kept.append(child)
                             else:
        -                        relative = (Path(directory) / child).relative_to(root)
        +                        relative = path.relative_to(root)
                                 skipped.add(f"{name}/{relative.as_posix()}/")
                         subdirectories[:] = kept
                         for filename in sorted(filenames):
        +                    path = Path(directory) / filename
                             stem, suffix = os.path.splitext(filename)
        -                    if suffix in {".pyc", ".pyo"}:
        +                    if suffix in {".pyc", ".pyo"} or filename.startswith("."):
                                 continue
        -                    if suffix == ".py" and _SOURCE_PATH_COMPONENT.fullmatch(stem):
        -                        sources.append(Path(directory) / filename)
        +                    relative = path.relative_to(root)
        +                    key = f"{name}/{relative.as_posix()}"
        +                    if (
        +                        path.is_symlink()
        +                        or not path.is_file()
        +                        or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", filename)
        +                    ):
        +                        skipped.add(key)
        +                    elif suffix == ".py":
        +                        if all(
        +                            _SOURCE_PATH_COMPONENT.fullmatch(part)
        +                            for part in relative.with_suffix("").parts
        +                        ):
        +                            sources.append(path)
        +                        else:
        +                            skipped.add(key)
                             else:
        -                        relative = (Path(directory) / filename).relative_to(root)
        -                        skipped.add(f"{name}/{relative.as_posix()}")
        +                        resources[key] = base64.b64encode(path.read_bytes()).decode(
        +                            "ascii"
        +                        )
                     if skipped:
        -                skipped_paths = ", ".join(sorted(skipped))
                         warnings.warn(
        -                    f"code= ships Python .py modules only; package {name!r} "
        -                    f"will not include: {skipped_paths}. Install a package that "
        -                    "includes the required resources with pip= or conda=, and "
        -                    f"remove {name!r} from code= so the copied package cannot "
        -                    "shadow the installed distribution.",
        +                    "code= cannot ship these package paths: "
        +                    f"{', '.join(sorted(skipped))}. "
        +                    "Use regular files with safe relative names and importable "
        +                    "Python module names.",
                             UserWarning,
                         )
                     for path in sources:
        @@ -1939,12 +3350,12 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]
                     if not file or not file.endswith(".py"):
                         raise ValueError(f"code= ships Python source; module {name!r} has none")
                     files[f"{name}.py"] = _source_text(Path(file))
        -    return files, frozenset(names)
        +    return files, resources, frozenset(names)
         
         
         def _source_text(path) -> str:
             try:
        -        return path.read_text(encoding="utf-8")
        +        return path.read_bytes().decode("utf-8")
             except UnicodeDecodeError as error:
                 raise ValueError(f"code= ships UTF-8 source; {path} is not UTF-8") from error
         
        @@ -2037,6 +3448,7 @@ def _class_member(cls: type, name: str) -> Any:
         
         def _class_call(cls: type) -> Callable[..., Any]:
             call = _class_member(cls, "__call__")
        +    _validate_callable(call)
             if not inspect.isfunction(call) or inspect.iscoroutinefunction(call):
                 raise TypeError("a class Function must define a synchronous __call__ method")
             close = _class_member(cls, "close")
        @@ -2047,10 +3459,10 @@ def _class_call(cls: type) -> Callable[..., Any]:
             return call
         
         
        -class UdfDefinition:
        +class FunctionDefinition:
             """A Python callable prepared for remote Function registration.
         
        -    Instances are created with :func:`udf`. Calling an instance is ordinary
        +    Instances are created with :func:`function`. Calling an instance is ordinary
             local Python: a decorated function is called directly, while a decorated
             class is constructed using its initialization fields and the returned
             instance is called with each input. Reuse the instance and call its
        @@ -2058,12 +3470,20 @@ class UdfDefinition:
             remote application or build the declared remote runtime, and it does not
             need the private implementation attribute.
         
        +    Arguments to this call are Python and Arrow values. An
        +    [Expr][lancedb.expr.Expr] argument, such as ``col("value")``, is a column
        +    binding that only a registered
        +    [FunctionVersion][lancedb.functions.FunctionVersion] can carry, so this
        +    call rejects it with ``TypeError`` instead of running the callable.
        +
             Remote execution adapts the callable to the internal Arrow batch ABI
             described by the registration artifact. By default it invokes the callable
             once per row. A callable whose parameters are all annotated as
             ``pyarrow.Array`` receives whole Arrow arrays and returns a
             ``pyarrow.Array`` instead. This authoring choice is independent of the
        -    internal artifact adapter in the registration request.
        +    internal artifact adapter in the registration request. GPU Functions should
        +    use the Arrow form when the model supports batches: a scalar GPU callable is
        +    invoked once per row and leaves the model's own batching unavailable.
             """
         
             def __init__(
        @@ -2077,9 +3497,15 @@ class UdfDefinition:
                 env: Mapping[str, str],
                 python_version: Optional[str],
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
                 row_timeout_seconds: Optional[float] = None,
        -        gpu: bool = False,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        gpu: Optional[bool] = None,
                 gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
                 conda: tuple[str, ...] = (),
                 conda_channels: tuple[str, ...] = (),
                 apt: tuple[str, ...] = (),
        @@ -2091,19 +3517,18 @@ class UdfDefinition:
                 if not is_class and (
                     not inspect.isfunction(function) or inspect.iscoroutinefunction(function)
                 ):
        -            raise TypeError("@udf requires a synchronous Python function or a class")
        -        function_name = name or function.__name__
        -        if not _FUNCTION_NAME.fullmatch(function_name):
        -            raise ValueError(f"invalid Function name: {function_name!r}")
        +            _validate_callable(function)
        +            raise TypeError(
        +                "@function requires a synchronous Python function or a class"
        +            )
                 if pip and conda:
                     raise ValueError("a Function environment is pip or conda, not both")
                 if conda_channels and not conda:
                     raise ValueError("conda_channels requires conda packages")
        -        gpu_marker = _normalize_gpu_marker(gpu)
        -        if gpu_class is not None:
        -            _validate_gpu_class_name(gpu_class)
        -            if gpu_marker is None:
        -                raise ValueError("gpu_class requires gpu=True")
        +        _validate_package_requirements("conda" if conda else "pip", conda or pip)
        +        gpu_marker, gpu_class, gpus_per_worker = _normalize_gpu_request(
        +            gpu, gpu_class, gpu_count
        +        )
                 packages = tuple(sorted(set(conda if conda else pip)))
                 system_packages = tuple(sorted(set(apt)))
                 if any(
        @@ -2155,10 +3580,15 @@ class UdfDefinition:
                         "model Functions reserve environment variables "
                         f"{reserved!r}; the worker sets them for the private snapshot"
                     )
        +        if not is_class:
        +            _validate_callable(function)
        +        function_name = name or function.__name__
        +        if not _FUNCTION_NAME.fullmatch(function_name):
        +            raise ValueError(f"invalid Function name: {function_name!r}")
                 if is_class:
                     if "<" in function.__qualname__ or "." in function.__qualname__:
                         raise ValueError(
        -                    "@udf classes must be defined at module level; nested classes "
        +                    "@function classes must be defined at module level; nested classes "
                             "would capture their enclosing scope"
                         )
                     signature = _infer_signature(
        @@ -2177,14 +3607,29 @@ class UdfDefinition:
                     signature = signature._copy(update={"initialization": initialization})
                 else:
                     signature = _infer_signature(function, input_schema, output_schema)
        -        code_files, code_modules = _code_files(code)
        +        if gpu_marker is not None:
        +            call = _class_call(function) if is_class else function
        +            if not _is_vectorized_callable(call, method=is_class):
        +                warnings.warn(
        +                    f"GPU Function {function_name!r} uses a scalar callable, so each "
        +                    "row invokes it separately and its model batch is not inferred. "
        +                    "For GPU throughput, annotate every input as pyarrow.Array or "
        +                    "take one pyarrow.RecordBatch, provide input_schema and "
        +                    "output_schema, and batch inside that callable.",
        +                    UserWarning,
        +                    stacklevel=3,
        +                )
        +        code_files, code_resources, code_modules = _code_files(code)
                 entry_source = _SourcePackager(
                     code_modules, frozenset(_requirement_name(package) for package in packages)
                 ).package(function, signature)
                 if code_files:
                     kind = _PYTHON_BUNDLE_ARTIFACT
        +            bundle = {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}}
        +            if code_resources:
        +                bundle["resources"] = code_resources
                     source = json.dumps(
        -                {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}},
        +                bundle,
                         ensure_ascii=False,
                         sort_keys=True,
                         separators=(",", ":"),
        @@ -2201,6 +3646,7 @@ class UdfDefinition:
                     env=environment,
                     gpu=gpu_marker,
                     gpu_class=gpu_class,
        +            gpus_per_worker=gpus_per_worker,
                 )
                 self._function = function
                 self._request = FunctionRegistrationRequest(
        @@ -2221,7 +3667,12 @@ class UdfDefinition:
                     signature=signature,
                     runtime=runtime,
                     batch_size=batch_size,
        +            max_concurrency=max_concurrency,
        +            total_cpu_millis=total_cpu_millis,
        +            total_memory_bytes=total_memory_bytes,
        +            total_gpu_count=total_gpu_count,
                     row_timeout_seconds=row_timeout_seconds,
        +            retry_policy=retry_policy,
                     models=models,
                 )
                 # A class's own __dict__ holds its methods; copying it would shadow
        @@ -2300,16 +3751,26 @@ class UdfDefinition:
                 return self._request._copy(update={"secret_bindings": resolved})
         
             def __call__(self, *args, **kwargs):
        +        from lancedb.expr import Expr
        +
        +        if any(isinstance(value, Expr) for value in (*args, *kwargs.values())):
        +            raise TypeError(
        +                "a FunctionDefinition runs locally on Python and Arrow values; "
        +                "an Expr input binds only on a registered FunctionVersion. "
        +                "Register the definition with create_function or "
        +                "create_function_async, then bind col(...) on the returned "
        +                "version."
        +            )
                 return self._function(*args, **kwargs)
         
         
         @overload
        -def udf(function: Callable[..., Any]) -> UdfDefinition: ...
        +def function(target: Callable[..., Any]) -> FunctionDefinition: ...
         
         
         @overload
        -def udf(
        -    function: None = None,
        +def function(
        +    target: None = None,
             *,
             name: Optional[str] = None,
             input_schema: Optional[pa.Schema] = None,
        @@ -2318,20 +3779,26 @@ def udf(
             env: Optional[Mapping[str, str]] = None,
             python_version: Optional[str] = None,
             batch_size: Optional[int] = None,
        +    max_concurrency: Optional[int] = None,
             row_timeout_seconds: Optional[float] = None,
        -    gpu: bool = False,
        +    retry_policy: Optional[FunctionRetryPolicy] = None,
        +    gpu: Optional[bool] = None,
             gpu_class: Optional[str] = None,
        +    gpu_count: Optional[int] = None,
        +    total_cpu_millis: Optional[int] = None,
        +    total_memory_bytes: Optional[int] = None,
        +    total_gpu_count: Optional[int] = None,
             conda: tuple[str, ...] | list[str] = (),
             conda_channels: tuple[str, ...] | list[str] = (),
             apt: tuple[str, ...] | list[str] = (),
             image: Optional[str] = None,
             code: Sequence[types.ModuleType] = (),
             models: Sequence[HuggingFaceModel] = (),
        -) -> Callable[[Callable[..., Any]], UdfDefinition]: ...
        +) -> Callable[[Callable[..., Any]], FunctionDefinition]: ...
         
         
        -def udf(
        -    function: Optional[Callable[..., Any]] = None,
        +def function(
        +    target: Optional[Callable[..., Any]] = None,
             *,
             name: Optional[str] = None,
             input_schema: Optional[pa.Schema] = None,
        @@ -2340,9 +3807,15 @@ def udf(
             env: Optional[Mapping[str, str]] = None,
             python_version: Optional[str] = None,
             batch_size: Optional[int] = None,
        +    max_concurrency: Optional[int] = None,
             row_timeout_seconds: Optional[float] = None,
        -    gpu: bool = False,
        +    retry_policy: Optional[FunctionRetryPolicy] = None,
        +    gpu: Optional[bool] = None,
             gpu_class: Optional[str] = None,
        +    gpu_count: Optional[int] = None,
        +    total_cpu_millis: Optional[int] = None,
        +    total_memory_bytes: Optional[int] = None,
        +    total_gpu_count: Optional[int] = None,
             conda: tuple[str, ...] | list[str] = (),
             conda_channels: tuple[str, ...] | list[str] = (),
             apt: tuple[str, ...] | list[str] = (),
        @@ -2358,9 +3831,23 @@ def udf(
             ``None`` for a null value. PyArrow fields are nullable unless declared
             otherwise, so most columns need ``Optional``. For Arrow types annotations
             cannot express precisely, pass ``input_schema``, ``output_schema``, or
        -    both; the one omitted is inferred. Scalar outputs must be non-nullable.
        -    Every named-struct field may be nullable; Enterprise preserves the
        -    struct's validity when the result is expanded into sibling columns.
        +    both; the one omitted is inferred. A scalar output is non-nullable by
        +    default; annotate the return as ``Optional[T]`` or ``T | None``, or pass a
        +    nullable ``output_schema`` field, to declare a nullable scalar. The
        +    deployment must accept nullable scalar outputs; an older server rejects
        +    the registration. Every named-struct field may be nullable; Enterprise
        +    preserves the struct's validity when the result is expanded into sibling
        +    columns.
        +    ``dict[str, T]`` declares an Arrow map with a non-nullable utf8 key; the
        +    value is non-nullable for ``T`` and nullable for ``Optional[T]``. A bare
        +    ``Decimal`` has no precision or scale; use
        +    ``Annotated[Decimal, pyarrow.decimal128(precision, scale)]``,
        +    ``Annotated[Decimal, pyarrow.decimal256(precision, scale)]``, or an
        +    explicit schema. Bare ``datetime`` keeps its existing ``timestamp[us]`` default
        +    without a timezone; other units and timezones require
        +    ``Annotated[datetime, pyarrow.timestamp(unit, tz=...)]`` or an explicit
        +    schema. A bare ``timedelta`` has no unit and is rejected; use
        +    ``Annotated[timedelta, pyarrow.duration(unit)]`` or an explicit schema.
         
             **Large values.** A ``bytes`` parameter receives the whole value, which
             is held in memory with its row and counts against the server's per-row
        @@ -2372,7 +3859,12 @@ def udf(
             it takes one ``pyarrow.RecordBatch``. These batch annotations require both
             ``input_schema`` and ``output_schema`` explicitly: the annotations do not
             specify Arrow element types or fields. This also applies to a class's
        -    ``__call__`` method. A decorated class is the same callable with state:
        +    ``__call__`` method. Each ``input_schema`` field names one parameter, so
        +    several input columns take one ``pyarrow.Array`` parameter each, while a
        +    single ``pyarrow.RecordBatch`` parameter binds one input column and
        +    receives it as a batch. The
        +    [Function authoring guide](https://lancedb.com/docs/curation/create-function#batch)
        +    has the worked examples. A decorated class is the same callable with state:
             each remote instance calls ``__init__`` once, calls
             ``__call__`` for every row or batch of every input it processes, and calls
             ``close()``, if defined, once when it retires. Load models, open clients,
        @@ -2380,6 +3872,14 @@ def udf(
             reuses them. An instance serves many batches of one binding, so state is
             shared across them, but not across instances or workers.
         
        +    Functions and ``__call__`` methods must return a value. Generators,
        +    including async generators, are not supported; return a list to produce
        +    multiple values for a list output. Lambdas and decorated wrappers such as
        +    ``functools.lru_cache`` are not supported. Use a named ``def`` and keep
        +    caches inside the body or in a class instance initialized by ``__init__``.
        +    Callable input parameters cannot have defaults; move configurable values
        +    to class initialization fields instead.
        +
             **Initialization.** The annotated parameters of a class's ``__init__``
             are the Function's initialization fields. Their values belong to each
             binding, not to the Function: ``function(text=col("body"), model="small")``
        @@ -2396,8 +3896,11 @@ def udf(
             - modules, and classes and functions importable from an installed
               package, become imports; the package must be declared in ``pip`` or
               ``conda``;
        -    - literals (``None``, booleans, numbers, strings, bytes, tuples of them)
        -      are inlined;
        +    - values are copied into the source: ``None``, ``bool``, ``int``,
        +      ``str``, ``bytes``, and finite ``float``; tuples, lists, dicts, sets,
        +      and frozensets of supported values; PyArrow data types, fields, and
        +      schemas; and NumPy arrays and scalars of ``bool``, integer,
        +      ``float16``, ``float32``, and ``float64`` dtypes;
             - functions and classes defined in ``__main__``, such as notebook cells,
               are packaged by source, together with what they reference;
             - modules and packages listed in ``code`` are shipped as Python source and
        @@ -2406,28 +3909,68 @@ def udf(
         
             A module imported by the packaged source -- including a direct ``import``
             inside a function or method body -- draws a warning at registration when
        -    it resolves to local source outside ``code`` and no declared requirement
        -    matches the imported module name. The client cannot reliably validate
        -    imports provided only by the base image: ``pip``/``conda`` distribution
        -    names need not match the modules they install, and the client does not
        -    know the contents of a built or custom image. Declare every third-party
        -    import in ``pip`` or ``conda`` even when it happens to be installed on the
        -    registration host.
        -    Closures, lambdas, nested definitions, mutable module-level
        -    objects, code that reaches the module namespace another way
        -    (``globals()``/``eval``, ``sys.modules``, ``builtins``), and a
        -    non-standard ``__builtins__`` are rejected where they can be seen and
        -    otherwise unsupported. Changing any packaged source, including a module in
        -    ``code``, produces a new Function version; the environment built from
        -    ``pip`` or ``conda`` is reused.
        +    the client cannot resolve its top-level module and declares no package
        +    dependencies, or when it resolves to local source outside ``code`` and
        +    no declared requirement matches the imported module name. The warning
        +    does not assert that the remote environment lacks the module:
        +    ``pip``/``conda`` distribution names need not match the modules they
        +    install, and the client cannot inspect the contents of a base or custom
        +    image. Warnings follow normal Python warning filters and may be promoted
        +    to errors. Declare every third-party import in ``pip`` or ``conda`` even
        +    when it happens to be installed on the registration host.
        +    Closures, lambdas, nested definitions, other mutable module-level objects,
        +    and a non-standard ``__builtins__`` are rejected where they can be seen and
        +    otherwise unsupported.
        +
        +    **Captured values.** A captured value is copied when the decorator runs
        +    and rebuilt in every worker process. Later changes on the client do not
        +    reach the Function, changes a worker makes stay in that process, and
        +    globals that share an object on the client become separate copies.
        +    Dictionaries keep their insertion order and set elements are written in a
        +    canonical order, so the same values always package to the same source.
        +    Floats, including NumPy elements, must be finite. Arrow values are rebuilt
        +    from Arrow's IPC schema encoding, which preserves nullability, metadata,
        +    and nested fields; extension types defined in Python cannot be captured.
        +    NumPy values keep their dtype and shape and need ``numpy`` in the remote
        +    environment, so declare it in ``pip`` or ``conda``. Each captured value is
        +    limited to 1 MiB of source and 32 levels of nesting, and cannot contain
        +    itself. Load larger data inside the function or class body, for example
        +    from a table or a package resource shipped with ``code``. Define other
        +    values, such as instances of your own classes, inside the function or
        +    class body as well.
        +
        +    **Namespace restrictions.** The packaged source may use three static
        +    diagnostic operations: ``sys.stderr``, ``sys.version_info``, and
        +    ``importlib.metadata.version``. Direct imports, ``from`` imports, and
        +    aliases are treated the same way, whether the import appears inside the
        +    function or class body or at module level. Any other import of ``sys``,
        +    ``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``,
        +    including submodules such as ``ctypes.util``, ``importlib.resources``, and
        +    ``importlib.import_module``, is rejected. Referencing a module-level alias
        +    for an unapproved module or operation is also rejected. References to
        +    ``globals``, ``locals``, ``vars``, ``eval``, ``exec``, ``compile``, or
        +    ``__import__`` are rejected as dynamic namespace access. These
        +    restrictions are conservative: even ordinary uses such as
        +    ``ctypes.util.find_library`` or ``sys.version`` remain blocked because
        +    these modules can reach names outside the reconstructed Function
        +    namespace. Move such code into an importable helper module supplied with
        +    ``code=``, ``pip=``, or ``conda=``, then import and call the helper from
        +    the Function. Helpers imported normally keep their own module namespace;
        +    these checks do not scan their bodies. A helper defined in ``__main__`` is
        +    packaged by source and is subject to the same checks.
        +
        +    Changing any packaged source, including a module in ``code``, produces a
        +    new Function version; the environment built from ``pip`` or ``conda`` is
        +    reused.
         
             Parameters
             ----------
             function : function or class, optional
                 The synchronous callable, or the class whose instances are called. For
        -        a function, annotate every parameter as ``pyarrow.Array`` to opt into
        -        vectorized execution; a matching return annotation documents that the
        -        callable returns an Arrow array.
        +        a function, annotate every parameter as ``pyarrow.Array`` or a single
        +        parameter as ``pyarrow.RecordBatch`` to opt into vectorized execution.
        +        A vectorized Function using ``BlobWriter`` returns a row-aligned list
        +        or tuple of results.
             name : str, optional
                 The remote Function name. Defaults to the callable name.
                 Must start with an ASCII letter or underscore and contain only ASCII
        @@ -2437,13 +3980,22 @@ def udf(
                 Required for batch annotations. When omitted, inputs are inferred from
                 the parameter annotations.
             output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional
        -        Explicit scalar or named-struct output. Scalar outputs must be
        -        non-nullable. Required for batch annotations. When omitted, the output
        -        is inferred from the return annotation.
        +        Explicit scalar or named-struct output. A scalar field's ``nullable``
        +        flag is preserved; a top-level named-struct field and a Blob v2 output
        +        must be non-nullable. Map and decimal fields use canonical Arrow JSON;
        +        a map key must be non-nullable utf8 and its value field keeps the
        +        declared nullability. Temporal fields use canonical Arrow JSON; the
        +        microsecond/no-timezone case keeps the legacy timestamp/duration shape.
        +        Required for batch annotations unless the return annotation declares
        +        a row-aligned sequence of ``BlobWriter`` results. When omitted, the
        +        output is inferred from the return annotation.
             pip : sequence of str, optional
        -        Pip requirements for the remote environment.
        +        Pip requirements for the remote environment. Syntax is validated at
        +        decoration time, including extras and environment markers. Named direct
        +        references and bare package or git URLs are supported.
             conda : sequence of str, optional
        -        Conda packages for the remote environment, instead of ``pip``.
        +        Conda packages for the remote environment, instead of ``pip``. MatchSpec
        +        syntax is validated at decoration time, including channels and builds.
             conda_channels : sequence of str, optional
                 Conda channels in priority order; requires ``conda``.
             apt : sequence of str, optional
        @@ -2467,29 +4019,56 @@ def udf(
                 Maximum number of input rows supplied in one execution batch. Must be
                 between 1 and 4294967295. Remote execution may use smaller batches.
                 When omitted, the service chooses the batch size adaptively.
        +    max_concurrency : int, optional
        +        Maximum user-code calls in flight for one Function within one logical
        +        execution. Must be between 1 and 4294967295. A refresh can override
        +        this default for that execution only. Omitting it preserves the
        +        existing behavior. This is not an account-wide quota.
             row_timeout_seconds : float, optional
                 Positive, finite deadline in seconds for each Python call: one row for
                 scalar Functions and one batch for vectorized Functions. This does not
                 govern class initialization. When omitted, the service applies its
        -        default per-call budget.
        -    gpu : bool, default False
        -        Whether every remote execution requires a GPU. The execution platform
        -        selects one compatible GPU for each worker. The requirement is part of
        -        the immutable Function version.
        +        default per-call budget, currently 300 seconds on Enterprise builds.
        +        Set it for a GPU Function whose longest call can exceed that budget.
        +        Enterprise builds that require an explicit GPU deadline reject a
        +        refresh when neither the definition nor the refresh request sets one;
        +        a refresh value overrides the definition.
        +    retry_policy : FunctionRetryPolicy, optional
        +        Retry selected failed calls inside the Function, with bounded attempts
        +        and backoff. A refresh may override this default. Retrying a partial
        +        call must be safe; completed calls are not repeated. For batch Functions,
        +        skip after exhaustion applies to the whole failed call.
        +    gpu : bool, optional
        +        Enable GPU execution. Defaults to CPU execution.
             gpu_class : str, optional
        -        Operator-defined GPU class for every execution of this Function, such
        -        as ``"a10g"`` or ``"h100"``. Requires ``gpu=True`` and follows the
        -        lowercase 63-character DNS-label rule. The class is part of the
        -        immutable Function version; per-refresh aggregate GPU budgets are
        -        selected through ``refresh_column`` instead of registration.
        +        Select an operator-configured GPU pool, such as ``"h100"``.
        +        Requires ``gpu=True``. Omitting it is equivalent to ``"any"`` and accepts
        +        any eligible configured GPU class. Use ``"default"`` to select the
        +        deployment's default pool explicitly.
        +    gpu_count : int, optional
        +        Default GPUs allocated together to each Function worker. Requires ``gpu=True``
        +        and defaults to one. Column/MV creation and refresh can override it.
        +        Must be a positive integer. Refresh
        +        ``total_gpu_count`` limits the total GPUs across the worker fleet.
        +    total_cpu_millis : int, optional
        +        Default total CPU budget for an execution, in millicores (1000 = one
        +        core). A column/MV declaration or refresh may override this value.
        +    total_memory_bytes : int, optional
        +        Default total memory budget for an execution, in bytes.
        +    total_gpu_count : int, optional
        +        Default total GPU budget across an execution's workers. This is
        +        separate from ``gpu_count``, which allocates GPUs to each worker.
        +        MVs add the defaults of their distinct pinned Function versions.
             code : sequence of module, optional
        -        Top-level modules or packages whose importable ``.py`` files ship
        -        with the Function and are importable by their own names. Package data
        -        files are not copied. To use a package that includes required data
        -        resources, install it with ``pip=`` or ``conda=`` and remove that
        -        package from ``code=`` so the copied Python package cannot shadow the
        -        installed distribution. ``@udf`` warns when it skips files from a
        -        package in ``code=``.
        +        Top-level modules or packages shipped with the Function and importable
        +        by their own names. Package resources, including binary data and
        +        vendored subpackages, retain their relative paths and exact bytes.
        +        Source and resource changes both create a new Function version.
        +        Caches and hidden paths are excluded. Symlinks and unsafe paths are
        +        skipped with a warning. Compiled dependencies must match the remote
        +        runtime; use ``pip=`` or ``conda=`` for platform-specific distributions
        +        and ``models=`` for large model snapshots. Resource bundles require
        +        server support for the ``python_bundle.resources`` field.
             models : sequence of HuggingFaceModel, optional
                 Immutable Hugging Face repository snapshots prepared in the worker
                 node cache before user code starts. A Function may declare a
        @@ -2500,7 +4079,7 @@ def udf(
         
             Returns
             -------
        -    UdfDefinition
        +    FunctionDefinition
                 A callable definition accepted by
                 :meth:`lancedb.db.DBConnection.create_function`,
                 :meth:`lancedb.db.AsyncConnection.create_function_async` and
        @@ -2508,14 +4087,14 @@ def udf(
         
             Examples
             --------
        -    >>> from lancedb import udf
        -    >>> @udf(pip=["numpy==2.2.0"])
        +    >>> from lancedb import function
        +    >>> @function(pip=["numpy==2.2.0"])
             ... def score(value: float) -> float:
             ...     return value * 2
             >>> score(1.5)
             3.0
             >>> import pyarrow as pa
        -    >>> @udf(
        +    >>> @function(
             ...     input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
             ...     output_schema=pa.int64(),
             ... )
        @@ -2523,14 +4102,14 @@ def udf(
             ...     return value
             >>> batch_identity(pa.array([1, 2, 3])).to_pylist()
             [1, 2, 3]
        -    >>> @udf(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
        +    >>> @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g", gpu_count=2)
             ... def gpu_score(value: int) -> int:
             ...     return value * 2
             >>> gpu_score.registration_request.runtime.gpu
             True
        -    >>> gpu_score.registration_request.runtime.gpu_class
        -    'a10g'
        -    >>> @udf
        +    >>> gpu_score.registration_request.runtime.gpus_per_worker
        +    2
        +    >>> @function
             ... class scale:
             ...     def __init__(self, factor: float, offset: float = 0.0):
             ...         self.factor, self.offset = factor, offset
        @@ -2547,7 +4126,7 @@ def udf(
             >>> [field.name for field in scale.registration_request.signature.initialization]
             ['factor', 'offset']
             >>> import lancedb
        -    >>> @udf(
        +    >>> @function(
             ...     input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
             ...     output_schema=lancedb.blob("copy", nullable=False),
             ... )
        @@ -2564,7 +4143,10 @@ def udf(
             remote environment, resolve Secrets, or run the remote Arrow adapter or
             sandbox. A registered ``FunctionVersion`` call is different: it binds
             ``col(...)`` inputs and returns a remote
        -    [FunctionApplication][lancedb.functions.FunctionApplication].
        +    [FunctionApplication][lancedb.functions.FunctionApplication]. Passing an
        +    [Expr][lancedb.expr.Expr] to a definition raises ``TypeError`` before the
        +    callable runs, because a column reference binds only on a registered
        +    version.
         
             ```python
             scaled = scale(factor=2.0)
        @@ -2580,6 +4162,14 @@ def udf(
             declared nullability. Use :func:`lancedb.blob` in the explicit schemas;
             plain ``pyarrow.large_binary()`` does not carry Blob v2 semantics.
         
        +    For a streaming Blob v2 result, annotate a scalar return with
        +    [``BlobWriter``][lancedb.functions.BlobWriter], or annotate a vectorized
        +    return with ``list[BlobWriter]`` or ``tuple[BlobWriter, ...]``. To declare a
        +    writer in a named or nested output, use ``BlobWriter.field(...)`` in the
        +    explicit output schema. Writer-capable Functions run during computed
        +    column refresh. Plain SQL ``SELECT`` continues to support byte-returning
        +    Functions under its Arrow output limits.
        +
             A Blob v2 field may sit at the top level or inside a struct in inputs and
             outputs. Only outputs may nest it in a list or large list (for example
             ``pa.list_(lancedb.blob("item"))``, returned as a list of ``bytes``);
        @@ -2588,8 +4178,8 @@ def udf(
             ``blob_mode="bytes"`` cannot fetch payloads inside lists.
             """
         
        -    def decorate(target: Any) -> UdfDefinition:
        -        return UdfDefinition(
        +    def decorate(target: Any) -> FunctionDefinition:
        +        return FunctionDefinition(
                     target,
                     name=name,
                     input_schema=input_schema,
        @@ -2598,9 +4188,15 @@ def udf(
                     env={} if env is None else env,
                     python_version=python_version,
                     batch_size=batch_size,
        +            max_concurrency=max_concurrency,
                     row_timeout_seconds=row_timeout_seconds,
        +            retry_policy=retry_policy,
                     gpu=gpu,
                     gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +            total_cpu_millis=total_cpu_millis,
        +            total_memory_bytes=total_memory_bytes,
        +            total_gpu_count=total_gpu_count,
                     conda=tuple(conda),
                     conda_channels=tuple(conda_channels),
                     apt=tuple(apt),
        @@ -2609,22 +4205,25 @@ def udf(
                     models=tuple(models),
                 )
         
        -    if function is None:
        +    if target is None:
                 return decorate
        -    return decorate(function)
        +    return decorate(target)
         
         
         __all__ = [
             "AssignmentMapping",
             "ApplicationInput",
        +    "BlobWriter",
             "FunctionApplication",
             "FunctionArtifact",
             "FunctionArtifactContent",
             "FunctionArtifactRequest",
             "FunctionBinding",
        +    "FunctionEnvironment",
             "FunctionOutput",
             "FunctionParameter",
             "FunctionRegistrationRequest",
        +    "FunctionRetryPolicy",
             "FunctionResultField",
             "FunctionSignature",
             "FunctionImage",
        @@ -2632,11 +4231,52 @@ __all__ = [
             "FunctionVersionRef",
             "HuggingFaceModel",
             "InputBinding",
        +    "LiteralInputBinding",
             "OutputMapping",
             "PythonEnvironmentSpec",
             "PythonAdapterSpec",
        +    "PythonEnvironmentBuild",
             "PythonRuntimeSpec",
        +    "RequestedPythonEnvironment",
        +    "RequestedPythonRuntime",
        +    "ResolvedEnvironment",
        +    "ResolvedEnvironmentProvenance",
        +    "ResolvedPackage",
             "RefreshColumnResult",
        -    "UdfDefinition",
        -    "udf",
        +    "FunctionErrors",
        +    "AsyncFunctionErrors",
        +    "FunctionErrorGroup",
        +    "FunctionProvenance",
        +    "FunctionValueProvenance",
        +    "FunctionDefinition",
         ]
        +
        +
        +def udf(*args: Any, **kwargs: Any) -> Any:
        +    """Deprecated alias of :func:`function`.
        +
        +    Accepts the same options, including ``row_timeout_seconds``. See
        +    :func:`function` for GPU deadline guidance.
        +    """
        +    warnings.warn(
        +        "lancedb.udf is deprecated; use lancedb.function",
        +        DeprecationWarning,
        +        stacklevel=2,
        +    )
        +    return function(*args, **kwargs)
        +
        +
        +UDF_DEFINITION_DEPRECATION = (
        +    "lancedb.UdfDefinition is deprecated; use lancedb.FunctionDefinition"
        +)
        +
        +
        +def __getattr__(name: str) -> Any:
        +    if name == "UdfDefinition":
        +        warnings.warn(UDF_DEFINITION_DEPRECATION, DeprecationWarning, stacklevel=2)
        +        return FunctionDefinition
        +    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
        +
        +
        +if TYPE_CHECKING:
        +    UdfDefinition = FunctionDefinition
        diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py
        index 9f53f203b..2b5dd8ff2 100644
        --- a/python/python/lancedb/index.py
        +++ b/python/python/lancedb/index.py
        @@ -2,7 +2,8 @@
         # SPDX-FileCopyrightText: Copyright The LanceDB Authors
         
         from dataclasses import dataclass
        -from typing import List, Literal, Optional
        +import json
        +from typing import Any, Dict, List, Literal, Optional, Union
         
         from ._lancedb import (
             IndexConfig,
        @@ -130,6 +131,140 @@ class NGram:
             pass
         
         
        +@dataclass
        +class ZoneMap:
        +    """Describe a ZoneMap index configuration.
        +
        +    A `ZoneMap` index stores compact min and max summaries for contiguous
        +    ranges (zones) of rows. During a scan it skips any zone whose summary
        +    cannot satisfy the predicate, so it accelerates range and equality
        +    filters such as `col > 10`, `col BETWEEN a AND b`, and `col = x`,
        +    without changing the results.
        +
        +    It suits large numeric or temporal columns whose values are correlated
        +    with row order (for example `timestamp`, `price`, `id`).
        +    """
        +
        +    pass
        +
        +
        +@dataclass
        +class RTree:
        +    """Describe an RTree index configuration.
        +
        +    `RTree` is a scalar index on a GeoArrow geometry column, that is, a column
        +    whose Arrow field metadata sets ``ARROW:extension:name`` to a GeoArrow type
        +    such as ``geoarrow.point``, ``geoarrow.polygon`` or ``geoarrow.wkb``. It
        +    stores the bounding box of each geometry and accelerates spatial filters
        +    passed to ``where()``.
        +
        +    The index accelerates ``ST_Intersects``, ``ST_Contains``, ``ST_Within``,
        +    ``ST_Touches``, ``ST_Crosses``, ``ST_Overlaps``, ``ST_Covers`` and
        +    ``ST_CoveredBy`` between the indexed column and a constant geometry, in
        +    either argument order, for example
        +    ``ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))``, as well as
        +    ``geom IS NULL``. These filters can be combined with other conditions
        +    using ``AND``.
        +
        +    See the R-tree section of 
        +    for storing geometry, the other spatial functions, and spatial filters on
        +    vector search.
        +
        +    Remote tables send the ``RTREE`` index type to the server, which must
        +    support it.
        +
        +    Examples
        +    --------
        +    >>> config = RTree(page_size=1024)
        +
        +    Attributes
        +    ----------
        +    page_size : int, optional
        +        The maximum number of entries in each R-tree page. Must be at least 2.
        +        ``None`` uses Lance's default of 4096.
        +    """
        +
        +    page_size: Optional[int] = None
        +
        +
        +@dataclass
        +class ScalarPlugin:
        +    """Configure a scalar index of a type recognized by a registered database plugin.
        +
        +    Use this for index types without a dedicated configuration class.
        +    Prefer a dedicated class, such as [BTree][lancedb.index.BTree], when one
        +    is available.
        +
        +    An unknown plugin name or invalid parameters cause index creation to fail.
        +
        +    Examples
        +    --------
        +    >>> from lancedb.index import ScalarPlugin
        +    >>> ScalarPlugin("bloomfilter", params={"number_of_items": 4096})
        +    ScalarPlugin(index_type='bloomfilter', params={'number_of_items': 4096})
        +
        +    Pass it as ``config`` to ``create_index``:
        +
        +    >>> table.create_index(  # doctest: +SKIP
        +    ...     "id",
        +    ...     config=ScalarPlugin("bloomfilter", '{"probability": 0.01}'),
        +    ... )
        +
        +    Attributes
        +    ----------
        +    index_type: str
        +        The index type, case-insensitive. Surrounding whitespace is ignored.
        +        Must not be empty.
        +    params: dict or str, optional
        +        The index parameters, as a dict or as a string holding a JSON object.
        +        They are passed as given. Each plugin defines its parameters and
        +        defaults; refer to the plugin's documentation for guidance.
        +
        +    Raises
        +    ------
        +    ValueError
        +        If ``index_type`` is empty, or ``params`` is a string that is not a
        +        JSON object.
        +    TypeError
        +        If ``index_type`` is not a string, or ``params`` is not a dict, a
        +        string or None.
        +    """
        +
        +    index_type: str
        +    params: Optional[Union[Dict[str, Any], str]] = None
        +
        +    def __post_init__(self):
        +        if not isinstance(self.index_type, str):
        +            raise TypeError(
        +                "ScalarPlugin index_type must be a str, got "
        +                + type(self.index_type).__name__
        +            )
        +        if not self.index_type.strip():
        +            raise ValueError("ScalarPlugin index_type must not be empty")
        +        if isinstance(self.params, str):
        +            try:
        +                parsed = json.loads(self.params)
        +            except json.JSONDecodeError as e:
        +                raise ValueError(f"ScalarPlugin params are not valid JSON: {e}") from e
        +            if not isinstance(parsed, dict):
        +                raise ValueError(
        +                    "ScalarPlugin params must be a JSON object, got "
        +                    + type(parsed).__name__
        +                )
        +        elif self.params is not None and not isinstance(self.params, dict):
        +            raise TypeError(
        +                "ScalarPlugin params must be a dict, a JSON string or None, got "
        +                + type(self.params).__name__
        +            )
        +
        +    @property
        +    def _params_json(self) -> Optional[str]:
        +        # Read by the native layer, which checks again that this is an object.
        +        if self.params is None or isinstance(self.params, str):
        +            return self.params
        +        return json.dumps(self.params)
        +
        +
         @dataclass
         class FTS:
             """Describe a FTS index configuration.
        @@ -984,4 +1119,6 @@ __all__ = [
             "LabelList",
             "Fm",
             "NGram",
        +    "RTree",
        +    "ScalarPlugin",
         ]
        diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py
        index 92b545ce7..778d44e2b 100644
        --- a/python/python/lancedb/job.py
        +++ b/python/python/lancedb/job.py
        @@ -5,9 +5,25 @@
         
         import asyncio
         import json
        +import logging
        +import reprlib
         import time
        +from contextlib import suppress
         from datetime import timedelta
        -from typing import Any, Callable, Generic, Optional, TypeVar, cast
        +from enum import Enum
        +from os import PathLike
        +from pathlib import Path
        +from typing import (
        +    Any,
        +    AsyncIterator,
        +    Callable,
        +    Generic,
        +    Iterator,
        +    Optional,
        +    TypeVar,
        +    cast,
        +)
        +from uuid import uuid4
         
         import pyarrow as pa
         
        @@ -15,6 +31,11 @@ from lancedb.background_loop import LOOP
         
         from . import _lancedb
         from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
        +from .functions import RefreshColumnResult
        +from .compaction import CompactionResult
        +from .cleanup import CleanupResult
        +from .prewarm import PrewarmDataResult
        +from .profiling import FunctionProfile, FunctionProfileKind, FunctionProfileStatus
         from .remote.errors import HttpError, RetryError
         
         T = TypeVar("T")
        @@ -25,9 +46,60 @@ __all__ = [
             "JobDescription",
             "JobFailureInfo",
             "JobInfo",
        +    "JobState",
        +    "FunctionProfile",
        +    "FunctionProfileKind",
        +    "FunctionProfileStatus",
         ]
         
         
        +class JobState(str, Enum):
        +    """Detailed lifecycle of one attempt, retaining unknown future values."""
        +
        +    CREATED = "created"
        +    QUEUED = "queued"
        +    IN_PROGRESS = "in_progress"
        +    SUCCEEDED = "succeeded"
        +    FAILED = "failed"
        +    CANCELED = "canceled"
        +    TIMED_OUT = "timed_out"
        +
        +    @classmethod
        +    def _missing_(cls, value):
        +        if not isinstance(value, str):
        +            return None
        +        aliases = {
        +            "running": cls.IN_PROGRESS,
        +            "finished": cls.SUCCEEDED,
        +            "cancelled": cls.CANCELED,
        +        }
        +        if value in aliases:
        +            return aliases[value]
        +        member = str.__new__(cls, value)
        +        member._name_ = None
        +        member._value_ = value
        +        return member
        +
        +    @property
        +    def is_terminal(self) -> bool:
        +        return self in (self.SUCCEEDED, self.FAILED, self.CANCELED, self.TIMED_OUT)
        +
        +    @property
        +    def is_success(self) -> bool:
        +        return self == self.SUCCEEDED
        +
        +    def __str__(self) -> str:
        +        return self.value
        +
        +
        +def _profile_seconds(value: Optional[timedelta], name: str) -> Optional[float]:
        +    if value is None:
        +        return None
        +    if not isinstance(value, timedelta):
        +        raise TypeError(f"{name} must be a datetime.timedelta")
        +    return value.total_seconds()
        +
        +
         def _timeout_message(
             job_id: Optional[str], timeout: timedelta, job_type: Optional[str]
         ) -> str:
        @@ -36,7 +108,7 @@ def _timeout_message(
             if job_id is None:
                 return (
                     f"operation still running after {seconds} {unit}; "
        -            "it continues on the server"
        +            "keep this handle to continue waiting"
                 )
             if job_type == "query":
                 return (
        @@ -50,11 +122,13 @@ def _timeout_message(
             )
         
         
        -def _normalize_job_progress(progress):
        +def _normalize_job_progress(progress, *, query=False):
             """Normalize ``wait(progress=...)`` using the same convention as writes."""
             if progress is True:
                 from tqdm.auto import tqdm
         
        +        if query:
        +            return tqdm(bar_format="Query{postfix} [{elapsed}]"), True
                 return tqdm(unit=" rows"), True
             if progress is False or progress is None:
                 return None, False
        @@ -62,6 +136,7 @@ def _normalize_job_progress(progress):
         
         
         _ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000
        +_QUERY_PROGRESS_INTERVAL_SECONDS = 1.0
         
         
         def _progress_eta(previous, current):
        @@ -139,6 +214,19 @@ def _job_progress_callback(progress, enrich):
                 planned = snapshot.get("rows_planned")
                 remaining = snapshot.get("rows_remaining")
                 computed = snapshot.get("rows_computed")
        +        job_type = snapshot.get("job_type")
        +        maintenance = job_type in ("compact", "prewarm_page_cache")
        +        if job_type == "compact":
        +            computed = snapshot.get("rows_rewritten")
        +            remaining = None
        +            if hasattr(progress, "unit"):
        +                progress.unit = " rows"
        +        elif job_type == "prewarm_page_cache":
        +            planned = snapshot.get("executors_targeted")
        +            computed = snapshot.get("executors_completed")
        +            remaining = None
        +            if hasattr(progress, "unit"):
        +                progress.unit = " executors"
                 if isinstance(planned, int):
                     epoch = snapshot.get("execution_epoch")
                     reset = (isinstance(last_planned, int) and planned < last_planned) or (
        @@ -164,7 +252,7 @@ def _job_progress_callback(progress, enrich):
                 if completed is not None:
                     if isinstance(planned, int):
                         completed = min(completed, planned)
        -            if first_snapshot and completed < last_rows:
        +            if (first_snapshot or maintenance) and completed < last_rows:
                         # The server may have started a new execution while a
                         # caller-owned bar retained its old position.
                         last_rows = completed
        @@ -190,6 +278,11 @@ class AsyncJob(Generic[T]):
             The operation may already be complete when the handle is created. ``T``
             is the endpoint's terminal result type; unit-result jobs resolve to
             ``None``.
        +
        +    Methods such as ``state()``, ``result()``, ``failure()`` and ``spec()`` read
        +    cached values without contacting the backend, including on async handles. Use
        +    ``await job.checkout_latest()`` to refresh the cached state and registry
        +    details together. ``events()`` makes a separate request for event history.
             """
         
             def __init__(
        @@ -200,26 +293,32 @@ class AsyncJob(Generic[T]):
                 self._inner = inner
                 self._result_decoder = result_decoder
                 self._last_progress_snapshot = None
        +        self._created_at = time.monotonic()
        +        self._local_job_id = str(uuid4()) if inner is None else None
         
             def _enrich_progress(self, snapshot):
                 enriched = _with_progress_eta(self._last_progress_snapshot, snapshot)
                 self._last_progress_snapshot = enriched
                 return enriched
         
        -    @property
             def id(self) -> Optional[str]:
        -        """The operation's opaque ID, interpreted according to :attr:`job_type`.
        +        """Return the operation's opaque ID, interpreted according to ``job_type()``.
         
                 Registry jobs expose a registry job ID; SQL-backed jobs expose a
                 connection-scoped query ID as a string. Local operations return ``None``.
                 Query IDs cannot be used with registry job APIs or to resume after a
                 client restart.
                 """
        +        return self._id
        +
        +    @property
        +    def _id(self) -> Optional[str]:
                 return self._inner.id if self._inner is not None else None
         
             async def status(self) -> str:
        -        """The operation's current lifecycle state: "running", "finished",
        -        "failed", or "cancelled".
        +        """Return the current status, usually "running", "finished", "failed",
        +        or "cancelled". A Function refresh waiting for execution workers reports
        +        "waiting_for_capacity".
         
                 A point snapshot; unlike `wait` it does not block or raise on a
                 terminal failure state. States a newer server reports that this
        @@ -229,20 +328,79 @@ class AsyncJob(Generic[T]):
                     return "finished"
                 return await self._inner.status()
         
        +    def job_id(self) -> Optional[str]:
        +        """Identity of the selected attempt last observed by this handle.
        +
        +        For operation handles, ``refresh()`` or ``status()`` can select a
        +        different attempt while ``id()`` stays unchanged. Save this value after
        +        refreshing and use it throughout paged diagnostics. Embedded IDs cannot
        +        be reopened on a server.
        +        """
        +        return (
        +            getattr(self._inner, "job_id", self.id())
        +            if self._inner is not None
        +            else self._local_job_id
        +        )
        +
        +    def operation_id(self) -> Optional[str]:
        +        """Root of the explicit retry lineage, when known."""
        +        return (
        +            getattr(self._inner, "operation_id", None)
        +            if self._inner is not None
        +            else self._local_job_id
        +        )
        +
        +    def attempt(self) -> Optional[int]:
        +        """One-based attempt ordinal; worker replacement does not increment it."""
        +        return getattr(self._inner, "attempt", None) if self._inner is not None else 1
        +
        +    def retry_of(self) -> Optional[str]:
        +        """Immediate predecessor attempt, when supplied by the backend."""
        +        return getattr(self._inner, "retry_of", None)
        +
        +    def lifecycle_state(self) -> Optional[JobState]:
        +        """Detailed state last observed; unknown values never imply success."""
        +        raw = getattr(self._inner, "lifecycle_state", None) or self.state()
        +        return JobState(raw) if raw is not None else None
        +
        +    async def status_typed(self) -> JobState:
        +        """Refresh and return the detailed, forward-compatible lifecycle state."""
        +        state = await self.status()
        +        return self.lifecycle_state() or JobState(state)
        +
        +    def source_table_version(self) -> Optional[int]:
        +        """Source snapshot pinned for this attempt, when reported."""
        +        return getattr(self._inner, "source_table_version", None)
        +
        +    def execution_epoch(self) -> Optional[int]:
        +        """Most recent execution's fencing token, when reported."""
        +        return getattr(self._inner, "execution_epoch", None)
        +
             async def progress(self) -> Optional[dict[str, Any]]:
                 """Fetch a structured progress snapshot.
         
        -        Registry jobs always report lifecycle fields. Queue metadata and
        -        counters are included when supplied by the server. Older servers may
        +        Registry jobs always report lifecycle fields. SQL query handles report
        +        lifecycle state and ``client_elapsed_time_millis``, measured since this
        +        handle was created. They do not expose server build phases or logs.
        +        Queue metadata and counters are included when supplied by the server.
        +        Older servers may
                 omit counters, and in-process operations return ``None``. A missing
        -        counter is unknown rather than zero. This is additive to :meth:`status`,
        -        whose string contract is unchanged.
        +        counter is unknown rather than zero.
                 """
                 if self._inner is None:
                     return None
        -        await self._inner.status()
        +        state = await self._inner.status()
                 description = getattr(self._inner, "_description", None)
                 if description is None or description.progress is None:
        +            if self.job_type() == "query":
        +                return {
        +                    "job_id": self.id(),
        +                    "job_type": "query",
        +                    "state": state,
        +                    "client_elapsed_time_millis": int(
        +                        (time.monotonic() - self._created_at) * 1_000
        +                    ),
        +                }
                     return None
                 return self._enrich_progress(description.progress)
         
        @@ -265,8 +423,19 @@ class AsyncJob(Generic[T]):
                 a caller-owned bar with the server's current completed rows and total;
                 later observations in a stable execution epoch use a high-water mark. A
                 new execution epoch or smaller plan resets the bar to that plan.
        +        Maintenance jobs display reported rewritten rows or completed executors;
        +        revised maintenance counters replace earlier retry observations. Totals
        +        remain unknown until the server reports them. Rewritten rows describe
        +        execution work, not committed compaction results.
                 ``False`` preserves the original wait behavior.
         
        +        For SQL-backed Function registration, progress shows the query's
        +        lifecycle state and client elapsed time. It observes the existing
        +        query handle while its original waiter runs; it does not resubmit or
        +        cancel the registration. Detailed bake phases and build logs are not
        +        available from the current query handle. Failure exceptions retain the
        +        server's cause and request identifiers.
        +
                 Raises `JobFailedError` if the operation failed, `JobCancelledError`
                 if it was cancelled, and `TimeoutError` if `timeout` elapses first.
                 Transient connection and read errors are retried with capped exponential
        @@ -282,7 +451,12 @@ class AsyncJob(Generic[T]):
                 """
                 if self._inner is None:
                     return cast(T, None)
        -        progress_obj, owns = _normalize_job_progress(progress)
        +        query_progress = (
        +            progress is not False
        +            and progress is not None
        +            and self.job_type() == "query"
        +        )
        +        progress_obj, owns = _normalize_job_progress(progress, query=query_progress)
                 progress_callback = _job_progress_callback(progress_obj, self._enrich_progress)
                 last_error = None
         
        @@ -308,28 +482,61 @@ class AsyncJob(Generic[T]):
                         await asyncio.sleep(delay)
                         delay = min(delay * 2, 30.0)
         
        +        async def observe_query():
        +            async def report():
        +                try:
        +                    snapshot = await self.progress()
        +                    if snapshot is not None:
        +                        progress_callback(snapshot)
        +                except Exception:
        +                    logging.getLogger(__name__).warning(
        +                        "job progress observer failed", exc_info=True
        +                    )
        +
        +            waiter = asyncio.create_task(wait_with_retries())
        +            try:
        +                while not waiter.done():
        +                    await report()
        +                    await asyncio.wait(
        +                        {waiter}, timeout=_QUERY_PROGRESS_INTERVAL_SECONDS
        +                    )
        +                try:
        +                    return await waiter
        +                finally:
        +                    await report()
        +            finally:
        +                if not waiter.done():
        +                    waiter.cancel()
        +                    with suppress(asyncio.CancelledError):
        +                        await waiter
        +
        +        wait_for_result = (
        +            observe_query
        +            if query_progress and progress_callback is not None
        +            else wait_with_retries
        +        )
                 try:
                     try:
                         if timeout is None:
        -                    result = await wait_with_retries()
        +                    result = await wait_for_result()
                         else:
                             result = await asyncio.wait_for(
        -                        wait_with_retries(), timeout.total_seconds()
        +                        wait_for_result(), timeout.total_seconds()
                             )
                     except asyncio.TimeoutError as error:
                         if last_error is None:
                             if timeout is None:
                                 raise
                             raise TimeoutError(
        -                        _timeout_message(self.id, timeout, self.job_type)
        +                        _timeout_message(self.id(), timeout, self.job_type())
                             ) from error
                         identity = (
        -                    f"job {self.id!r}" if self.id is not None else "the operation"
        +                    f"job {self.id()!r}" if self.id() is not None else "the operation"
                         )
        -                if self.id is not None and self.job_type != "query":
        +                if self.id() is not None and self.job_type() != "query":
                             reconnect = (
        -                        f"Use db.open_job({self.id!r}) to reconnect, then call wait() "
        -                        "on the returned job."
        +                        f"Use db.open_job({self.id()!r}) to reconnect, "
        +                        "then call wait() on the returned job."
                             )
                         else:
                             reconnect = "Call wait() on this job handle to reconnect."
        @@ -351,9 +558,21 @@ class AsyncJob(Generic[T]):
                     return
                 await self._inner.cancel()
         
        +    async def retry(self) -> "AsyncJob[T]":
        +        """Select a successor for this exact failed attempt using pinned inputs.
        +
        +        Repeated requests select the same successor even after it finishes.
        +        Requires a supporting server and a safely retryable Function job.
        +        In-process operations do not retain a replayable specification and
        +        raise ``NotImplementedError``.
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError("retry requires a registry-backed job")
        +        return AsyncJob(await self._inner.retry(), self._result_decoder)
        +
             async def refresh(self) -> None:
                 """Ask the backend for this job's current state, and for a server-side
        -        job its full record, then cache it for the properties below.
        +        job its full record, then cache it for the read methods below.
         
                 Registry details are `None` until this runs, because submitting an
                 operation does not fetch its full registry record. Query-backed jobs
        @@ -365,49 +584,96 @@ class AsyncJob(Generic[T]):
                     return
                 await self._inner.refresh()
         
        -    @property
        -    def state(self) -> Optional[str]:
        -        """The last observed lifecycle state, without contacting the backend.
        +    async def checkout_latest(self) -> None:
        +        """Refresh this handle's cached state and complete job record together.
         
        -        `None` until the handle has talked to it. See :meth:`AsyncJob.refresh`.
        +        For a registry job, each call fetches one current record and updates
        +        the values returned by ``state()``, ``job_type()``, ``creation_ms()``,
        +        ``spec()``, ``result()`` and ``failure()`` from that observation. Calling
        +        those read methods afterward does not contact the backend. Query-backed
        +        and in-process jobs update their lifecycle state without registry details.
        +
        +        Updates this handle in place and returns ``None``. It does not wait for
        +        completion or restart the operation. Failed or cancelled states are
        +        cached without raising a job-failure exception; request errors propagate
        +        and leave the cached record unchanged. Event history remains a separate
        +        live request through [events()][lancedb.job.AsyncJob.events].
        +
        +        [refresh()][lancedb.job.AsyncJob.refresh] remains available with the
        +        same behavior.
        +
        +        Examples
        +        --------
        +        >>> await job.checkout_latest()  # doctest: +SKIP
        +        >>> print(job.state(), job.result(), job.failure())  # doctest: +SKIP
                 """
        -        if self._inner is None:
        -            return "finished"
        -        return self._inner._state
        +        await self.refresh()
        +
        +    def state(self) -> Optional[str]:
        +        """Return the last observed lifecycle state without contacting the backend.
        +
        +        `None` until the handle has talked to it. Call
        +        [checkout_latest()][lancedb.job.AsyncJob.checkout_latest] to refresh
        +        the state and registry details together.
        +        """
        +        return self._state
         
             @property
        +    def _state(self) -> Optional[str]:
        +        return self._inner._state if self._inner is not None else "finished"
        +
             def job_type(self) -> Optional[str]:
        -        """The job's kind of work, without contacting the backend.
        +        """Return the job's kind of work without contacting the backend.
         
                 SQL-backed handles report ``"query"`` immediately. Registry handles
                 report the server's job type after :meth:`refresh` or :meth:`status`.
                 In-process handles return ``None``.
                 """
        +        return self._job_type
        +
        +    @property
        +    def _job_type(self) -> Optional[str]:
                 return self._inner.job_type if self._inner is not None else None
         
        -    @property
             def creation_ms(self) -> Optional[int]:
        -        """When the job was created, in milliseconds since the epoch."""
        +        """Return the cached creation time in epoch milliseconds; no backend call."""
        +        return self._creation_ms
        +
        +    @property
        +    def _creation_ms(self) -> Optional[int]:
                 return self._field("creation_ms")
         
        -    @property
             def spec(self) -> Optional[Any]:
        -        """The job-type-specific specification it was submitted with."""
        +        """Return the complete cached job specification without a backend call."""
        +        return self._spec
        +
        +    @property
        +    def _spec(self) -> Optional[Any]:
                 return self._field("spec")
         
        -    @property
             def result(self) -> Optional[Any]:
        -        """The job-type-specific terminal result, as reported data rather than
        -        the typed model :meth:`AsyncJob.wait` returns.
        +        """Return the cached job-specific terminal result without a backend call.
         
        -        `None` until the job succeeds, so a job that never terminates reports
        -        its progress through :meth:`AsyncJob.events` instead.
        +        This is reported data rather than the typed model
        +        [wait()][lancedb.job.AsyncJob.wait] returns. It can remain `None` until
        +        a successful registry record is fetched with
        +        [checkout_latest()][lancedb.job.AsyncJob.checkout_latest] or another
        +        live status request. For ongoing progress, use
        +        [progress()][lancedb.job.AsyncJob.progress] or
        +        [events()][lancedb.job.AsyncJob.events].
                 """
        +        return self._result
        +
        +    @property
        +    def _result(self) -> Optional[Any]:
                 return self._field("result")
         
        -    @property
             def failure(self) -> Optional[JobFailureInfo]:
        -        """Why the job failed, when it failed and the server reports a reason."""
        +        """Return cached failure details, when reported, without a backend call."""
        +        return self._failure
        +
        +    @property
        +    def _failure(self) -> Optional[JobFailureInfo]:
                 return self._field("failure")
         
             @property
        @@ -422,15 +688,211 @@ class AsyncJob(Generic[T]):
                 description = self._inner._description if self._inner is not None else None
                 return getattr(description, name) if description is not None else None
         
        +    async def stack(self, worker_id: str) -> dict[str, Any]:
        +        """Capture Python thread stacks from a running Function worker.
        +
        +        Requires server support and system operate privilege. The response has
        +        ``status``, ``worker_id``, ``execution_epoch`` and ``stacks``. Each session
        +        reports its status, capture timestamp, Python frames and truncation.
        +        ``omitted_sessions`` counts sessions beyond the server's capture limit.
        +        Captures exclude source text, locals and native frames; a recent capture
        +        may be reused to bound overhead. Unsupported or unavailable captures
        +        have an explicit status. Transport and authorization errors propagate.
        +        Local operations and SQL query handles raise ``NotImplementedError``.
        +        Timeout stack evidence remains in the job's failure events.
        +
        +        Examples
        +        --------
        +        >>> evidence = await job.stack("worker-id")  # doctest: +SKIP
        +        >>> print(evidence["stacks"])  # doctest: +SKIP
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "worker stacks require a server-side Function job"
        +            )
        +        return json.loads(await self._inner.stack(worker_id))
        +
        +    async def capture_profile(
        +        self,
        +        worker_id: str,
        +        *,
        +        kind: FunctionProfileKind = "cpu",
        +        duration: Optional[timedelta] = None,
        +        session_slot: int = 0,
        +    ) -> FunctionProfile:
        +        """Request a profile of one running Enterprise Function worker session.
        +
        +        Return an accepted capture identity without waiting for recording to
        +        finish. The capture belongs to this existing refresh job. The server
        +        pins its worker, Python session and execution epoch. System Operate
        +        permission and server profiling support are required.
        +
        +        ``kind`` is ``"cpu"`` for Python CPU samples, ``"memory"`` for Python
        +        allocations retained at the end of capture, or ``"gpu"`` for PyTorch
        +        CUDA activities. CPU and memory allow 1–30 seconds, defaulting to 10;
        +        GPU allows 1–5 seconds, defaulting to 5. Slot zero is the first Python
        +        session. GPU tracing requires initialized PyTorch CUDA/CUPTI. CPU
        +        sampling requires readable per-thread procfs and is unavailable in
        +        dedicated sandboxes. Captures add workload-dependent overhead.
        +
        +        Examples
        +        --------
        +        >>> from datetime import timedelta
        +        >>> profile = await job.capture_profile(  # doctest: +SKIP
        +        ...     "worker-id", kind="gpu", duration=timedelta(seconds=2)
        +        ... )
        +        >>> print(profile.profile_id)  # doctest: +SKIP
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return FunctionProfile._from_json(
        +            await self._inner.capture_profile(
        +                worker_id,
        +                kind=kind,
        +                duration_seconds=_profile_seconds(duration, "duration"),
        +                session_slot=session_slot,
        +            )
        +        )
        +
        +    async def profile_status(self, profile_id: str) -> FunctionProfile:
        +        """Fetch capture status and identity without waiting.
        +
        +        A failed capture returns ``status="failed"`` and the server's ``error``.
        +        This does not change the parent job's status. Keep the profile ID to
        +        retrieve retained evidence after the refresh finishes.
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return FunctionProfile._from_json(await self._inner.profile_status(profile_id))
        +
        +    async def wait_for_profile(
        +        self,
        +        profile_id: str,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +        poll_interval: Optional[timedelta] = None,
        +    ) -> FunctionProfile:
        +        """Wait for a capture independently of the parent Function refresh.
        +
        +        Defaults to a 60-second timeout and two seconds between status requests.
        +        Set ``poll_interval`` to change the polling cadence. The timeout includes
        +        HTTP requests and sleeps. It raises ``TimeoutError`` without cancelling
        +        either the capture or the refresh; keep the ID to wait again. A failed
        +        capture raises ``RuntimeError`` with the server's reason. Use
        +        ``profile_status`` to inspect a failed capture's typed metadata.
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return FunctionProfile._from_json(
        +            await self._inner.wait_for_profile(
        +                profile_id,
        +                timeout_seconds=_profile_seconds(timeout, "timeout"),
        +                poll_interval_seconds=_profile_seconds(poll_interval, "poll_interval"),
        +            )
        +        )
        +
        +    async def profile_artifact(self, profile_id: str) -> dict[str, Any]:
        +        """Retrieve the actual JSON for a completed capture.
        +
        +        CPU artifacts use speedscope, Python allocations use tracemalloc, and
        +        GPU artifacts use Chrome Trace Event JSON. Truncation metadata is
        +        preserved. The server retains up to eight captures per job for at most
        +        an hour, or until job scratch is reclaimed or archived. Permission,
        +        expired-artifact and unsupported-server errors propagate to the caller.
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return json.loads(await self._inner.profile_artifact(profile_id))
        +
        +    async def export_profile(self, profile_id: str, path: str | PathLike[str]) -> None:
        +        """Write a completed capture's actual JSON to a file.
        +
        +        The destination is overwritten only after retrieval succeeds. Export a
        +        CPU capture to a speedscope file, or a GPU capture to a trace file for
        +        Perfetto. GPU kernel/transfer durations may overlap and are not GPU
        +        utilization. Python operator attribution and GPU allocation stacks are
        +        outside the GPU trace format.
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        artifact = await self._inner.profile_artifact(profile_id)
        +        await asyncio.to_thread(Path(path).write_text, artifact, encoding="utf-8")
        +
        +    async def stats(self) -> Optional[str]:
        +        """Return a printable run report for this Function job.
        +
        +        The report includes recorded phase timings, finishing-supervisor slot
        +        occupancy, all-attempt split execution and batch latency, and accepted-row
        +        throughput. Each call reads the current server report.
        +        Returns ``None`` while the job is running or if no recorded profile is
        +        available, without waiting for completion. Missing measurements remain
        +        unavailable rather than becoming zero. The server formats the report;
        +        the SDK returns it verbatim.
        +
        +        Requires a server-side Function job and a server supporting run reports.
        +        Local operations and SQL query handles do not support this operation.
        +        Unsupported operations raise ``NotImplementedError`` or a server error.
        +        This method returns text; use ``print`` to display it.
        +
        +        Examples
        +        --------
        +        >>> print(await job.stats())  # doctest: +SKIP
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "job statistics require a server-side Function job"
        +            )
        +        return await self._inner.stats()
        +
        +    async def export_timeline(self, path: str | PathLike[str]) -> None:
        +        """Write a fresh recorded Function job timeline as Chrome trace JSON.
        +
        +        Open the file in Perfetto or Chrome tracing. The recording contains
        +        retained split spans grouped by worker and timestamped job phases.
        +        Batch counts and latency statistics are included as details; individual
        +        batch timestamps are not recorded. Running jobs export a partial snapshot
        +        without waiting or cancelling. Download again to include later work.
        +
        +        Requires a server-side Function job and a server supporting timeline
        +        export. Unsupported operations raise ``NotImplementedError`` or a server
        +        error. The destination is overwritten only after the trace is fetched.
        +        Filesystem errors propagate to the caller.
        +
        +        Examples
        +        --------
        +        >>> await job.export_timeline("refresh.trace.json")  # doctest: +SKIP
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "job timeline export requires a server-side Function job"
        +            )
        +        trace = await self._inner.timeline()
        +        await asyncio.to_thread(Path(path).write_text, trace, encoding="utf-8")
        +
             async def events(
                 self,
                 *,
                 limit: Optional[int] = None,
                 filter: Optional[str] = None,
        +        page_token: Optional[str] = None,
             ) -> "pa.Table":
                 """This job's recorded lifecycle events.
         
        -        Where the properties above report a terminal result only once the job
        +        Each call requests event history without updating the cached record.
        +        Use [checkout_latest()][lancedb.job.AsyncJob.checkout_latest] to refresh
        +        the job's state and registry details together.
        +
        +        Where the read methods above report a terminal result only once the job
                 reaches one, events are written as the job runs and outlive the workers
                 that produced them. A distributed job records a `claim`/`claim_complete`
                 pair per unit of work, each carrying `rows_processed`, so a job that
        @@ -454,71 +916,163 @@ class AsyncJob(Generic[T]):
                             "jobs",
                         )
                     )
        -        return await self._inner.events(limit=limit, filter=filter)
        +        if page_token is None:
        +            return await self._inner.events(limit=limit, filter=filter)
        +        return await self._inner.events(
        +            limit=limit, filter=filter, page_token=page_token
        +        )
        +
        +    async def history(
        +        self, *, limit: Optional[int] = None, filter: Optional[str] = None
        +    ) -> AsyncIterator["pa.Table"]:
        +        """Walk retained history in pages, following opaque server continuations."""
        +        token = None
        +        while True:
        +            page = await self.events(limit=limit, filter=filter, page_token=token)
        +            yield page
        +            next_token = (page.schema.metadata or {}).get(
        +                b"lancedb.job_coordinator.page_token"
        +            )
        +            if next_token is None:
        +                return
        +            next_token = next_token.decode()
        +            if next_token == token:
        +                raise RuntimeError("job history repeated its page token")
        +            token = next_token
         
             def __repr__(self) -> str:
                 return _job_repr("AsyncJob", self)
         
         
         _REPR_INDENT = " " * 4
        +_REPR_MAX_FIELD_LENGTH = 240
        +_PAYLOAD_REPR = reprlib.Repr()
        +_PAYLOAD_REPR.maxlevel = 2
        +_PAYLOAD_REPR.maxdict = 4
        +_PAYLOAD_REPR.maxlist = 4
        +_PAYLOAD_REPR.maxtuple = 4
        +_PAYLOAD_REPR.maxstring = 120
        +_PAYLOAD_REPR.maxother = 120
         
         
         def _repr_payload(value: Any) -> str:
        -    """Render a job payload as indented JSON, aligned under its field."""
        -    try:
        -        rendered = json.dumps(value, indent=4)
        -    except TypeError:
        -        return repr(value)
        -    return rendered.replace("\n", "\n" + _REPR_INDENT)
        +    """Bound nested payload previews without changing the stored values."""
        +    rendered = _PAYLOAD_REPR.repr(value).replace("\n", "\\n")
        +    if len(rendered) > _REPR_MAX_FIELD_LENGTH:
        +        return rendered[: _REPR_MAX_FIELD_LENGTH - 3] + "..."
        +    return rendered
         
         
         def _job_repr(kind: str, job: Any) -> str:
        -    """Render every field the handle currently knows, omitting the rest.
        +    """Show cached job identity and bounded previews without backend calls.
         
        -    One field per line, with the JSON payloads indented, because a refresh
        -    job's spec and result are the point of printing it.
        +    The complete payloads remain available through ``spec()`` and ``result()``.
             """
        -    state = job.state
        +    state = job.state()
             if state is None:
                 # Nothing has been fetched yet, so there is nothing to lay out.
        -        known = f"id={job.id!r}, " if job.id is not None else ""
        +        known = f"id={_repr_payload(job.id())}, " if job.id() is not None else ""
                 return f"{kind}({known}not refreshed)"
         
             fields = []
        -    if job.id is not None:
        -        fields.append(f"id={job.id!r}")
        -    fields.append(f"state={state!r}")
        +    if job.id() is not None:
        +        fields.append(f"id={_repr_payload(job.id())}")
        +    fields.append(f"state={_repr_payload(state)}")
             for name in ("job_type", "creation_ms"):
        -        value = getattr(job, name)
        -        if value is not None:
        -            fields.append(f"{name}={value!r}")
        -    for name in ("spec", "result"):
        -        value = getattr(job, name)
        +        value = getattr(job, name)()
                 if value is not None:
                     fields.append(f"{name}={_repr_payload(value)}")
        -    if job.failure is not None:
        -        fields.append(f"failure={job.failure!r}")
        +    for name in ("spec", "result"):
        +        value = getattr(job, name)()
        +        if value is not None:
        +            fields.append(f"{name}={_repr_payload(value)}")
        +    if job.failure() is not None:
        +        fields.append(f"failure={_repr_payload(job.failure())}")
             body = "".join(f"\n{_REPR_INDENT}{field}," for field in fields)
             return f"{kind}({body}\n)"
         
         
         class Job(Generic[T]):
        -    """Synchronous counterpart of `AsyncJob` with the same result type."""
        +    """Synchronous counterpart of `AsyncJob` with the same result type.
        +
        +    Call ``state()``, ``result()``, ``failure()`` and ``spec()`` to read the
        +    cached record after ``job.checkout_latest()`` refreshes it holistically.
        +    ``events()`` makes a separate live request for event history.
        +    """
         
             def __init__(self, inner: Optional[AsyncJob[T]]):
        -        self._inner = inner
        +        self._inner = inner if inner is not None else AsyncJob(None)
        +
        +    def job_id(self) -> Optional[str]:
        +        """Selected attempt ID; refresh can change it while ``id()`` stays fixed.
        +
        +        Save the value after refreshing for paged diagnostics.
        +        See [AsyncJob.job_id()][lancedb.job.AsyncJob.job_id].
        +        """
        +        return self._inner.job_id()
        +
        +    def operation_id(self) -> Optional[str]:
        +        """Root retry identity.
        +
        +        See [AsyncJob.operation_id()][lancedb.job.AsyncJob.operation_id].
        +        """
        +        return self._inner.operation_id()
        +
        +    def attempt(self) -> Optional[int]:
        +        """One-based attempt ordinal.
        +
        +        See [AsyncJob.attempt()][lancedb.job.AsyncJob.attempt].
        +        """
        +        return self._inner.attempt()
        +
        +    def retry_of(self) -> Optional[str]:
        +        """Immediate predecessor.
        +
        +        See [AsyncJob.retry_of()][lancedb.job.AsyncJob.retry_of].
        +        """
        +        return self._inner.retry_of()
        +
        +    def lifecycle_state(self) -> Optional[JobState]:
        +        """Detailed state last observed.
        +
        +        See [AsyncJob.lifecycle_state()][lancedb.job.AsyncJob.lifecycle_state].
        +        """
        +        return self._inner.lifecycle_state()
        +
        +    def status_typed(self) -> JobState:
        +        """Refresh the detailed lifecycle state. See :meth:`AsyncJob.status_typed`."""
        +        return LOOP.run(self._inner.status_typed())
        +
        +    def source_table_version(self) -> Optional[int]:
        +        """Pinned source snapshot.
        +
        +        See the async handle's
        +        [source_table_version()][lancedb.job.AsyncJob.source_table_version].
        +        """
        +        return self._inner.source_table_version()
        +
        +    def execution_epoch(self) -> Optional[int]:
        +        """Execution fencing token.
        +
        +        See [AsyncJob.execution_epoch()][lancedb.job.AsyncJob.execution_epoch].
        +        """
        +        return self._inner.execution_epoch()
        +
        +    def id(self) -> Optional[str]:
        +        """Return the operation's opaque server ID without a backend call.
        +
        +        See [AsyncJob.id()][lancedb.job.AsyncJob.id].
        +        """
        +        return self._id
         
             @property
        -    def id(self) -> Optional[str]:
        -        """Identifies the operation on the server that is running it.
        -
        -        See :attr:`AsyncJob.id`.
        -        """
        -        return self._inner.id if self._inner is not None else None
        +    def _id(self) -> Optional[str]:
        +        return self._inner._id if self._inner is not None else None
         
             def status(self) -> str:
        -        """The operation's current lifecycle state: "running", "finished",
        -        "failed", or "cancelled".
        +        """Return the current status, usually "running", "finished", "failed",
        +        or "cancelled". A Function refresh waiting for execution workers reports
        +        "waiting_for_capacity".
         
                 See :meth:`AsyncJob.status`.
                 """
        @@ -565,6 +1119,10 @@ class Job(Generic[T]):
                     return
                 LOOP.run(self._inner.cancel())
         
        +    def retry(self) -> "Job[T]":
        +        """Select this attempt's pinned successor. See :meth:`AsyncJob.retry`."""
        +        return Job(LOOP.run(self._inner.retry()))
        +
             def refresh(self) -> None:
                 """Ask the backend for this job's current state and record.
         
        @@ -574,35 +1132,87 @@ class Job(Generic[T]):
                     return
                 LOOP.run(self._inner.refresh())
         
        -    @property
        +    def checkout_latest(self) -> None:
        +        """Refresh this handle's cached state and complete job record together.
        +
        +        Updates this handle in place and returns ``None`` without waiting for
        +        completion. See
        +        [AsyncJob.checkout_latest()][lancedb.job.AsyncJob.checkout_latest]
        +        for refreshed fields and availability. ``refresh()`` remains available
        +        with the same behavior.
        +
        +        Examples
        +        --------
        +        >>> job.checkout_latest()  # doctest: +SKIP
        +        >>> print(job.state(), job.result(), job.failure())  # doctest: +SKIP
        +        """
        +        self.refresh()
        +
             def state(self) -> Optional[str]:
        -        """The last observed lifecycle state. See :attr:`AsyncJob.state`."""
        -        return self._inner.state if self._inner is not None else "finished"
        +        """Return the cached lifecycle state without a backend call.
        +
        +        See [AsyncJob.state()][lancedb.job.AsyncJob.state].
        +        """
        +        return self._state
         
             @property
        +    def _state(self) -> Optional[str]:
        +        return self._inner._state if self._inner is not None else "finished"
        +
             def job_type(self) -> Optional[str]:
        -        """The job's type. See :attr:`AsyncJob.job_type`."""
        -        return self._inner.job_type if self._inner is not None else None
        +        """Return the cached job type without a backend call.
        +
        +        See [AsyncJob.job_type()][lancedb.job.AsyncJob.job_type].
        +        """
        +        return self._job_type
         
             @property
        +    def _job_type(self) -> Optional[str]:
        +        return self._inner._job_type if self._inner is not None else None
        +
             def creation_ms(self) -> Optional[int]:
        -        """When the job was created. See :attr:`AsyncJob.creation_ms`."""
        -        return self._field("creation_ms")
        +        """Return the cached creation time in epoch milliseconds.
        +
        +        See [AsyncJob.creation_ms()][lancedb.job.AsyncJob.creation_ms].
        +        """
        +        return self._creation_ms
         
             @property
        +    def _creation_ms(self) -> Optional[int]:
        +        return self._field("_creation_ms")
        +
             def spec(self) -> Optional[Any]:
        -        """The job's specification. See :attr:`AsyncJob.spec`."""
        -        return self._field("spec")
        +        """Return the complete cached specification without a backend call.
        +
        +        See [AsyncJob.spec()][lancedb.job.AsyncJob.spec].
        +        """
        +        return self._spec
         
             @property
        +    def _spec(self) -> Optional[Any]:
        +        return self._field("_spec")
        +
             def result(self) -> Optional[Any]:
        -        """The job's terminal result. See :attr:`AsyncJob.result`."""
        -        return self._field("result")
        +        """Return the cached terminal result without a backend call.
        +
        +        See [AsyncJob.result()][lancedb.job.AsyncJob.result].
        +        """
        +        return self._result
         
             @property
        +    def _result(self) -> Optional[Any]:
        +        return self._field("_result")
        +
             def failure(self) -> Optional[JobFailureInfo]:
        -        """Why the job failed. See :attr:`AsyncJob.failure`."""
        -        return self._field("failure")
        +        """Return cached failure details without a backend call.
        +
        +        See [AsyncJob.failure()][lancedb.job.AsyncJob.failure].
        +        """
        +        return self._failure
        +
        +    @property
        +    def _failure(self) -> Optional[JobFailureInfo]:
        +        return self._field("_failure")
         
             @property
             def _spec_json(self) -> Optional[str]:
        @@ -615,11 +1225,146 @@ class Job(Generic[T]):
             def _field(self, name: str) -> Optional[Any]:
                 return getattr(self._inner, name) if self._inner is not None else None
         
        +    def stack(self, worker_id: str) -> dict[str, Any]:
        +        """Capture Python thread stacks from a running Function worker.
        +
        +        See [AsyncJob.stack][lancedb.job.AsyncJob.stack] for availability,
        +        permissions and response fields.
        +
        +        Examples
        +        --------
        +        >>> print(job.stack("worker-id")["stacks"])  # doctest: +SKIP
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "worker stacks require a server-side Function job"
        +            )
        +        return LOOP.run(self._inner.stack(worker_id))
        +
        +    def capture_profile(
        +        self,
        +        worker_id: str,
        +        *,
        +        kind: FunctionProfileKind = "cpu",
        +        duration: Optional[timedelta] = None,
        +        session_slot: int = 0,
        +    ) -> FunctionProfile:
        +        """Request a profile of a running Enterprise Function worker session.
        +
        +        See [AsyncJob.capture_profile][lancedb.job.AsyncJob.capture_profile] for
        +        kinds, recording windows, permissions and runtime requirements.
        +
        +        >>> from datetime import timedelta
        +        >>> profile = job.capture_profile(  # doctest: +SKIP
        +        ...     "worker-id", kind="cpu", duration=timedelta(seconds=10)
        +        ... )
        +        >>> job.wait_for_profile(profile.profile_id)  # doctest: +SKIP
        +        >>> job.export_profile(  # doctest: +SKIP
        +        ...     profile.profile_id, "cpu.speedscope.json"
        +        ... )
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return LOOP.run(
        +            self._inner.capture_profile(
        +                worker_id, kind=kind, duration=duration, session_slot=session_slot
        +            )
        +        )
        +
        +    def profile_status(self, profile_id: str) -> FunctionProfile:
        +        """Fetch capture status, including retained captures after refresh.
        +
        +        See [AsyncJob.profile_status][lancedb.job.AsyncJob.profile_status].
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return LOOP.run(self._inner.profile_status(profile_id))
        +
        +    def wait_for_profile(
        +        self,
        +        profile_id: str,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +        poll_interval: Optional[timedelta] = None,
        +    ) -> FunctionProfile:
        +        """Wait for a capture with a configurable timeout and polling cadence.
        +
        +        See [AsyncJob.wait_for_profile][lancedb.job.AsyncJob.wait_for_profile].
        +        A client timeout never cancels the capture or parent refresh job.
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return LOOP.run(
        +            self._inner.wait_for_profile(
        +                profile_id, timeout=timeout, poll_interval=poll_interval
        +            )
        +        )
        +
        +    def profile_artifact(self, profile_id: str) -> dict[str, Any]:
        +        """Retrieve a completed capture's actual JSON, preserving its format.
        +
        +        See [AsyncJob.profile_artifact][lancedb.job.AsyncJob.profile_artifact].
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return LOOP.run(self._inner.profile_artifact(profile_id))
        +
        +    def export_profile(self, profile_id: str, path: str | PathLike[str]) -> None:
        +        """Write a retained capture's JSON after successful retrieval.
        +
        +        See [AsyncJob.export_profile][lancedb.job.AsyncJob.export_profile].
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "Function profiling requires an Enterprise Function refresh job"
        +            )
        +        return LOOP.run(self._inner.export_profile(profile_id, path))
        +
        +    def stats(self) -> Optional[str]:
        +        """Return a printable Function job run report.
        +
        +        See [AsyncJob.stats][lancedb.job.AsyncJob.stats] for metrics and availability.
        +
        +        Examples
        +        --------
        +        >>> print(job.stats())  # doctest: +SKIP
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "job statistics require a server-side Function job"
        +            )
        +        return LOOP.run(self._inner.stats())
        +
        +    def export_timeline(self, path: str | PathLike[str]) -> None:
        +        """Write Chrome trace JSON for this Function job.
        +
        +        See :meth:`AsyncJob.export_timeline`. Open the file in Perfetto or
        +        Chrome tracing.
        +
        +        Examples
        +        --------
        +        >>> job.export_timeline("refresh.trace.json")  # doctest: +SKIP
        +        """
        +        if self._inner is None:
        +            raise NotImplementedError(
        +                "job timeline export requires a server-side Function job"
        +            )
        +        return LOOP.run(self._inner.export_timeline(path))
        +
             def events(
                 self,
                 *,
                 limit: Optional[int] = None,
                 filter: Optional[str] = None,
        +        page_token: Optional[str] = None,
             ) -> "pa.Table":
                 """This job's recorded lifecycle events.
         
        @@ -632,7 +1377,20 @@ class Job(Generic[T]):
                             "jobs",
                         )
                     )
        -        return LOOP.run(self._inner.events(limit=limit, filter=filter))
        +        return LOOP.run(
        +            self._inner.events(limit=limit, filter=filter, page_token=page_token)
        +        )
        +
        +    def history(
        +        self, *, limit: Optional[int] = None, filter: Optional[str] = None
        +    ) -> Iterator["pa.Table"]:
        +        """Walk retained history in pages. See :meth:`AsyncJob.history`."""
        +        pages = self._inner.history(limit=limit, filter=filter)
        +        try:
        +            while (page := LOOP.run(anext(pages, None))) is not None:
        +                yield page
        +        finally:
        +            LOOP.run(pages.aclose())
         
             def __repr__(self) -> str:
                 return _job_repr("Job", self)
        @@ -643,3 +1401,15 @@ def _typed_job(
         ) -> AsyncJob[T]:
             """Bind an internal JSON-producing job to its public result model."""
             return AsyncJob(inner, result_decoder)
        +
        +
        +def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
        +    if inner.job_type == "cleanup":
        +        return _typed_job(inner, CleanupResult.from_json)
        +    if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"):
        +        return _typed_job(inner, RefreshColumnResult.from_json)
        +    if inner.job_type == "prewarm_page_cache":
        +        return _typed_job(inner, PrewarmDataResult.from_json)
        +    if inner.job_type == "compact":
        +        return _typed_job(inner, CompactionResult.from_json)
        +    return AsyncJob(inner)
        diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py
        index 8abc9d85b..f85599b2d 100644
        --- a/python/python/lancedb/listing.py
        +++ b/python/python/lancedb/listing.py
        @@ -6,7 +6,19 @@
         from __future__ import annotations
         
         import asyncio
        -from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar
        +from collections import deque
        +from itertools import islice
        +from operator import index
        +from typing import (
        +    Any,
        +    AsyncIterator,
        +    Callable,
        +    Generic,
        +    Iterator,
        +    Optional,
        +    TypeVar,
        +    overload,
        +)
         
         from .background_loop import LOOP
         
        @@ -59,29 +71,85 @@ class Listing(Iterator[T], Generic[T]):
                     print(name)
         
             Use ``list(connection.list_views())`` to collect all results.
        +
        +    Indexes and slices refer to the remaining items and do not consume them.
        +    A bounded forward slice, such as ``listing[:5]``, fetches only enough pages
        +    to reach its stop. ``len(listing)``, negative indexes, and open-ended or
        +    reverse slices fetch and cache all remaining results. Iteration then drains
        +    that cache. These operations may perform requests and raise request errors.
             """
         
             def __init__(self, inner: AsyncListing[T]):
                 self._inner = inner
        +        self._buffer: deque[T] = deque()
         
             def __iter__(self) -> Listing[T]:
                 return self
         
             def __next__(self) -> T:
        +        if self._buffer:
        +            return self._buffer.popleft()
                 try:
                     return LOOP.run(self._inner.__anext__())
                 except StopAsyncIteration:
                     raise StopIteration from None
         
        +    def _fill(self, count: Optional[int]) -> None:
        +        while count is None or len(self._buffer) < count:
        +            try:
        +                item = LOOP.run(self._inner.__anext__())
        +            except StopAsyncIteration:
        +                return
        +            self._buffer.append(item)
        +
        +    def __len__(self) -> int:
        +        """Fetch and cache every remaining item, returning the remaining count."""
        +        self._fill(None)
        +        return len(self._buffer)
        +
        +    def __bool__(self) -> bool:
        +        self._fill(1)
        +        return bool(self._buffer)
        +
        +    @overload
        +    def __getitem__(self, key: int) -> T: ...
        +
        +    @overload
        +    def __getitem__(self, key: slice) -> list[T]: ...
        +
        +    def __getitem__(self, key: int | slice) -> T | list[T]:
        +        """Read remaining items without consuming them; bounded slices stay lazy."""
        +        if isinstance(key, slice):
        +            start = 0 if key.start is None else index(key.start)
        +            stop = None if key.stop is None else index(key.stop)
        +            step = 1 if key.step is None else index(key.step)
        +            if step == 0:
        +                raise ValueError("slice step cannot be zero")
        +            if start >= 0 and stop is not None and stop >= 0 and step > 0:
        +                if start >= stop:
        +                    return []
        +                self._fill(stop)
        +                start, stop, step = key.indices(len(self._buffer))
        +                return list(
        +                    islice(self._buffer, start, stop, min(step, len(self._buffer) + 1))
        +                )
        +            self._fill(None)
        +            return list(self._buffer)[key]
        +        position = index(key)
        +        self._fill(None if position < 0 else position + 1)
        +        return self._buffer[position]
        +
             def num_page_results(self) -> int:
                 """Return the number of cached items available without another request."""
        -        return self._inner.num_page_results()
        +        return len(self._buffer) + self._inner.num_page_results()
         
             def page_token(self) -> Optional[str]:
                 """Return the next request's token.
         
                 See [AsyncListing.page_token][lancedb.listing.AsyncListing.page_token]
                 for initial, cached, final-page, and error behavior.
        +        Indexing, slicing, and counting can also advance this token; drain all
        +        ``num_page_results()`` cached items before resuming from it.
                 """
                 return self._inner.page_token()
         
        @@ -175,6 +243,9 @@ class _AsyncPagedNameListing(AsyncIterator[str]):
         class AsyncTableListing(_AsyncPagedNameListing):
             """Awaitable table iterator; awaiting loads one page.
         
        +    Iteration fetches all pages. The ``tables`` attribute contains only the
        +    current page, so use ``await db.table_exists([name])`` for existence checks.
        +
             For example::
         
                 page = await db.list_tables(limit=20)
        @@ -229,6 +300,10 @@ class _PagedNameListing(Iterator[str]):
         class TableListing(_PagedNameListing):
             """Table iterator retaining the current page as a list.
         
        +    Iteration fetches all pages. The ``tables`` attribute contains only the
        +    current page, so use ``db.table_exists([name])`` or ``name in db`` for
        +    existence checks. Use ``list(db.list_tables())`` to collect all names.
        +
             For example::
         
                 page = db.list_tables(limit=20)
        @@ -239,6 +314,7 @@ class TableListing(_PagedNameListing):
         
             @property
             def tables(self) -> list[str]:
        +        """A copy of the table names in the most recently fetched page."""
                 return self._inner.tables
         
         
        diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py
        index a1c83dd6d..28f7d9401 100644
        --- a/python/python/lancedb/materialized_view.py
        +++ b/python/python/lancedb/materialized_view.py
        @@ -19,6 +19,7 @@ from dataclasses import dataclass
         
         from .background_loop import LOOP
         from .job import AsyncJob, Job, _typed_job
        +from .resources import _resource_options
         
         if TYPE_CHECKING:
             import pyarrow as pa
        @@ -133,6 +134,16 @@ def _quote_identifier(name: str) -> str:
             return f"`{escaped}`"
         
         
        +def _validate_create_materialized_view(source, query, select, where, limit):
        +    if query is not None:
        +        if any(value is not None for value in (source, select, where, limit)):
        +            raise ValueError(
        +                "query cannot be combined with source, select, where or limit"
        +            )
        +    elif source is None:
        +        raise ValueError("either source or query must be provided")
        +
        +
         def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
             """``select`` items may be a column name, an ``(alias, expression)`` pair,
             or a dict of the same. A bare name projects itself and is quoted, so any
        @@ -156,6 +167,19 @@ def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
             return normalized
         
         
        +def _refresh_execution_options(
        +    total_cpu_millis, total_memory_bytes, total_gpu_count, gpu_class, gpu_count=None
        +):
        +    values = _resource_options(
        +        total_cpu_millis,
        +        total_memory_bytes,
        +        total_gpu_count,
        +        gpu_class=gpu_class,
        +        gpu_count=gpu_count,
        +    )
        +    return {name: value for name, value in values.items() if value is not None}
        +
        +
         class AsyncMaterializedView:
             """A handle on a materialized view: its table plus its definition.
         
        @@ -185,7 +209,15 @@ class AsyncMaterializedView:
                 return _definition_from_json(raw)
         
             async def refresh(
        -        self, *, full: bool = False, source_version: Optional[int] = None
        +        self,
        +        *,
        +        full: bool = False,
        +        source_version: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> "RefreshMaterializedViewResult":
                 """Recompute the view from its source.
         
        @@ -194,16 +226,43 @@ class AsyncMaterializedView:
                 and ``source_version`` selects a source version instead of the latest.
                 LanceDB Enterprise SQL refreshes do not support source-version pinning.
         
        +        ``total_cpu_millis`` (1000 = one core), ``total_memory_bytes``, and
        +        ``total_gpu_count`` cap aggregate resources for this execution,
        +        including its Function processes. Each resource may be overridden
        +        independently. Unset values inherit the view defaults, then the sum
        +        across distinct pinned Functions, then deployment defaults. GPU count
        +        may be zero for CPU-only views.
        +        ``gpu_class`` selects an operator-defined GPU class for this execution
        +        only. Omitted options preserve defaults.
        +        These options require an Enterprise backend that enforces isolation;
        +        Embedded refreshes reject them. Other servers may reject the new options.
        +
                 LanceDB Enterprise results leave ``mode``, ``rows_written``, and
                 ``source_version`` as ``None`` because the SQL job adapter does not expose
                 these metrics.
                 """
                 return await self._table._inner.refresh_materialized_view(
        -            source_version=source_version, full=full
        +            source_version=source_version,
        +            full=full,
        +            **_refresh_execution_options(
        +                total_cpu_millis,
        +                total_memory_bytes,
        +                total_gpu_count,
        +                gpu_class,
        +                gpu_count=gpu_count,
        +            ),
                 )
         
             async def refresh_async(
        -        self, *, full: bool = False, source_version: Optional[int] = None
        +        self,
        +        *,
        +        full: bool = False,
        +        source_version: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> "AsyncJob[RefreshMaterializedViewResult]":
                 """Submit a refresh and return its job without waiting.
         
        @@ -221,7 +280,15 @@ class AsyncMaterializedView:
         
                 return _typed_job(
                     await self._table._inner.refresh_materialized_view_async(
        -                source_version=source_version, full=full
        +                source_version=source_version,
        +                full=full,
        +                **_refresh_execution_options(
        +                    total_cpu_millis,
        +                    total_memory_bytes,
        +                    total_gpu_count,
        +                    gpu_class,
        +                    gpu_count=gpu_count,
        +                ),
                     ),
                     RefreshMaterializedViewResult.from_json,
                 )
        @@ -253,14 +320,42 @@ class MaterializedView:
                 return LOOP.run(self._async.definition())
         
             def refresh(
        -        self, *, full: bool = False, source_version: Optional[int] = None
        +        self,
        +        *,
        +        full: bool = False,
        +        source_version: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> "RefreshMaterializedViewResult":
                 """Recompute the view from its source. See
                 [AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]."""
        -        return LOOP.run(self._async.refresh(full=full, source_version=source_version))
        +        return LOOP.run(
        +            self._async.refresh(
        +                full=full,
        +                source_version=source_version,
        +                **_refresh_execution_options(
        +                    total_cpu_millis,
        +                    total_memory_bytes,
        +                    total_gpu_count,
        +                    gpu_class,
        +                    gpu_count=gpu_count,
        +                ),
        +            )
        +        )
         
             def refresh_async(
        -        self, *, full: bool = False, source_version: Optional[int] = None
        +        self,
        +        *,
        +        full: bool = False,
        +        source_version: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> "Job[RefreshMaterializedViewResult]":
                 """Submit a refresh and return its job without waiting.
         
        @@ -269,6 +364,16 @@ class MaterializedView:
                 """
                 return Job(
                     LOOP.run(
        -                self._async.refresh_async(full=full, source_version=source_version)
        +                self._async.refresh_async(
        +                    full=full,
        +                    source_version=source_version,
        +                    **_refresh_execution_options(
        +                        total_cpu_millis,
        +                        total_memory_bytes,
        +                        total_gpu_count,
        +                        gpu_class,
        +                        gpu_count=gpu_count,
        +                    ),
        +                )
                     )
                 )
        diff --git a/python/python/lancedb/merge.py b/python/python/lancedb/merge.py
        index 49f4793ed..c861414aa 100644
        --- a/python/python/lancedb/merge.py
        +++ b/python/python/lancedb/merge.py
        @@ -161,6 +161,8 @@ class LanceMergeInsertBuilder(object):
                 on_bad_vectors: str = "error",
                 fill_value: float = 0.0,
                 timeout: Optional[timedelta] = None,
        +        *,
        +        retries: Optional[int] = None,
             ) -> MergeInsertResult:
                 """
                 Executes the merge insert operation
        @@ -189,7 +191,22 @@ class LanceMergeInsertBuilder(object):
                     first attempt will not be cancelled.
         
                     When this is set, the timeout is enforced on all attempts, including
        -            the first.
        +            the first. For remote tables it is sent as a server execution timeout;
        +            it does not extend HTTP read or proxy idle timeouts, or prove that a
        +            failed request did not commit.
        +        retries: int, optional
        +            Override the remote retry budget for this execution only (0 to 255).
        +            Use ``execute(new_data, retries=0)`` to disable even retries after
        +            precommit conflicts (409) or rate limits (429). This does not change
        +            connection-wide/read budgets or local transaction conflict retries.
        +
        +            By default, remote calls use the connection's
        +            [RetryConfig][lancedb.remote.RetryConfig]. Its ``statuses`` (also set
        +            through ``LANCE_CLIENT_RETRY_STATUSES``) selects candidates within
        +            the retry budget; it never permits replay of ambiguous merge outcomes.
        +            In particular, 502, ordinary 503, and 504 are never replayed, even if
        +            configured. Reconcile table contents before manually repeating a merge
        +            whose commit outcome is unknown.
         
                 Returns
                 -------
        @@ -198,4 +215,6 @@ class LanceMergeInsertBuilder(object):
                 """
                 if timeout is not None:
                     self._timeout = timeout
        -        return self._table._do_merge(self, new_data, on_bad_vectors, fill_value)
        +        return self._table._do_merge(
        +            self, new_data, on_bad_vectors, fill_value, retries=retries
        +        )
        diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py
        index 3356b363c..bee9576c2 100644
        --- a/python/python/lancedb/namespace.py
        +++ b/python/python/lancedb/namespace.py
        @@ -10,6 +10,7 @@ through a namespace abstraction.
         
         from __future__ import annotations
         
        +import json
         import sys
         import warnings
         from typing import Any, Dict, Iterable, List, Optional, Union
        @@ -39,6 +40,9 @@ from lance_namespace_urllib3_client.models.query_table_request_vector import (
             QueryTableRequestVector,
         )
         from lance_namespace_urllib3_client.models.string_fts_query import StringFtsQuery
        +from lance_namespace_urllib3_client.models.structured_fts_query import (
        +    StructuredFtsQuery,
        +)
         from lance_namespace.errors import (
             NamespaceNotEmptyError,
             NamespaceNotFoundError,
        @@ -78,6 +82,7 @@ from lancedb.materialized_view import (
             SelectArg,
         )
         from lancedb.table import AsyncTable, LanceTable, Table
        +from lancedb.query import MatchQuery, MultiMatchQuery, PhraseQuery
         from lancedb.util import validate_table_name
         from lancedb.common import DATA
         from lancedb.pydantic import LanceModel
        @@ -178,6 +183,26 @@ def _query_to_namespace_request(
                     full_text_query_request = QueryTableRequestFullTextQuery(
                         string_query=StringFtsQuery(query=fts_query)
                     )
        +        elif getattr(fts_query, "operator", None) is not None:
        +            columns = fts_query.columns or []
        +            text = fts_query.query
        +            if len(text) >= 2 and text.startswith('"') and text.endswith('"'):
        +                if len(columns) > 1:
        +                    raise ValueError(
        +                        "Phrase queries cannot be used with multiple columns."
        +                    )
        +                structured = PhraseQuery(text[1:-1], columns[0] if columns else None)
        +            elif len(columns) > 1:
        +                structured = MultiMatchQuery(text, columns, operator=fts_query.operator)
        +            else:
        +                structured = MatchQuery(
        +                    text, columns[0] if columns else None, operator=fts_query.operator
        +                )
        +            full_text_query_request = QueryTableRequestFullTextQuery(
        +                structured_query=StructuredFtsQuery.from_dict(
        +                    {"query": json.loads(structured.to_json())}
        +                )
        +            )
                 elif hasattr(fts_query, "query"):
                     full_text_query_request = QueryTableRequestFullTextQuery(
                         string_query=StringFtsQuery(
        @@ -484,7 +509,9 @@ class LanceNamespaceDBConnection(DBConnection):
                     Supported values:
         
                     - "QueryTable": Execute queries on the namespace server via
        -              namespace.query_table() instead of locally.
        +              namespace.query_table() instead of locally. Queries with a
        +              nonempty ``order_by`` or an explicit ``scan_in_order(True)``
        +              execute on the client and require access to the table storage.
                     - "CreateTable": Execute table creation on the namespace server via
                       namespace.create_table() instead of using declare_table + local write.
         
        @@ -559,7 +586,7 @@ class LanceNamespaceDBConnection(DBConnection):
                         "storage_options": self.storage_options or None,
                         "read_consistency_interval_seconds": (
                             self.read_consistency_interval.total_seconds()
        -                    if self.read_consistency_interval
        +                    if self.read_consistency_interval is not None
                             else None
                         ),
                     }
        @@ -579,12 +606,15 @@ class LanceNamespaceDBConnection(DBConnection):
                 If limit is None, return all table names; zero returns an empty list.
         
                 .. deprecated::
        -            Use :meth:`list_tables` instead, which provides proper pagination support.
        +            Iterate over :meth:`list_tables` to get all names, or use
        +            :meth:`table_exists` to check for a particular table. The listing's
        +            ``tables`` attribute contains only one page.
                 """
                 import warnings
         
                 warnings.warn(
        -            "table_names() is deprecated, use list_tables() instead",
        +            "table_names() is deprecated, iterate list_tables() for all names "
        +            "or use table_exists([name]) to check existence",
                     DeprecationWarning,
                     stacklevel=2,
                 )
        @@ -612,6 +642,8 @@ class LanceNamespaceDBConnection(DBConnection):
                 storage_options: Optional[Dict[str, str]] = None,
                 data_storage_version: Optional[str] = None,
                 enable_v2_manifest_paths: Optional[bool] = None,
        +        initial_bases: Optional[List[Any]] = None,
        +        allow_external_blob_outside_bases: bool = False,
             ) -> Table:
                 if namespace_path is None:
                     namespace_path = []
        @@ -633,6 +665,8 @@ class LanceNamespaceDBConnection(DBConnection):
                         embedding_functions=embedding_functions,
                         namespace_path=namespace_path,
                         storage_options=storage_options,
        +                initial_bases=initial_bases,
        +                allow_external_blob_outside_bases=allow_external_blob_outside_bases,
                     )
                 )
         
        @@ -640,6 +674,7 @@ class LanceNamespaceDBConnection(DBConnection):
                     self,
                     name,
                     namespace_path=namespace_path,
        +            storage_options=storage_options,
                     namespace_client=self._namespace_client,
                     pushdown_operations=self._namespace_client_pushdown_operations,
                     route_pushdown_to_rust=self._route_pushdown_to_rust,
        @@ -678,6 +713,7 @@ class LanceNamespaceDBConnection(DBConnection):
                     self,
                     name,
                     namespace_path=namespace_path,
        +            storage_options=storage_options,
                     namespace_client=self._namespace_client,
                     pushdown_operations=self._namespace_client_pushdown_operations,
                     route_pushdown_to_rust=self._route_pushdown_to_rust,
        @@ -693,14 +729,21 @@ class LanceNamespaceDBConnection(DBConnection):
             def create_materialized_view(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: "SelectArg" = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
        +        exist_ok: bool = False,
             ) -> "MaterializedView":
                 """Define a materialized view over a table in the root namespace.
                 See
        @@ -712,12 +755,19 @@ class LanceNamespaceDBConnection(DBConnection):
                             self._inner.create_materialized_view(
                                 name,
                                 source,
        +                        query=query,
                                 select=select,
                                 where=where,
                                 limit=limit,
                                 with_no_data=with_no_data,
                                 auto_refresh_enabled=auto_refresh_enabled,
                                 auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +                        total_cpu_millis=total_cpu_millis,
        +                        total_memory_bytes=total_memory_bytes,
        +                        total_gpu_count=total_gpu_count,
        +                        exist_ok=exist_ok,
        +                        gpu_class=gpu_class,
        +                        gpu_count=gpu_count,
                             )
                         ).name
                     )
        @@ -727,25 +777,39 @@ class LanceNamespaceDBConnection(DBConnection):
             def create_materialized_view_async(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: "SelectArg" = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
        +        exist_ok: bool = False,
             ) -> Job[None]:
                 job = LOOP.run(
                     self._inner.create_materialized_view_async(
                         name,
                         source,
        +                query=query,
                         select=select,
                         where=where,
                         limit=limit,
                         with_no_data=with_no_data,
                         auto_refresh_enabled=auto_refresh_enabled,
                         auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                total_gpu_count=total_gpu_count,
        +                exist_ok=exist_ok,
        +                gpu_class=gpu_class,
        +                gpu_count=gpu_count,
                     )
                 )
                 return Job(job)
        @@ -1015,6 +1079,8 @@ class LanceNamespaceDBConnection(DBConnection):
                 bool
                     True if the table exists, False otherwise.
                 """
        +        if self._route_pushdown_to_rust:
        +            return LOOP.run(self._inner.table_exists(table_id))
                 request = TableExistsRequest(id=table_id)
                 try:
                     self._namespace_client.table_exists(request)
        @@ -1030,7 +1096,11 @@ class LanceNamespaceDBConnection(DBConnection):
                 limit: Optional[int] = None,
             ) -> TableListing:
                 """
        -        List all tables in this database with pagination support.
        +        Iterate over all tables in this database, fetching pages as needed.
        +
        +        The ``tables`` attribute contains only the current page (100 names by
        +        default). Iterate over the listing to visit all pages, or use
        +        ``table_exists([name])`` to check for a particular table.
         
                 Parameters
                 ----------
        @@ -1090,6 +1160,7 @@ class LanceNamespaceDBConnection(DBConnection):
                     self,
                     name,
                     namespace_path=namespace_path,
        +            storage_options=storage_options,
                     location=table_uri,
                     namespace_client=namespace_client,
                     managed_versioning=managed_versioning,
        @@ -1163,7 +1234,9 @@ class AsyncLanceNamespaceDBConnection:
                     Supported values:
         
                     - "QueryTable": Execute queries on the namespace server via
        -              namespace.query_table() instead of locally.
        +              namespace.query_table() instead of locally. Queries with a
        +              nonempty ``order_by`` or an explicit ``scan_in_order(True)``
        +              execute on the client and require access to the table storage.
                     - "CreateTable": Execute table creation on the namespace server via
                       namespace.create_table() instead of using declare_table + local write.
         
        @@ -1227,12 +1300,15 @@ class AsyncLanceNamespaceDBConnection:
                 If limit is None, return all table names; zero returns an empty list.
         
                 .. deprecated::
        -            Use :meth:`list_tables` instead, which provides proper pagination support.
        +            Iterate over :meth:`list_tables` to get all names, or use
        +            :meth:`table_exists` to check for a particular table. The listing's
        +            ``tables`` attribute contains only one page.
                 """
                 import warnings
         
                 warnings.warn(
        -            "table_names() is deprecated, use list_tables() instead",
        +            "table_names() is deprecated, iterate list_tables() for all names "
        +            "or use table_exists([name]) to check existence",
                     DeprecationWarning,
                     stacklevel=2,
                 )
        @@ -1257,6 +1333,8 @@ class AsyncLanceNamespaceDBConnection:
                 storage_options: Optional[Dict[str, str]] = None,
                 data_storage_version: Optional[str] = None,
                 enable_v2_manifest_paths: Optional[bool] = None,
        +        initial_bases: Optional[List[Any]] = None,
        +        allow_external_blob_outside_bases: bool = False,
             ) -> AsyncTable:
                 """Create a new table in the namespace."""
                 if namespace_path is None:
        @@ -1278,6 +1356,8 @@ class AsyncLanceNamespaceDBConnection:
                     namespace_path=namespace_path,
                     embedding_functions=embedding_functions,
                     storage_options=storage_options,
        +            initial_bases=initial_bases,
        +            allow_external_blob_outside_bases=allow_external_blob_outside_bases,
                 )
                 return table._set_namespace_context(
                     namespace_path=namespace_path,
        @@ -1327,25 +1407,39 @@ class AsyncLanceNamespaceDBConnection:
             async def create_materialized_view(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: "SelectArg" = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
        +        exist_ok: bool = False,
             ) -> "AsyncMaterializedView":
                 """Define a materialized view over a table in the root namespace."""
                 view = await self._inner.create_materialized_view(
                     name,
                     source,
        +            query=query,
                     select=select,
                     where=where,
                     limit=limit,
                     with_no_data=with_no_data,
                     auto_refresh_enabled=auto_refresh_enabled,
                     auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +            total_cpu_millis=total_cpu_millis,
        +            total_memory_bytes=total_memory_bytes,
        +            total_gpu_count=total_gpu_count,
        +            exist_ok=exist_ok,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
                 )
                 # Reopen through the namespace so the view's table carries the
                 # namespace client and pushdown configuration a bare inner table lacks.
        @@ -1354,25 +1448,39 @@ class AsyncLanceNamespaceDBConnection:
             async def create_materialized_view_async(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: "SelectArg" = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
        +        exist_ok: bool = False,
             ) -> AsyncJob[None]:
                 """Submit materialized-view creation and return its job."""
                 return await self._inner.create_materialized_view_async(
                     name,
                     source,
        +            query=query,
                     select=select,
                     where=where,
                     limit=limit,
                     with_no_data=with_no_data,
                     auto_refresh_enabled=auto_refresh_enabled,
                     auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +            total_cpu_millis=total_cpu_millis,
        +            total_memory_bytes=total_memory_bytes,
        +            total_gpu_count=total_gpu_count,
        +            exist_ok=exist_ok,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
                 )
         
             async def open_materialized_view(self, name: str) -> "AsyncMaterializedView":
        @@ -1614,6 +1722,8 @@ class AsyncLanceNamespaceDBConnection:
                 bool
                     True if the table exists, False otherwise.
                 """
        +        if self._route_pushdown_to_rust:
        +            return await self._inner.table_exists(table_id)
                 request = TableExistsRequest(id=table_id)
                 try:
                     self._namespace_client.table_exists(request)
        @@ -1628,7 +1738,11 @@ class AsyncLanceNamespaceDBConnection:
                 limit: Optional[int] = None,
             ) -> AsyncTableListing:
                 """
        -        List all tables in this database with pagination support.
        +        Iterate over all tables in this database, fetching pages as needed.
        +
        +        The ``tables`` attribute contains only the current page (100 names by
        +        default). Iterate over the listing to visit all pages, or use
        +        ``table_exists([name])`` to check for a particular table.
         
                 Parameters
                 ----------
        @@ -1658,12 +1772,18 @@ class AsyncLanceNamespaceDBConnection:
                 *,
                 default_namespace_path: Optional[List[str]] = None,
                 parameters: Optional[QueryParameters] = None,
        +        timeout: Optional[timedelta] = None,
        +        read_timeout: Optional[timedelta] = None,
        +        cancel_on_drop: bool = False,
             ) -> AsyncRecordBatchReader:
                 """Execute SQL when supported by the underlying connection."""
                 return await self._inner.execute_query(
                     query,
                     default_namespace_path=default_namespace_path,
                     parameters=parameters,
        +            timeout=timeout,
        +            read_timeout=read_timeout,
        +            cancel_on_drop=cancel_on_drop,
                 )
         
             async def execute_query_async(
        @@ -1672,6 +1792,9 @@ class AsyncLanceNamespaceDBConnection:
                 *,
                 default_namespace_path: Optional[List[str]] = None,
                 parameters: Optional[QueryParameters] = None,
        +        timeout: Optional[timedelta] = None,
        +        read_timeout: Optional[timedelta] = None,
        +        cancel_on_drop: bool = False,
             ) -> AsyncSqlQuery:
                 """Start executing SQL when supported by the underlying connection.
         
        @@ -1681,6 +1804,9 @@ class AsyncLanceNamespaceDBConnection:
                     query,
                     default_namespace_path=default_namespace_path,
                     parameters=parameters,
        +            timeout=timeout,
        +            read_timeout=read_timeout,
        +            cancel_on_drop=cancel_on_drop,
                 )
         
             async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription:
        @@ -1749,7 +1875,9 @@ def connect_namespace(
                 Supported values:
         
                 - "QueryTable": Execute queries on the namespace server via
        -          namespace.query_table() instead of locally.
        +          namespace.query_table() instead of locally. Queries with a nonempty
        +          ``order_by`` or an explicit ``scan_in_order(True)`` execute on the
        +          client and require access to the table storage.
                 - "CreateTable": Execute table creation on the namespace server via
                   namespace.create_table() instead of using declare_table + local write.
         
        @@ -1840,7 +1968,9 @@ def connect_namespace_async(
                 Supported values:
         
                 - "QueryTable": Execute queries on the namespace server via
        -          namespace.query_table() instead of locally.
        +          namespace.query_table() instead of locally. Queries with a nonempty
        +          ``order_by`` or an explicit ``scan_in_order(True)`` execute on the
        +          client and require access to the table storage.
                 - "CreateTable": Execute table creation on the namespace server via
                   namespace.create_table() instead of using declare_table + local write.
         
        diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py
        index a6f584f8a..1656548ec 100644
        --- a/python/python/lancedb/permutation.py
        +++ b/python/python/lancedb/permutation.py
        @@ -8,14 +8,35 @@ import os
         from deprecation import deprecated
         import pyarrow as pa
         
        +from ._lancedb import Connection as NativeConnection
         from ._lancedb import async_permutation_builder, PermutationReader
         from .table import LanceTable, Table
         from .background_loop import LOOP
        -from .util import batch_to_tensor, batch_to_tensor_dict, batch_to_tensor_rows
        +from .util import (
        +    batch_to_tensor,
        +    batch_to_tensor_columns,
        +    batch_to_tensor_dict,
        +    batch_to_tensor_rows,
        +    get_uri_scheme,
        +)
         from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union
         
         if TYPE_CHECKING:
             from lancedb.dependencies import pandas as pd, numpy as np, polars as pl
        +    from .db import DBConnection
        +
        +
        +def _native_connection(db: Any) -> Any:
        +    """Return the native connection wrapped by a sync or async connection."""
        +    async_connection = getattr(db, "_conn", None)
        +    if async_connection is not None:
        +        return _native_connection(async_connection)
        +    inner = getattr(db, "_inner", None)
        +    if inner is not None:
        +        return _native_connection(inner)
        +    if isinstance(db, NativeConnection):
        +        return db
        +    raise TypeError("db must be a LanceDB connection")
         
         
         class PermutationBuilder:
        @@ -38,7 +59,9 @@ class PermutationBuilder:
             be referenced by name in the future.  If names are not provided then they can only
             be referenced by their ordinal index.  There is no requirement to name every split.
         
        -    The permutation is stored in memory and will be lost when the program exits.
        +    The permutation is stored in memory and will be lost when the program exits,
        +    unless [persist][lancedb.permutation.PermutationBuilder.persist] is called before
        +    [execute][lancedb.permutation.PermutationBuilder.execute].
             """
         
             def __init__(self, table: Table):
        @@ -51,6 +74,9 @@ class PermutationBuilder:
                 Tables with an RTE write spec are rejected: unflushed rows have no row id.
                 """
                 self._async = async_permutation_builder(table)
        +        self._persist_connection: Optional[Any] = None
        +        self._persist_table_name: Optional[str] = None
        +        self._persist_namespace_path: list[str] = []
         
             def split_random(
                 self,
        @@ -257,6 +283,80 @@ class PermutationBuilder:
                 self._async.filter(filter)
                 return self
         
        +    def persist(
        +        self,
        +        db: "DBConnection",
        +        table_name: str,
        +        *,
        +        namespace_path: Optional[list[str]] = None,
        +        mode: Literal["create", "overwrite"] = "create",
        +    ) -> "PermutationBuilder":
        +        """
        +        Store the permutation table in an embedded database.
        +
        +        The base table can be Embedded or Enterprise; this connection is only the
        +        plan destination. Persisting a plan makes the same split available to
        +        another process or another machine with access to the destination storage.
        +        The plan is an ordinary LanceDB table containing row ids and split ids; it
        +        can be opened with [open_table][lancedb.db.DBConnection.open_table] and
        +        passed to
        +        [Permutation.from_tables][lancedb.permutation.Permutation.from_tables].
        +        The table returned by ``execute`` keeps the destination connection and
        +        namespace context, so it can be pickled and reopened directly.
        +
        +        Parameters
        +        ----------
        +        db: DBConnection
        +            An embedded LanceDB connection for the plan destination. Local files
        +            and object storage are supported. The base table may be Embedded or
        +            Enterprise; persisting the plan itself to Enterprise is not supported
        +            yet.
        +        table_name: str
        +            The name of the permutation table to create.
        +        namespace_path: list[str], optional
        +            The namespace to create the table in. The default is the root
        +            namespace.
        +        mode: {"create", "overwrite"}, default "create"
        +            ``create`` fails if the destination table already exists.
        +            ``overwrite`` writes a new version of the table. Readers that already
        +            opened the previous version keep reading that snapshot.
        +
        +        Returns
        +        -------
        +        PermutationBuilder
        +            This builder, so ``persist`` can be chained with the split, filter,
        +            and execute methods.
        +        """
        +        if mode not in ("create", "overwrite"):
        +            raise ValueError(f"Invalid mode {mode!r}; expected 'create' or 'overwrite'")
        +
        +        uri = getattr(db, "uri", None)
        +        if uri is None:
        +            raise TypeError("db must be a LanceDB connection")
        +        if get_uri_scheme(str(uri)) == "db":
        +            raise NotImplementedError(
        +                "Permutation persistence is not supported for LanceDB Enterprise "
        +                "connections yet; reproducible Enterprise plan ordering requires "
        +                "deterministic remote row ordering."
        +            )
        +
        +        if namespace_path is None:
        +            namespace_path = []
        +        elif not isinstance(namespace_path, (list, tuple)):
        +            raise TypeError("namespace_path must be a list of strings or None")
        +
        +        namespace_path = list(namespace_path)
        +        self._async.persist(
        +            _native_connection(db),
        +            table_name,
        +            namespace_path=namespace_path,
        +            mode=mode,
        +        )
        +        self._persist_connection = db
        +        self._persist_table_name = table_name
        +        self._persist_namespace_path = namespace_path
        +        return self
        +
             def execute(self) -> LanceTable:
                 """
                 Execute the configuration and create the permutation table.
        @@ -264,7 +364,14 @@ class PermutationBuilder:
         
                 async def do_execute():
                     inner_tbl = await self._async.execute()
        -            return await LanceTable.from_inner(inner_tbl)
        +            if self._persist_connection is None:
        +                return await LanceTable.from_inner(inner_tbl)
        +            return await LanceTable.from_inner(
        +                inner_tbl,
        +                connection=self._persist_connection,
        +                name=self._persist_table_name,
        +                namespace_path=self._persist_namespace_path,
        +            )
         
                 return LOOP.run(do_execute())
         
        @@ -405,11 +512,100 @@ class Transforms:
         # HuggingFace uses 10 which is pretty small
         DEFAULT_BATCH_SIZE = 100
         
        +_MAP_FORMAT_ERROR = (
        +    "map cannot be combined with with_format or with_transform; convert the "
        +    "output inside the map callback or in the DataLoader collate_fn instead"
        +)
        +
        +
        +def _map_rows(data: Any, num_rows: int) -> list[dict[str, Any]]:
        +    """Return the data flowing through a map chain as a list of row dicts."""
        +    if isinstance(data, pa.RecordBatch):
        +        return data.to_pylist()
        +    if isinstance(data, dict):
        +        return [
        +            {name: values[i] for name, values in data.items()} for i in range(num_rows)
        +        ]
        +    return data
        +
        +
        +def _map_columns(data: Any) -> dict[str, Any]:
        +    """Return the data flowing through a map chain as a dict of columns."""
        +    if isinstance(data, pa.RecordBatch):
        +        return data.to_pydict()
        +    if isinstance(data, list):
        +        names = data[0].keys()
        +        if any(row.keys() != names for row in data):
        +            raise ValueError(
        +                "Cannot pass rows to a batched map callback because the previous "
        +                "callback did not return the same keys for every row"
        +            )
        +        return {name: [row[name] for row in data] for name in names}
        +    return data
        +
        +
        +class _MapTransform:
        +    """
        +    The transform installed by [map][lancedb.permutation.Permutation.map]
        +
        +    Each step is a ``(fn, batched)`` pair.  This is a module-level class, and not a
        +    closure, so that a mapped permutation pickles whenever its callbacks do.
        +    """
        +
        +    def __init__(self, steps: tuple[tuple[Callable, bool], ...]):
        +        self.steps = steps
        +
        +    def __call__(self, batch: pa.RecordBatch) -> list[dict[str, Any]]:
        +        num_rows = batch.num_rows
        +        if num_rows == 0:
        +            return []
        +
        +        # The layout is only converted when a callback needs the other one
        +        data = batch
        +        for fn, batched in self.steps:
        +            if batched:
        +                data = fn(_map_columns(data))
        +                if not isinstance(data, dict):
        +                    raise TypeError(
        +                        "A batched map callback must return a dict of columns, "
        +                        f"got {type(data).__name__}"
        +                    )
        +                for name, values in data.items():
        +                    # A str or dict can be indexed but is not a column of values
        +                    if isinstance(values, (str, bytes, dict)) or not hasattr(
        +                        values, "__getitem__"
        +                    ):
        +                        raise TypeError(
        +                            "A batched map callback must return a list of values "
        +                            f"for column `{name}`, got {type(values).__name__}"
        +                        )
        +                    if len(values) != num_rows:
        +                        raise ValueError(
        +                            f"A batched map callback returned {len(values)} values "
        +                            f"for column `{name}` but the batch has {num_rows} rows"
        +                        )
        +            else:
        +                data = [fn(row) for row in _map_rows(data, num_rows)]
        +                for row in data:
        +                    if not isinstance(row, dict):
        +                        raise TypeError(
        +                            "A map callback must return a dict for each row, "
        +                            f"got {type(row).__name__}"
        +                        )
        +        return _map_rows(data, num_rows)
        +
        +
        +def _is_persisted_plan(table: Table) -> bool:
        +    """Whether a permutation table lives in reopenable storage rather than memory."""
        +    return isinstance(table, LanceTable) and not table._conn.uri.startswith("memory://")
        +
         
         def _table_to_pickle_state(table: Table) -> dict[str, Any]:
             from .remote.table import RemoteTable
         
             if isinstance(table, RemoteTable):
        +        # RemoteTable already owns its reopen state; keep the table object so
        +        # pickle delegates to its __getstate__ without duplicating the fields.
                 return {
                     "kind": "remote",
                     "table": table,
        @@ -418,20 +614,15 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]:
             if not isinstance(table, LanceTable):
                 raise ValueError(f"Cannot pickle table of type {type(table)!r}")
         
        -    base_uri = table._conn.uri
        -    if base_uri.startswith("memory://"):
        +    state = table.__getstate__()
        +    if state.get("kind") == "memory":
                 return {
                     "kind": "memory",
        -            "name": table.name,
        -            "data": table.to_arrow(),
        +            "state": state,
                 }
        -
             return {
        -        "kind": "local",
        -        "name": table.name,
        -        "uri": base_uri,
        -        "namespace": table._namespace_path,
        -        "storage_options": table._conn.storage_options,
        +        "kind": "lance",
        +        "state": state,
             }
         
         
        @@ -444,13 +635,25 @@ def _drop_base_version(permutation_data: pa.Table) -> pa.Table:
             return permutation_data.replace_schema_metadata(metadata)
         
         
        +def _lance_table_from_pickle_state(state: dict[str, Any]) -> LanceTable:
        +    table = LanceTable.__new__(LanceTable)
        +    table.__setstate__(state)
        +    return table
        +
        +
         def _table_from_pickle_state(state: dict[str, Any]) -> Table:
             from . import connect
         
             kind = state["kind"]
             if kind == "remote":
                 return state["table"]
        +    if kind == "lance":
        +        return _lance_table_from_pickle_state(state["state"])
             if kind == "memory":
        +        if "state" in state:
        +            return _lance_table_from_pickle_state(state["state"])
        +        # Backward compatibility for pickles written before tables carried
        +        # their own state.
                 return connect("memory://").create_table(state["name"], state["data"])
             if kind == "local":
                 db = connect(state["uri"], storage_options=state["storage_options"])
        @@ -483,6 +686,9 @@ class Permutation:
                 limit: Optional[int] = None,
                 connection_factory: Optional[Callable[[str], Table]] = None,
                 _reader: Optional[PermutationReader] = None,
        +        _plan_metadata: Optional[dict[bytes, bytes]] = None,
        +        _plan_version: Optional[int] = None,
        +        _plan_branch: Optional[str] = None,
             ):
                 """
                 Internal constructor.  Use
        @@ -495,10 +701,16 @@ class Permutation:
                 self.split = split
                 self.selection = selection
                 self.transform_fn = transform_fn
        +        # Whether the default transform was replaced, by with_format, by
        +        # with_transform, or by a caller passing its own transform here
        +        self._explicit_transform = transform_fn is not Transforms.arrow2python
                 self.batch_size = batch_size
                 self.offset = offset
                 self.limit = limit
                 self.connection_factory = connection_factory
        +        self._plan_metadata = _plan_metadata
        +        self._plan_version = _plan_version
        +        self._plan_branch = _plan_branch
                 if _reader is None:
                     _reader = LOOP.run(self._build_reader())
                 self.reader: PermutationReader = _reader
        @@ -638,6 +850,17 @@ class Permutation:
                 then the first split will be used.
                 """
                 assert base_table is not None, "base_table is required"
        +        persisted_plan = permutation_table is not None and _is_persisted_plan(
        +            permutation_table
        +        )
        +        if persisted_plan:
        +            # Pin before reading metadata or constructing the reader. The caller's
        +            # handle may keep tracking latest, but the live reader and pickle must
        +            # share one immutable plan snapshot.
        +            permutation_table = permutation_table._pin_current_snapshot()
        +        plan_metadata = None if permutation_table is not None else {}
        +        if permutation_table is not None and (isinstance(split, str) or persisted_plan):
        +            plan_metadata = dict(permutation_table.schema.metadata or {})
                 if split is not None:
                     if permutation_table is None:
                         raise ValueError(
        @@ -645,12 +868,7 @@ class Permutation:
                             " because no permutation table is provided"
                         )
                     if isinstance(split, str):
        -                if permutation_table.schema.metadata is None:
        -                    raise ValueError(
        -                        f"Cannot create a permutation on split `{split}`"
        -                        " because no split names are defined in the permutation table"
        -                    )
        -                raw = permutation_table.schema.metadata.get(b"split_names")
        +                raw = (plan_metadata or {}).get(b"split_names")
                         split_names = raw.decode("utf-8") if raw is not None else None
                         if split_names is None:
                             raise ValueError(
        @@ -673,6 +891,14 @@ class Permutation:
                 else:
                     split = 0
         
        +        plan_version = None
        +        plan_branch = None
        +        if persisted_plan:
        +            # Pin the pickled plan to the snapshot this object was created from,
        +            # not what the destination name points at after an overwrite.
        +            plan_version = permutation_table.version
        +            plan_branch = permutation_table.current_branch()
        +
                 async def do_from_tables():
                     reader = await PermutationReader.from_tables(
                         base_table, permutation_table, split
        @@ -687,6 +913,9 @@ class Permutation:
                         DEFAULT_BATCH_SIZE,
                         Transforms.arrow2python,
                         _reader=reader,
        +                _plan_metadata=plan_metadata,
        +                _plan_version=plan_version,
        +                _plan_branch=plan_branch,
                     )
         
                 return LOOP.run(do_from_tables())
        @@ -696,37 +925,59 @@ class Permutation:
         
                 The base table is captured either via a user-supplied
                 ``connection_factory`` (see [with_connection_factory]) or, as a
        -        fallback, by the table's own picklable reopen state. The permutation
        -        table is captured as a pyarrow Table (which pickles via Arrow IPC
        -        natively). The reader is dropped from the wire format and rebuilt
        -        lazily on first use.
        +        fallback, by the table's own picklable reopen state. A permutation
        +        table in memory is captured as a pyarrow Table (which pickles via Arrow
        +        IPC natively). A persisted plan is reopened by reference and pinned to
        +        the plan snapshot this object was built from. The reader is dropped
        +        from the wire format and rebuilt lazily on first use.
                 """
        +        base_table_state = (
        +            None
        +            if self.connection_factory is not None
        +            else _table_to_pickle_state(self.base_table)
        +        )
        +        base_is_memory = (
        +            base_table_state is not None and base_table_state["kind"] == "memory"
        +        )
        +
                 permutation_data: Optional[pa.Table] = None
        -        if self.permutation_table is not None:
        +        permutation_table_state: Optional[dict[str, Any]] = None
        +        if (
        +            self.permutation_table is not None
        +            and _is_persisted_plan(self.permutation_table)
        +            and not base_is_memory
        +        ):
        +            plan_state = _table_to_pickle_state(self.permutation_table)
        +            # Keep the plan's own branch/version coordinate. A later overwrite
        +            # of the destination must not change what this pickle reads.
        +            table_state = plan_state["state"]
        +            if self._plan_version is not None:
        +                table_state["checkout_version"] = self._plan_version
        +                # None is the main branch. Restore it explicitly because the
        +                # live handle may have moved to another branch since capture.
        +                table_state["branch"] = self._plan_branch
        +            permutation_table_state = plan_state
        +        elif self.permutation_table is not None:
                     permutation_data = self.permutation_table.to_arrow()
         
                 common = {
                     "base_table_name": self.base_table.name,
        -            "permutation_data": permutation_data,
                     "split": self.split,
                     "selection": self.selection,
                     "batch_size": self.batch_size,
                     "transform_fn": self.transform_fn,
        +            "explicit_transform": self._explicit_transform,
                     "offset": self.offset,
                     "limit": self.limit,
                     "connection_factory": self.connection_factory,
                 }
        -
        -        if self.connection_factory is not None:
        -            # The factory carries enough state to recover the base table on
        -            # its own; we don't need to capture the URI / storage options /
        -            # namespace from the existing connection.
        -            return common
        -
        -        return {
        -            **common,
        -            "base_table_state": _table_to_pickle_state(self.base_table),
        -        }
        +        if permutation_table_state is not None:
        +            common["permutation_table_state"] = permutation_table_state
        +        else:
        +            common["permutation_data"] = permutation_data
        +        if base_table_state is not None:
        +            common["base_table_state"] = base_table_state
        +        return common
         
             def __setstate__(self, state: dict[str, Any]) -> None:
                 from . import connect
        @@ -758,27 +1009,99 @@ class Permutation:
                     )
         
                 permutation_table: Optional[Table] = None
        -        permutation_data = state["permutation_data"]
        -        if permutation_data is not None:
        -            if rebuilt_base:
        -                # The base table was materialized from Arrow, so it is a fresh
        -                # single-version dataset and the recorded pin cannot resolve on it.
        -                permutation_data = _drop_base_version(permutation_data)
        -            mem_db = connect("memory://")
        -            permutation_table = mem_db.create_table("permutation", permutation_data)
        +        plan_metadata: dict[bytes, bytes] = {}
        +        plan_version = None
        +        plan_branch = None
        +        if "permutation_table_state" in state:
        +            plan_state = state["permutation_table_state"]
        +            permutation_table = _table_from_pickle_state(plan_state)
        +            nested_state = plan_state.get("state", {})
        +            plan_version = nested_state.get("checkout_version")
        +            plan_branch = nested_state.get("branch")
        +            plan_metadata = dict(permutation_table.schema.metadata or {})
        +        else:
        +            permutation_data = state.get("permutation_data")
        +            if permutation_data is not None:
        +                if rebuilt_base:
        +                    # The base table was materialized from Arrow, so it is a fresh
        +                    # single-version dataset and the recorded pin cannot resolve on it.
        +                    permutation_data = _drop_base_version(permutation_data)
        +                mem_db = connect("memory://")
        +                permutation_table = mem_db.create_table("permutation", permutation_data)
        +                plan_metadata = dict(permutation_table.schema.metadata or {})
         
                 self.base_table = base_table
                 self.permutation_table = permutation_table
        +        self._plan_metadata = plan_metadata
        +        self._plan_version = plan_version
        +        self._plan_branch = plan_branch
                 self.split = state["split"]
                 self.selection = state["selection"]
                 self.batch_size = state["batch_size"]
                 self.transform_fn = state["transform_fn"]
        +        # Pickles written before this flag existed still carry their transform.
        +        # Anything but the default must have been set explicitly.
        +        self._explicit_transform = state.get(
        +            "explicit_transform", self.transform_fn is not Transforms.arrow2python
        +        )
                 self.offset = state["offset"]
                 self.limit = state["limit"]
                 self.connection_factory = connection_factory
                 self.reader = None
                 self._pid = None
         
        +    def __copy__(self) -> "Permutation":
        +        """Return a shallow copy without going through the pickle path.
        +
        +        The ``with_*`` builders use ``copy.copy`` to derive a new permutation.
        +        The default copy protocol would use ``__getstate__``/``__setstate__``,
        +        which materializes the permutation table with ``to_arrow()`` (not
        +        supported for remote tables) and rebuilds the base table and reader.
        +        A shallow copy instead keeps the existing table handles and reader;
        +        the caller replaces only the attribute it is changing.
        +        """
        +        new = self.__class__.__new__(self.__class__)
        +        new.__dict__ = self.__dict__.copy()
        +        return new
        +
        +    def _loaded_plan_metadata(self) -> dict[bytes, bytes]:
        +        if self._plan_metadata is None:
        +            self._plan_metadata = (
        +                dict(self.permutation_table.schema.metadata or {})
        +                if self.permutation_table is not None
        +                else {}
        +            )
        +        return self._plan_metadata
        +
        +    @property
        +    def base_version(self) -> Optional[int]:
        +        """The base table version recorded in the plan, or ``None`` for legacy plans.
        +
        +        This value comes from the plan's schema metadata, so reading it does not
        +        query the base table. Version numbers are per-branch; see
        +        [base_branch][lancedb.permutation.Permutation.base_branch].
        +        """
        +        raw = self._loaded_plan_metadata().get(b"base_version")
        +        if raw is None:
        +            return None
        +        try:
        +            return int(raw)
        +        except ValueError as error:
        +            raise ValueError(
        +                f"Permutation table has an unreadable base_version of {raw!r}"
        +            ) from error
        +
        +    @property
        +    def base_branch(self) -> Optional[str]:
        +        """The base table branch recorded in the plan, or ``None`` for main.
        +
        +        Legacy plans recorded no branch and therefore also return ``None``.
        +        """
        +        raw = self._loaded_plan_metadata().get(b"base_branch")
        +        if raw is None:
        +            return None
        +        return raw.decode("utf-8")
        +
             def _ensure_open(self) -> None:
                 pid = os.getpid()
                 if self.reader is not None and getattr(self, "_pid", None) == pid:
        @@ -1008,6 +1331,7 @@ class Permutation:
                     "pandas",
                     "arrow",
                     "torch",
        +            "torch_dict",
                     "torch_row",
                     "torch_col",
                     "polars",
        @@ -1019,34 +1343,68 @@ class Permutation:
                 If this method is not called, the "python" format will be used.
         
                 The format can be one of:
        -        - "numpy" - the batch will be a dict of numpy arrays (one per column)
        +        - "numpy" - a single NumPy ndarray built with
        +          ``batch.to_pandas().to_numpy()``. This conversion may copy data and
        +          may promote mixed numeric columns to a common numeric dtype, for
        +          example int64 and float32 to float64. Nested or incompatible columns
        +          produce an object array.
                 - "python" - the batch will be a list of dicts (one per row)
                 - "python_col" - the batch will be a dict of lists (one entry per column)
                 - "pandas" - the batch will be a pandas DataFrame
                 - "arrow" - the batch will be a pyarrow RecordBatch
        -        - "torch" - the batch will be a list of per-row dicts mapping column
        -          name to a 0-D torch tensor. Works with the default
        -          ``torch.utils.data.DataLoader`` collate, which stacks the per-row
        -          dicts back into a dict of batched tensors.
        -        - "torch_row" - the batch will be a list of tensors, one per row
        -        - "torch_col" - the batch will be a 2D torch tensor (first dim indexes columns)
        +        - "torch" - a list of per-row dicts mapping column names to tensors with
        +          shape ``(*S)``. The default DataLoader collate stacks these into a
        +          dict of ``(B, *S)`` tensors.
        +        - "torch_dict" - a dict mapping each column name to one tensor with
        +          shape ``(B, *S)``. Columns may have different sample shapes ``S``.
        +          Use an identity collate to consume the batch directly. Tensors share
        +          Arrow storage where the layout allows.
        +        - "torch_row" - a list of per-row tensors with shape ``(C, *S)``. All
        +          columns must have the same sample shape ``S``. A single scalar column
        +          produces ``(1,)`` tensors. Numeric dtypes are combined with
        +          ``torch.promote_types``.
        +        - "torch_col" - one tensor with shape ``(C, B, *S)``. All columns must
        +          have the same sample shape ``S``. For one column this is an
        +          ``unsqueeze(0)`` view of the column tensor.
                 - "polars" - the batch will be a polars DataFrame
         
        -        Conversion may or may not involve a data copy.  Lance uses Arrow internally
        -        and so it is able to zero-copy to the arrow and polars formats.
        +        For torch formats, ``S`` is the shape of one sample. Scalar columns have
        +        ``S = ()``. A fixed-size-list column of width ``D`` contributes a
        +        dimension ``D``, and nested fixed-size lists contribute one dimension
        +        per level. Fixed-shape tensors use their logical shape, including any
        +        axis permutation. "torch_dict", "torch", and "torch_col" reject nulls;
        +        use the "python" or "arrow" format for nullable columns. "torch_row"
        +        preserves the previous NaN behavior for nullable scalar integer and
        +        floating columns, but rejects nulls in nested fixed-size-list and tensor
        +        columns.
         
        -        Conversion to torch and torch_col will be zero-copy but will only support a
        -        subset of data types (numeric types).
        +        ``lance.bfloat16`` values become ``torch.bfloat16`` tensors when the
        +        leaf field is ``fixed_size_binary[2]`` and carries the
        +        ``ARROW:extension:name`` metadata value ``lance.bfloat16``. Unmarked
        +        binary columns are rejected.
         
        -        Conversion to numpy and/or pandas will typically be zero-copy for numeric
        -        types.  Conversion of strings, lists, and structs will require creating python
        -        objects and this is not zero-copy.
        +        Conversion may or may not involve a data copy. Lance uses Arrow
        +        internally and can zero-copy to the arrow and polars formats.
        +        "torch_dict", "torch", and a single-column "torch_col" produce
        +        numeric and fixed-size-list tensors without copying where the Arrow
        +        layout allows. Multi-column "torch_col" and "torch_row" stack columns
        +        and therefore copy. Conversion to numpy and/or pandas can copy even
        +        homogeneous numeric columns. Conversion of strings, lists, and structs
        +        will require creating Python objects and this is not zero-copy.
         
                 For custom formatting, use
                 [with_transform][lancedb.permutation.Permutation.with_transform] which
                 overrides this method.
        +
        +        A format cannot be combined with
        +        [map][lancedb.permutation.Permutation.map], which always yields a list
        +        of dicts.  Doing so raises a ValueError.
                 """
                 assert format is not None, "format is required"
        +        # Checked before with_transform does, so that a format with an optional
        +        # dependency cannot fail on its import first
        +        if isinstance(self.transform_fn, _MapTransform):
        +            raise ValueError(_MAP_FORMAT_ERROR)
                 if format == "python":
                     return self.with_transform(Transforms.arrow2python)
                 if format == "python_col":
        @@ -1059,6 +1417,8 @@ class Permutation:
                     return self.with_transform(Transforms.arrow2arrow)
                 elif format == "torch":
                     return self.with_transform(batch_to_tensor_dict)
        +        elif format == "torch_dict":
        +            return self.with_transform(batch_to_tensor_columns)
                 elif format == "torch_row":
                     return self.with_transform(batch_to_tensor_rows)
                 elif format == "torch_col":
        @@ -1077,10 +1437,109 @@ class Permutation:
         
                 Note: transforms are not invoked in parallel.  This method is not a good place
                 for expensive operations such as image decoding.
        +
        +        For a higher-level API that works with Python dicts, see
        +        [map][lancedb.permutation.Permutation.map].  A transform cannot be combined
        +        with ``map``.  Doing so raises a ValueError.
                 """
                 assert transform is not None, "transform is required"
        +        if isinstance(self.transform_fn, _MapTransform):
        +            raise ValueError(_MAP_FORMAT_ERROR)
                 new = copy.copy(self)
                 new.transform_fn = transform
        +        new._explicit_transform = True
        +        return new
        +
        +    def map(
        +        self,
        +        fn: Callable[[dict[str, Any]], dict[str, Any]],
        +        *,
        +        batched: bool = False,
        +    ) -> "Permutation":
        +        """
        +        Apply a function to the rows of the permutation
        +
        +        This is a dict-based alternative to
        +        [with_transform][lancedb.permutation.Permutation.with_transform], loosely
        +        modeled after the huggingface ``Dataset.map``.  It is lazy: ``fn`` is not
        +        called until data is read.
        +
        +        Calls to ``map`` can be chained.  The callbacks run in order and the dict
        +        returned by a callback replaces the row entirely, so the next callback only
        +        sees what the previous one returned.  Unlike the huggingface method, the
        +        returned dict is not merged into the row: return every column to keep.
        +
        +        A mapped permutation always yields a list of dicts (one per row) for each
        +        batch, which is the same shape as the default "python" format.  ``batched``
        +        only controls what ``fn`` receives.  Rows keep their position, so a callback
        +        cannot add, drop, or reorder rows.
        +
        +        Since ``map`` decides the output format it cannot be combined with
        +        [with_format][lancedb.permutation.Permutation.with_format] or
        +        [with_transform][lancedb.permutation.Permutation.with_transform].  Calling
        +        one after the other, in either order, raises a ValueError.  Convert the
        +        mapped rows to tensors in the DataLoader ``collate_fn`` instead.
        +
        +        [select_columns][lancedb.permutation.Permutation.select_columns],
        +        [remove_columns][lancedb.permutation.Permutation.remove_columns],
        +        [rename_column][lancedb.permutation.Permutation.rename_column] and
        +        [schema][lancedb.permutation.Permutation.schema] describe the columns read
        +        from the base table, which are the input of the first callback.  They do
        +        not describe the output of ``map``, whether they are used before or after it.
        +
        +        Parameters
        +        ----------
        +        fn: Callable
        +            The function to apply.  It receives and returns a single row as a dict
        +            mapping column names to values.  If ``batched`` is True it instead
        +            receives and returns a whole batch as a dict mapping column names to
        +            lists of values, and every returned column must have one value per
        +            input row.
        +
        +            DataLoader workers started with ``spawn`` or ``forkserver`` receive a
        +            pickled copy of the permutation, so ``fn`` must then be picklable.
        +            Use a top-level function; lambdas and local functions do not pickle.
        +        batched: bool, default False
        +            Whether ``fn`` is called once per batch instead of once per row.
        +
        +        Examples
        +        --------
        +        >>> import lancedb
        +        >>> db = lancedb.connect("memory:///")
        +        >>> tbl = db.create_table("tbl", data=[{"x": x} for x in range(3)])
        +        >>> def add_y(row):
        +        ...     return {**row, "y": row["x"] * 2}
        +        >>> def add_z(batch):
        +        ...     return {**batch, "z": [x + y for x, y in zip(batch["x"], batch["y"])]}
        +        >>> permutation = Permutation.identity(tbl).map(add_y).map(add_z, batched=True)
        +        >>> permutation.take_offsets([0, 1])
        +        [{'x': 0, 'y': 0, 'z': 0}, {'x': 1, 'y': 2, 'z': 3}]
        +
        +        With a PyTorch DataLoader, a ``collate_fn`` turns the mapped rows of each
        +        batch into tensors::
        +
        +            import torch
        +
        +            def collate(rows):
        +                return {
        +                    "x": torch.tensor([row["x"] for row in rows]),
        +                    "z": torch.tensor([row["z"] for row in rows]),
        +                }
        +
        +            dataloader = torch.utils.data.DataLoader(
        +                permutation, batch_size=32, shuffle=True, collate_fn=collate
        +            )
        +        """
        +        if not callable(fn):
        +            raise TypeError("fn must be callable")
        +        if self._explicit_transform:
        +            raise ValueError(_MAP_FORMAT_ERROR)
        +
        +        steps = ((fn, batched),)
        +        if isinstance(self.transform_fn, _MapTransform):
        +            steps = self.transform_fn.steps + steps
        +        new = copy.copy(self)
        +        new.transform_fn = _MapTransform(steps)
                 return new
         
             def take_offsets(self, offsets: list[int]) -> Any:
        @@ -1088,8 +1547,8 @@ class Permutation:
                 Take rows from the permutation by offset
         
                 The returned value is passed through the permutation's current transform,
        -        so `with_format` and `with_transform` affect this method in the same way
        -        they affect iteration.
        +        so `with_format`, `with_transform`, and `map` affect this method in the
        +        same way they affect iteration.
                 """
                 self._ensure_open()
         
        diff --git a/python/python/lancedb/prewarm.py b/python/python/lancedb/prewarm.py
        new file mode 100644
        index 000000000..441f40d6d
        --- /dev/null
        +++ b/python/python/lancedb/prewarm.py
        @@ -0,0 +1,75 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +"""Typed metadata previews and results of data-cache prewarm jobs."""
        +
        +from dataclasses import dataclass, fields
        +import json
        +from typing import Optional
        +
        +
        +@dataclass(frozen=True)
        +class PrewarmDataResult:
        +    """Reported executor work for a pinned snapshot, not guaranteed cache residency.
        +
        +    Counts omitted by older workers remain None. I/O counts are unknown when
        +    executors do not report them. Partial completions are a subset of completed
        +    executors and may reflect cache pressure.
        +    """
        +
        +    table_version: int
        +    executors_targeted: Optional[int] = None
        +    executors_completed: Optional[int] = None
        +    executors_partial: Optional[int] = None
        +    fragments_selected: Optional[int] = None
        +    ranges_completed: Optional[int] = None
        +    bytes_read: Optional[int] = None
        +
        +    @classmethod
        +    def from_json(cls, raw: str) -> "PrewarmDataResult":
        +        value = json.loads(raw)
        +        names = {field.name for field in fields(cls)}
        +        return cls(**{key: item for key, item in value.items() if key in names})
        +
        +
        +@dataclass(frozen=True)
        +class PrewarmPruningSummary:
        +    """Conservative metadata pruning; selected ranges are not exact row matches.
        +
        +    ``mode`` is a server-reported string, including future pruning modes.
        +    Unknown interval counts and fallback reasons remain None.
        +    """
        +
        +    mode: str
        +    input_fragments: int
        +    selected_fragments: int
        +    pruned_fragments: int
        +    selected_row_ranges: Optional[int] = None
        +    fallback_reason: Optional[str] = None
        +
        +
        +@dataclass(frozen=True)
        +class PrewarmDataPlan:
        +    """Metadata-only preview for a snapshot, without a warming job.
        +
        +    A later submission chooses its own snapshot and can produce a different
        +    plan. ``plan`` is readable display text; use ``pruning`` for structured facts.
        +    """
        +
        +    table_version: int
        +    plan: str
        +    pruning: PrewarmPruningSummary
        +
        +    @classmethod
        +    def from_json(cls, raw: str) -> "PrewarmDataPlan":
        +        # The native SDK validates the wire format before returning this value.
        +        value = json.loads(raw)
        +        summary = value["pruning"]
        +        names = {field.name for field in fields(PrewarmPruningSummary)}
        +        return cls(
        +            table_version=value["table_version"],
        +            plan=value["plan"],
        +            pruning=PrewarmPruningSummary(
        +                **{key: item for key, item in summary.items() if key in names}
        +            ),
        +        )
        diff --git a/python/python/lancedb/profiling.py b/python/python/lancedb/profiling.py
        new file mode 100644
        index 000000000..5534f9e53
        --- /dev/null
        +++ b/python/python/lancedb/profiling.py
        @@ -0,0 +1,49 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +"""Typed snapshots of on-demand Enterprise Function worker captures."""
        +
        +import json
        +from dataclasses import dataclass
        +from typing import Literal, Optional
        +
        +FunctionProfileKind = Literal["cpu", "gpu", "memory"]
        +FunctionProfileStatus = Literal["pending", "capturing", "complete", "failed"]
        +
        +__all__ = ["FunctionProfile", "FunctionProfileKind", "FunctionProfileStatus"]
        +
        +
        +@dataclass(frozen=True)
        +class FunctionProfile:
        +    """A capture's identity, current status and artifact retention bounds.
        +
        +    Retain ``profile_id`` to retrieve the capture through the parent Job,
        +    including after its refresh completes. ``status`` and ``error`` describe
        +    the capture independently of the parent refresh job. Timestamp fields are
        +    milliseconds since the Unix epoch. ``expires_at_millis`` is an upper bound:
        +    the server may reclaim job scratch or evict an older capture sooner.
        +
        +    CPU evidence contains Python stacks weighted by thread CPU time. Memory
        +    evidence contains Python allocations made during capture and retained at
        +    its end. GPU evidence contains PyTorch CUDA activities; it excludes Python
        +    operator attribution and GPU allocation stacks.
        +    """
        +
        +    profile_id: str
        +    job_id: str
        +    worker_id: str
        +    execution_epoch: int
        +    session_slot: int
        +    kind: FunctionProfileKind
        +    duration_seconds: float
        +    status: FunctionProfileStatus
        +    requested_at_millis: int
        +    deadline_at_millis: int
        +    expires_at_millis: int
        +    completed_at_millis: Optional[int] = None
        +    error: Optional[str] = None
        +    artifact_id: Optional[str] = None
        +
        +    @classmethod
        +    def _from_json(cls, value: str) -> "FunctionProfile":
        +        return cls(**json.loads(value))
        diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py
        index 5185bf2a8..650584d46 100644
        --- a/python/python/lancedb/query.py
        +++ b/python/python/lancedb/query.py
        @@ -41,26 +41,28 @@ from .rerankers.base import Reranker
         from .rerankers.rrf import RRFReranker
         from .rerankers.util import check_reranker_result
         from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field
        -from .util import _validate_query_vector, flatten_columns, get_uri_scheme
        +from .util import _validate_query_vector, add_note, flatten_columns, get_uri_scheme
         from . import _wal_hybrid  # WAL-PK-FUSION: delete.
         from ._blob import (
             BLOB_MODE_TO_HANDLING,
             FetchBlobsAsync,
             FetchBlobsSync,
        +    _remote_blob_snapshot,
             blob_auto_row_id_for_scan,
        +    blob_projection_sources,
             blob_v2_projection_sources,
             finalize_blob_query_table,
             reject_unfetchable_blob_columns,
             reject_unmatched_blob_outputs,
        -    replace_v2_blob_columns_with_bytes,
        -    replace_v2_blob_columns_with_bytes_sync,
        +    replace_blob_columns_with_bytes,
        +    replace_blob_columns_with_bytes_sync,
             strip_auto_row_ids,
             validate_blob_mode,
         )
         from .types import BlobMode, QueryProjection
         
         if TYPE_CHECKING:
        -    import sys
        +    from typing import Self
         
             import PIL
             import polars as pl
        @@ -75,11 +77,6 @@ if TYPE_CHECKING:
             from .pydantic import LanceModel
             from .table import AsyncTable, Table
         
        -    if sys.version_info >= (3, 11):
        -        from typing import Self
        -    else:
        -        from typing_extensions import Self
        -
         T = TypeVar("T", bound="LanceModel")
         
         
        @@ -193,20 +190,41 @@ def _unsupported_blob_pandas_error(reason: str) -> RuntimeError:
             )
         
         
        -def _supports_local_blob_fetch(
        +def _supports_blob_fetch(
             async_table: "AsyncTable", pushdown_operations: Iterable[str]
         ) -> bool:
        -    # Remote tables and QueryTable pushdown answer queries on a server, so a
        -    # fetch through this handle could read another version.
        -    return async_table._inner._is_native() and "QueryTable" not in pushdown_operations
        +    # Remote queries carry their producing snapshot in response metadata.
        +    # Namespace QueryTable pushdown has no equivalent snapshot contract.
        +    return (
        +        not async_table._inner._is_native() or "QueryTable" not in pushdown_operations
        +    )
        +
        +
        +def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table:
        +    """Preserve a snapshot only when every query leg used the same identity."""
        +    keys = (b"lancedb:query_version", b"lancedb:query_snapshot")
        +    snapshots = {
        +        tuple((source.schema.metadata or {}).get(key) for key in keys)
        +        for source in sources
        +    }
        +    metadata = dict(result.schema.metadata or {})
        +    for key in keys:
        +        metadata.pop(key, None)
        +    snapshot = next(iter(snapshots)) if len(snapshots) == 1 else None
        +    if snapshot is not None and all(value is not None for value in snapshot):
        +        metadata.update(zip(keys, snapshot))
        +    return result.replace_schema_metadata(metadata)
         
         
         def _blob_bytes_without_snapshot_error() -> NotImplementedError:
             return NotImplementedError(
                 "blob_mode='bytes' cannot safely materialize blob columns without a "
        -        "stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown "
        -        "run the query on a server, so the blob fetch could read another table "
        -        "version. Use blob_mode='descriptions'."
        +        "stable table snapshot. Namespace QueryTable pushdown does not bind "
        +        "the query and blob fetches to one table version. "
        +        "Use blob_mode='descriptions' to inspect descriptors. To read "
        +        "payloads, select row IDs with with_row_id(True), then call "
        +        "table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, "
        +        "row_ids). Keep the source unchanged between selection and fetching."
             )
         
         
        @@ -231,16 +249,46 @@ def _query_needs_lance_scanner(builder: Any) -> bool:
             )
         
         
        +def _raise_unsupported_fragment_constraints(
        +    fragments: Optional[Any],
        +    fragment_ids: Optional[List[int]],
        +    *,
        +    operation: str,
        +) -> None:
        +    """Reject fragment selection where execution would silently scan everything."""
        +    if fragments is None and fragment_ids is None:
        +        return
        +    raise NotImplementedError(
        +        "with_fragments() and fragment_ids() are only supported for embedded "
        +        "plain-scan blob queries executed through to_pandas(). "
        +        f"{operation} would ignore the fragment selection and scan the full "
        +        "table. Remove the fragment constraint, or use table.to_lance() with "
        +        "a Lance scanner for this query shape."
        +    )
        +
        +
         def _query_is_plain_scan(query: Query) -> bool:
             return (
                 query.vector is None
                 and query.full_text_query is None
                 and query.take_offsets is None
        +        and query.take_row_ids is None
                 and not query.postfilter
                 and not query.order_by
             )
         
         
        +def _query_is_plain_blob_scan(query: Query) -> bool:
        +    """Whether native batch conversion can preserve this query's row result."""
        +    return (
        +        query.vector is None
        +        and query.full_text_query is None
        +        and query.take_offsets is None
        +        and query.take_row_ids is None
        +        and not query.postfilter
        +    )
        +
        +
         def _filter_to_sql(filter: Optional[Union[str, Expr]]) -> Optional[str]:
             if filter is None:
                 return None
        @@ -318,6 +366,10 @@ def _scanner_kwargs_for_query(
                 "with_row_id": with_row_id if with_row_id is not None else query.with_row_id,
                 "with_row_address": query.with_row_address,
                 "fast_search": query.fast_search,
        +        "scan_in_order": query.scan_in_order,
        +        # Legacy scalar-index plans can reorder rows. Explicit storage order
        +        # evaluates filters over the manifest-ordered scan instead.
        +        "use_scalar_index": False if query.scan_in_order is True else None,
                 "blob_handling": BLOB_MODE_TO_HANDLING[blob_mode],
                 "fragments": fragments,
             }
        @@ -328,6 +380,12 @@ def _scanner_fragments_for_query(query: Query, dataset: Optional[Any]) -> Option
             if query.fragments is not None and query.fragment_ids is not None:
                 raise ValueError("fragments and fragment_ids cannot both be set")
             if query.fragments is not None:
        +        if query.scan_in_order is True:
        +            raise ValueError(
        +                "scan_in_order(True) cannot validate with_fragments() against "
        +                "the scanned dataset version; use fragment_ids() to select "
        +                "fragments by manifest id"
        +            )
                 return query.fragments
             if query.fragment_ids is None:
                 return None
        @@ -417,7 +475,7 @@ def _finish_plain_scan_pandas(
         ) -> pd.DataFrame:
             if blob_sources:
                 tbl = _scanner_to_table(scanner)
        -        tbl = replace_v2_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
        +        tbl = replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
                 if strip_auto_row_id and "_rowid" in tbl.column_names:
                     tbl = tbl.drop_columns(["_rowid"])
                 if flatten is not None:
        @@ -452,7 +510,10 @@ def _finish_remote_pandas(
             raise NotImplementedError(
                 f"remote to_pandas(blob_mode={blob_mode!r}) cannot safely materialize "
                 "blob columns without a stable table snapshot; "
        -        "use blob_mode='descriptions'"
        +        "use blob_mode='descriptions' to inspect descriptors. To read payloads, "
        +        "select row IDs with with_row_id(True), then call "
        +        "table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, "
        +        "row_ids). Keep the source unchanged between selection and fetching."
             )
         
         
        @@ -468,7 +529,7 @@ async def _finish_plain_scan_pandas_async(
         ) -> pd.DataFrame:
             if blob_sources:
                 tbl = _scanner_to_table(scanner)
        -        tbl = await replace_v2_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
        +        tbl = await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
                 if strip_auto_row_id and "_rowid" in tbl.column_names:
                     tbl = tbl.drop_columns(["_rowid"])
                 if flatten is not None:
        @@ -514,11 +575,107 @@ def ensure_vector_query(
         
         
         class ColumnOrdering(pydantic.BaseModel):
        +    """A single sort key for ``order_by``.
        +
        +    Attributes
        +    ----------
        +    column_name: str
        +        The column to sort by.
        +    ascending: bool, default True
        +        Sort ascending when true, descending otherwise.
        +    nulls_first: bool, default False
        +        Place null values before non-null values when true.
        +    """
        +
             column_name: str
             ascending: bool = True
             nulls_first: bool = False
         
         
        +_OrderingItem = Union[str, Tuple[str, str], ColumnOrdering, Dict[str, Any]]
        +_OrderingInput = Optional[Union[_OrderingItem, List[_OrderingItem]]]
        +_COLUMN_ORDERING_KEYS = frozenset({"column_name", "ascending", "nulls_first"})
        +_ORDERING_EXAMPLE = '[{"column_name": "uris", "ascending": True}]'
        +
        +
        +def _normalize_ordering(ordering: _OrderingInput) -> Optional[List[ColumnOrdering]]:
        +    """Normalize the accepted ``order_by`` inputs into ``ColumnOrdering`` models.
        +
        +    ``None`` and an empty list clear the ordering. A tuple is always a single
        +    ``(column_name, "asc"|"desc")`` pair, while a list is always a sequence of
        +    separate orderings, so ``("a", "desc")`` and ``["a", "desc"]`` differ.
        +    """
        +    if ordering is None:
        +        return None
        +    if isinstance(ordering, tuple):
        +        items: List[Any] = [ordering]
        +    elif isinstance(ordering, list):
        +        items = ordering
        +    else:
        +        items = [ordering]
        +
        +    normalized = [
        +        _normalize_ordering_item(item, index) for index, item in enumerate(items)
        +    ]
        +    return normalized or None
        +
        +
        +def _normalize_ordering_item(item: Any, index: int) -> ColumnOrdering:
        +    prefix = f"order_by entry {index}"
        +    if isinstance(item, ColumnOrdering):
        +        if not item.column_name:
        +            raise ValueError(f"{prefix} has an empty column_name")
        +        return item
        +    if isinstance(item, str):
        +        if not item:
        +            raise ValueError(f"{prefix} is an empty column name")
        +        return ColumnOrdering(column_name=item)
        +    if isinstance(item, tuple):
        +        if len(item) != 2:
        +            raise ValueError(
        +                f"{prefix} must be a (column_name, 'asc'|'desc') tuple; got {item!r}"
        +            )
        +        column_name, direction = item
        +        if not isinstance(column_name, str) or not column_name:
        +            raise ValueError(
        +                f"{prefix} must start with a non-empty column name; got {item!r}"
        +            )
        +        if not isinstance(direction, str) or direction.lower() not in ("asc", "desc"):
        +            raise ValueError(
        +                f"{prefix} has invalid direction {direction!r}; "
        +                "expected 'asc' or 'desc'"
        +            )
        +        return ColumnOrdering(
        +            column_name=column_name, ascending=direction.lower() == "asc"
        +        )
        +    if isinstance(item, dict):
        +        unknown_keys = set(item) - _COLUMN_ORDERING_KEYS
        +        if unknown_keys:
        +            raise ValueError(
        +                f"{prefix} has unsupported key(s) {sorted(map(str, unknown_keys))}; "
        +                f"expected keys: {sorted(_COLUMN_ORDERING_KEYS)}. "
        +                f"Example: {_ORDERING_EXAMPLE}"
        +            )
        +        if "column_name" not in item:
        +            raise ValueError(
        +                f"{prefix} is missing 'column_name'. Example: {_ORDERING_EXAMPLE}"
        +            )
        +        try:
        +            normalized = ColumnOrdering(**item)
        +        except pydantic.ValidationError as err:
        +            raise ValueError(
        +                f"{prefix} is not a valid ordering: {err}. Example: {_ORDERING_EXAMPLE}"
        +            ) from err
        +        if not normalized.column_name:
        +            raise ValueError(f"{prefix} has an empty column_name")
        +        return normalized
        +    raise TypeError(
        +        f"{prefix} must be a column name, a (column_name, 'asc'|'desc') tuple, "
        +        f"a ColumnOrdering, or a dict with 'column_name'; "
        +        f"got {type(item).__name__}"
        +    )
        +
        +
         class FullTextQueryType(str, Enum):
             MATCH = "match"
             MATCH_PHRASE = "match_phrase"
        @@ -816,10 +973,29 @@ class FullTextSearchQuery(pydantic.BaseModel):
             query: str | FullTextQuery
                 If a string, it is treated as a MatchQuery.
                 If a FullTextQuery object, it is used directly.
        +    operator: FullTextOperator, optional
        +        Combine terms in a string query using AND or OR (the default).
        +        Quoted strings keep phrase semantics regardless of the operator.
             """
         
             columns: Optional[List[str]] = None
             query: Union[str, FullTextQuery]
        +    operator: Optional[FullTextOperator] = None
        +
        +    @pydantic.model_validator(mode="after")
        +    def _validate_operator(self) -> Self:
        +        if self.operator is not None and not isinstance(self.query, str):
        +            raise ValueError("operator requires a string full-text query")
        +        return self
        +
        +
        +def _add_fts_position_error_note(error: Exception) -> None:
        +    if "position is not found but required for phrase queries" in str(error):
        +        add_note(
        +            error,
        +            "Phrase queries require an index built with positions. Rebuild it with "
        +            "table.create_index(column, config=FTS(with_position=True), replace=True).",
        +        )
         
         
         class Query(pydantic.BaseModel):
        @@ -934,6 +1110,9 @@ class Query(pydantic.BaseModel):
                 The default is False
             """
         
        +    # Internal: the sync query layer already prepared blob row ids.
        +    _blob_row_id_prepared: bool = pydantic.PrivateAttr(default=False)
        +
             # The name of the vector column to use for vector search.
             vector_column: Optional[str] = None
         
        @@ -1009,6 +1188,12 @@ class Query(pydantic.BaseModel):
             # This is populated when a take query is converted to this serializable form.
             take_offsets: Optional[List[int]] = None
         
        +    # Row IDs whose requested order and duplicate occurrences must be restored.
        +    take_row_ids: Optional[List[int]] = None
        +
        +    # Restore take-offset duplicates in the exact input order.
        +    preserve_order: Optional[bool] = None
        +
             # if true, will only search the indexed data
             fast_search: Optional[bool] = None
         
        @@ -1028,12 +1213,18 @@ class Query(pydantic.BaseModel):
         
             order_by: Optional[List[ColumnOrdering]] = None
         
        +    # Tri-state storage-order requirement: None preserves the backend default,
        +    # True requires manifest order, False allows an unordered scan.
        +    scan_in_order: Optional[bool] = None
        +
             @classmethod
             def from_inner(cls, req: PyQueryRequest) -> Self:
                 query = cls()
                 query.limit = req.limit
                 query.offset = req.offset
                 query.take_offsets = req.take_offsets
        +        query.take_row_ids = req.take_row_ids
        +        query.preserve_order = req.preserve_order
                 query.filter = req.filter
                 query.full_text_query = req.full_text_search
                 query.columns = req.select
        @@ -1059,6 +1250,7 @@ class Query(pydantic.BaseModel):
                 query.postfilter = req.postfilter
                 if req.order_by is not None:
                     query.order_by = [ColumnOrdering(**o) for o in req.order_by]
        +        query.scan_in_order = req.scan_in_order
                 if req.full_text_search is not None:
                     query.full_text_query = FullTextSearchQuery(
                         columns=None,
        @@ -1086,6 +1278,7 @@ class LanceQueryBuilder(ABC):
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
                 fast_search: bool = None,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> Self:
                 """
                 Create a query builder based on the given query and query type.
        @@ -1110,6 +1303,10 @@ class LanceQueryBuilder(ABC):
                 fast_search: bool
                     Skip flat search of unindexed data.
                 """
        +        if operator is not None:
        +            operator = FullTextOperator(operator)
        +            if not isinstance(query, str) or query_type not in ("auto", "fts"):
        +                raise ValueError("operator requires a string full-text query")
                 if query_type != "fts":
                     _validate_query_vector(query)
         
        @@ -1140,6 +1337,9 @@ class LanceQueryBuilder(ABC):
                     table, query, query_type, vector_column_name
                 )
         
        +        if operator is not None and query_type != "fts":
        +            raise ValueError("operator requires a string full-text query")
        +
                 if query_type == "hybrid":
                     return LanceHybridQueryBuilder(
                         table, query, vector_column_name, fts_columns=fts_columns
        @@ -1153,7 +1353,7 @@ class LanceQueryBuilder(ABC):
                         ordering_field_name=ordering_field_name,
                         fts_columns=fts_columns,
                         fast_search=fast_search,
        -            )
        +            ).operator(operator)
         
                 if isinstance(query, (list, tuple)):
                     query = np.array(query, dtype=np.float32)
        @@ -1225,6 +1425,7 @@ class LanceQueryBuilder(ABC):
                 self._approx_mode = None
                 self._bypass_vector_index = None
                 self._order_by = None
        +        self._scan_in_order = None
         
             @deprecation.deprecated(
                 deprecated_in="0.3.1",
        @@ -1270,13 +1471,13 @@ class LanceQueryBuilder(ABC):
                 blob_mode: str, default "lazy"
                     Controls how blob columns are returned. Local blob v2 queries support
                     ``"bytes"`` and ``"descriptions"`` without pylance. Eligible local
        -            plain scans use pylance's scanner for lazy blob handles in ``"lazy"``
        -            mode and for legacy blob columns. Other local blob v2
        -            queries return descriptors in ``"lazy"`` and ``"descriptions"``
        -            modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
        -            LanceDB Enterprise blob queries support only ``"descriptions"`` until a
        -            stable
        -            table snapshot can bind the query and blob fetches.
        +            plain scans also support ``"bytes"`` for row-addressable legacy blob
        +            columns without pylance. Other local blob v2 queries return
        +            descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
        +            in ``"bytes"`` mode, through :meth:`to_arrow`.
        +            Enterprise queries support ``"bytes"`` at the query response's
        +            snapshot and ``"descriptions"`` without payload reads. Remote
        +            ``"lazy"`` handles are not supported.
                 **kwargs
                     Forwarded to pyarrow.Table.to_pandas after query execution and
                     optional flattening.
        @@ -1284,6 +1485,10 @@ class LanceQueryBuilder(ABC):
                 validate_blob_mode(blob_mode)
                 if _is_remote_query_table(self._table):
                     blob_sources = self._validated_blob_sources(blob_mode)
        +            if blob_mode == "bytes":
        +                return flatten_columns(
        +                    self.to_arrow(timeout=timeout, blob_mode=blob_mode), flatten
        +                ).to_pandas(**kwargs)
                     return _finish_remote_pandas(
                         self.to_arrow(timeout=timeout),
                         blob_mode=blob_mode,
        @@ -1330,6 +1535,9 @@ class LanceQueryBuilder(ABC):
                 and also the "_distance" column which is the distance between the query
                 vector and the returned vectors.
         
        +        This collects all results in memory. To process a large result a batch
        +        at a time, use [to_batches][lancedb.query.LanceQueryBuilder.to_batches].
        +
                 Parameters
                 ----------
                 timeout: Optional[timedelta]
        @@ -1338,8 +1546,8 @@ class LanceQueryBuilder(ABC):
                 blob_mode: str, default "lazy"
                     ``"lazy"`` returns blob v2 descriptors that carry the row id
                     ``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
        -            ``"bytes"`` returns payload bytes and raises for legacy blob columns
        -            and blobs inside lists.
        +            ``"bytes"`` returns payload bytes for supported row-addressable blob
        +            columns and raises for blobs inside lists.
                 """
                 raise NotImplementedError
         
        @@ -1356,11 +1564,16 @@ class LanceQueryBuilder(ABC):
                 Execute the query and return the results as a pyarrow
                 [RecordBatchReader](https://arrow.apache.org/docs/python/generated/pyarrow.RecordBatchReader.html)
         
        -        For v2 blob projections, the default ``blob_mode="lazy"`` keeps the
        +        For blob v2 projections, the default ``blob_mode="lazy"`` keeps the
                 auto ``_rowid`` column visible so batch consumers can call
                 ``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide
                 automatic row ids.
         
        +        A remote table decodes batches as they arrive when the server streams
        +        query results. If the response stops partway, reading raises
        +        [ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError]
        +        after the batches already returned, which are valid but incomplete.
        +
                 Parameters
                 ----------
                 batch_size: int
        @@ -1368,11 +1581,14 @@ class LanceQueryBuilder(ABC):
                 timeout: Optional[timedelta]
                     The maximum time to wait for the query to complete.
                     If None, wait indefinitely.
        +            The timeout also covers reading the batches, so consuming them
        +            slowly can exceed it.
                 blob_mode: str, default "lazy"
        -            ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
        -            ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
        -            payloads one batch at a time, without requiring pylance. Bytes mode
        -            has the same restrictions as :meth:`to_arrow`.
        +            ``"lazy"`` keeps blob v2 descriptors and auto row ids for manual
        +            fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches
        +            supported row-addressable blob payloads one batch at a time, without
        +            requiring pylance. Bytes mode has the same restrictions as
        +            :meth:`to_arrow`.
         
                 Examples
                 --------
        @@ -1544,6 +1760,10 @@ class LanceQueryBuilder(ABC):
                 -----
                 Calling this multiple times combines the filters with a logical AND
                 rather than replacing the previous filter.
        +
        +        Spatial predicates such as ``ST_Intersects(geom, ST_GeomFromText(...))``
        +        work on GeoArrow columns and use an [RTree][lancedb.index.RTree] index
        +        when one exists.
                 """
                 self._where = _combine_where(self._where, where)
                 self._postfilter = not prefilter
        @@ -1568,38 +1788,153 @@ class LanceQueryBuilder(ABC):
             def _user_requested_row_id(self) -> bool:
                 return self._with_row_id is True
         
        -    def _blob_auto_row_id_enabled(self) -> bool:
        +    def _blob_auto_row_id_enabled(self, schema: Optional[pa.Schema] = None) -> bool:
        +        if self._with_row_id is not None:
        +            return False
        +        if schema is None:
        +            schema = self._table.schema
                 return blob_auto_row_id_for_scan(
        -            self._table.schema,
        +            schema,
                     self._columns,
                     with_row_id=self._with_row_id,
                 )
         
        -    def _scan_needs_row_id(self) -> bool:
        -        return self._user_requested_row_id() or self._blob_auto_row_id_enabled()
        +    def _row_id_schema(self) -> Optional[pa.Schema]:
        +        if self._with_row_id is not None:
        +            return None
        +        return self._table.schema
         
        -    def _query_for_scan(self) -> Query:
        +    def _scan_needs_row_id(self, schema: Optional[pa.Schema] = None) -> bool:
        +        if self._user_requested_row_id():
        +            return True
        +        return self._blob_auto_row_id_enabled(schema)
        +
        +    def _query_for_scan(
        +        self,
        +        blob_sources: Optional[dict[str, str]] = None,
        +        schema: Optional[pa.Schema] = None,
        +    ) -> Query:
        +        self._ensure_fragment_constraints_supported("this query")
                 query = self.to_query_object()
        -        if self._scan_needs_row_id():
        +        if schema is None:
        +            schema = self._row_id_schema()
        +        if self._scan_needs_row_id(schema) or blob_sources:
                     query.with_row_id = True
                 return query
         
        -    def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
        -        """Map projected blob v2 outputs to their source columns.
        +    def _prepare_blob_execution(
        +        self, blob_mode: BlobMode
        +    ) -> tuple[dict[str, str], Optional[pa.Schema]]:
        +        validate_blob_mode(blob_mode)
        +        schema = self._table.schema
        +        if blob_mode == "lazy":
        +            if not schema_has_blob_field(schema):
        +                return {}, schema
        +            # Lazy results hide automatic row ids inside projected blob columns.
        +            return blob_v2_projection_sources(schema, self._columns), schema
        +        return self._validated_blob_sources(blob_mode, schema), schema
        +
        +    def _to_batches_prepared(
        +        self,
        +        *,
        +        batch_size: Optional[int],
        +        timeout: Optional[timedelta],
        +        blob_mode: BlobMode,
        +        blob_sources: dict[str, str],
        +        schema: Optional[pa.Schema],
        +    ) -> pa.RecordBatchReader:
        +        query = self._query_for_scan(blob_sources, schema)
        +        reader = self._execute_query_prepared(
        +            query,
        +            batch_size=batch_size,
        +            timeout=timeout,
        +            pull_reader=(
        +                blob_mode == "lazy"
        +                and _query_is_plain_scan(query)
        +                and not _query_needs_lance_scanner(self)
        +            ),
        +        )
        +        return self._batches_in_mode(reader, blob_mode, blob_sources, schema)
        +
        +    def _execute_query_prepared(
        +        self,
        +        query: Query,
        +        *,
        +        batch_size: Optional[int] = None,
        +        timeout: Optional[timedelta] = None,
        +        pull_reader: bool = False,
        +    ) -> pa.RecordBatchReader:
        +        if not _is_remote_query_table(self._table):
        +            query._blob_row_id_prepared = True
        +        if (
        +            pull_reader
        +            and not _is_remote_query_table(self._table)
        +            and not self._table.namespace
        +            and getattr(self._table, "_namespace_client", None) is None
        +        ):
        +            return self._table._execute_pull_query(
        +                query, batch_size=batch_size, timeout=timeout
        +            )
        +        return self._table._execute_query(query, batch_size=batch_size, timeout=timeout)
        +
        +    def _execute_arrow_prepared(
        +        self, query: Query, *, timeout: Optional[timedelta] = None
        +    ) -> pa.Table:
        +        if not _is_remote_query_table(self._table):
        +            query._blob_row_id_prepared = True
        +        return self._table._execute_arrow(query, timeout=timeout)
        +
        +    def _ensure_fragment_constraints_supported(self, operation: str) -> None:
        +        _raise_unsupported_fragment_constraints(
        +            self._fragments,
        +            self._fragment_ids,
        +            operation=operation,
        +        )
        +
        +    def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
        +        if blob_mode != "bytes":
        +            return False
        +        try:
        +            query = self.to_query_object()
        +        except NotImplementedError:
        +            return False
        +        return (
        +            _query_is_plain_blob_scan(query)
        +            and getattr(self, "_reranker", None) is None
        +            and not _query_needs_lance_scanner(self)
        +            and self._table._table._inner._is_native()
        +            and _supports_blob_fetch(
        +                self._table._table,
        +                getattr(self._table, "_pushdown_operations", ()),
        +            )
        +        )
        +
        +    def _validated_blob_sources(
        +        self, blob_mode: BlobMode, schema: Optional[pa.Schema] = None
        +    ) -> dict[str, str]:
        +        """Map projected blob outputs to their source columns.
         
                 Bytes mode is checked here, before the query runs.
                 """
                 validate_blob_mode(blob_mode)
        -        schema = self._table.schema
        -        blob_sources = blob_v2_projection_sources(schema, self._columns)
        +        if blob_mode == "lazy":
        +            return {}
        +        if schema is None:
        +            schema = self._table.schema
        +        blob_sources = blob_projection_sources(
        +            schema,
        +            self._columns,
        +            include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode),
        +        )
                 if blob_mode != "bytes":
                     return blob_sources
                 reject_unfetchable_blob_columns(schema, self._columns, blob_sources)
        -        if blob_sources and not _supports_local_blob_fetch(
        +        if blob_sources and not _supports_blob_fetch(
                     self._table._table, getattr(self._table, "_pushdown_operations", ())
                 ):
                     raise _blob_bytes_without_snapshot_error()
        -        reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources)
        +        if not _is_remote_query_table(self._table):
        +            reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources)
                 return blob_sources
         
             def _blob_output_schema(self) -> pa.Schema:
        @@ -1612,9 +1947,20 @@ class LanceQueryBuilder(ABC):
                     return tbl
                 if blob_mode == "descriptions":
                     return strip_auto_row_ids(tbl, blob_sources)
        -        return replace_v2_blob_columns_with_bytes_sync(
        -            tbl, blob_sources, self._table.fetch_blobs
        -        )
        +        reject_unmatched_blob_outputs(tbl.schema, blob_sources)
        +        if _is_remote_query_table(self._table) and blob_sources:
        +            version, identity = _remote_blob_snapshot(tbl.schema)
        +
        +            async def fetch_at_version(column, row_ids):
        +                return await self._table._table._inner.fetch_blobs(
        +                    column, row_ids, version=version, snapshot_identity=identity
        +                )
        +
        +            def fetch_blobs(column, row_ids):
        +                return LOOP.run(fetch_at_version(column, row_ids))
        +        else:
        +            fetch_blobs = self._table.fetch_blobs
        +        return replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
         
             def _finalize_blob_query_table(
                 self,
        @@ -1622,20 +1968,26 @@ class LanceQueryBuilder(ABC):
                 *,
                 blob_mode: BlobMode,
                 blob_sources: dict[str, str],
        +        schema: Optional[pa.Schema] = None,
             ) -> pa.Table:
        -        blob_auto_row_id = self._blob_auto_row_id_enabled()
        -        finalized = finalize_blob_query_table(
        -            tbl,
        -            user_requested_row_id=self._user_requested_row_id(),
        -            blob_auto_row_id=blob_auto_row_id,
        -            blob_paths=blob_sources.keys() if blob_auto_row_id else (),
        -        )
        +        blob_auto_row_id = self._blob_auto_row_id_enabled(schema)
        +        if blob_mode == "bytes" and blob_sources:
        +            # Bytes conversion reads _rowid directly, including when the
        +            # projection mixes legacy and v2 columns.
        +            finalized = tbl
        +        else:
        +            finalized = finalize_blob_query_table(
        +                tbl,
        +                user_requested_row_id=self._user_requested_row_id(),
        +                blob_auto_row_id=blob_auto_row_id,
        +                blob_paths=blob_sources.keys() if blob_auto_row_id else (),
        +            )
                 finalized = self._apply_arrow_blob_mode(finalized, blob_mode, blob_sources)
                 # with_row_id(False) does not reach the scan, which adds _rowid anyway.
                 # Lazy keeps it because fetch_blobs(hits) reads it there.
                 if (
                     blob_mode != "lazy"
        -            and self._with_row_id is False
        +            and not self._user_requested_row_id()
                     and "_rowid" in finalized.column_names
                 ):
                     finalized = finalized.drop_columns(["_rowid"])
        @@ -1646,22 +1998,26 @@ class LanceQueryBuilder(ABC):
                 reader: pa.RecordBatchReader,
                 blob_mode: BlobMode,
                 blob_sources: dict[str, str],
        +        schema: Optional[pa.Schema] = None,
             ) -> pa.RecordBatchReader:
                 if blob_mode == "lazy":
                     return reader
         
                 def convert(tbl: pa.Table) -> pa.Table:
                     return self._finalize_blob_query_table(
        -                tbl, blob_mode=blob_mode, blob_sources=blob_sources
        +                tbl,
        +                blob_mode=blob_mode,
        +                blob_sources=blob_sources,
        +                schema=schema,
                     )
         
        -        schema = convert(pa.Table.from_batches([], schema=reader.schema)).schema
        +        result_schema = convert(pa.Table.from_batches([], schema=reader.schema)).schema
         
                 def batches():
                     for batch in reader:
                         yield from convert(pa.Table.from_batches([batch])).to_batches()
         
        -        return pa.RecordBatchReader.from_batches(schema, batches())
        +        return pa.RecordBatchReader.from_batches(result_schema, batches())
         
             def with_row_address(self, with_row_address: bool = True) -> Self:
                 """Set whether to return row addresses.
        @@ -1680,12 +2036,53 @@ class LanceQueryBuilder(ABC):
                 return self
         
             def with_fragments(self, fragments: Any) -> Self:
        -        """Set the Lance fragments to scan for plain scanner-backed queries."""
        +        """Restrict an embedded plain-scan blob query to the given Lance fragments.
        +
        +        Fragment selection is supported only when ``to_pandas()`` uses the
        +        embedded Lance plain-scan path: the table is an embedded, non-memory
        +        Lance dataset, the query is a plain scan (no vector, full-text, take,
        +        postfilter, or ordering), and the selected output includes a blob
        +        column. Other terminals and remote tables raise ``NotImplementedError``
        +        before scanning instead of silently scanning the full table.
        +        Blob-specific ``to_pandas()`` fallbacks keep their existing validation
        +        errors.
        +
        +        Parameters
        +        ----------
        +        fragments : list[lance.Fragment]
        +            Fragments from ``table.to_lance().get_fragments()``. Pass fragments
        +            from the same dataset snapshot. Use ``fragment_ids()`` instead when
        +            ``scan_in_order(True)`` is set; fragment objects cannot be validated
        +            against the pinned dataset version.
        +
        +        Returns
        +        -------
        +        LanceQueryBuilder
        +            The LanceQueryBuilder object.
        +        """
                 self._fragments = fragments
                 return self
         
             def fragment_ids(self, fragment_ids: List[int]) -> Self:
        -        """Set the Lance fragment ids to scan for plain scanner-backed queries."""
        +        """Restrict an embedded plain-scan blob query to the given fragment ids.
        +
        +        Fragment selection uses the same supported ``to_pandas()`` path as
        +        ``with_fragments()``. On that path, an empty list selects no rows and
        +        missing ids raise ``ValueError``. Other terminals and remote tables
        +        raise ``NotImplementedError`` before scanning instead of silently
        +        scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep
        +        their existing validation errors.
        +
        +        Parameters
        +        ----------
        +        fragment_ids : list[int]
        +            Fragment ids from ``table.to_lance().get_fragments()``.
        +
        +        Returns
        +        -------
        +        LanceQueryBuilder
        +            The LanceQueryBuilder object.
        +        """
                 self._fragment_ids = fragment_ids
                 return self
         
        @@ -1741,24 +2138,40 @@ class LanceQueryBuilder(ABC):
                 -------
                 plan : str
                 """  # noqa: E501
        +        self._ensure_fragment_constraints_supported("explain_plan()")
                 return self._table._explain_plan(self.to_query_object(), verbose=verbose)
         
        -    def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self:
        +    def order_by(self, ordering: _OrderingInput = None) -> Self:
                 """
                 Set the ordering for the results.
         
                 Parameters
                 ----------
        -        ordering: Optional[List[ColumnOrdering]]
        -            The ordering to use for the results.  If None, then the default ordering
        -            will be used.
        +        ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]]
        +            The ordering to use for the results. Each entry can be a column
        +            name, a ``(column_name, "asc"|"desc")`` tuple, a
        +            [ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a
        +            ``column_name`` key. A bare tuple is a single direction pair, while
        +            a list contains separate orderings, so ``("a", "desc")`` sorts by
        +            ``a`` descending and ``["a", "desc"]`` sorts by both columns.
        +            Pass ``None`` or an empty list to clear the ordering.
         
                 Returns
                 -------
                 LanceQueryBuilder
                     The LanceQueryBuilder object.
        +
        +        Examples
        +        --------
        +        >>> import lancedb
        +        >>> db = lancedb.connect("memory://")
        +        >>> table = db.create_table("ordering", [{"name": "b"}, {"name": "a"}])
        +        >>> table.search().order_by(["name"]).to_list()
        +        [{'name': 'a'}, {'name': 'b'}]
        +        >>> table.search().order_by([("name", "desc")]).to_list()
        +        [{'name': 'b'}, {'name': 'a'}]
                 """
        -        self._order_by = ordering
        +        self._order_by = _normalize_ordering(ordering)
                 return self
         
             def analyze_plan(
        @@ -1815,6 +2228,7 @@ class LanceQueryBuilder(ABC):
                 plan : str
                     The physical query execution plan with runtime metrics.
                 """
        +        self._ensure_fragment_constraints_supported("analyze_plan()")
                 return self._table._analyze_plan(
                     self.to_query_object(), distributed_metrics=distributed_metrics
                 )
        @@ -1875,18 +2289,29 @@ class LanceQueryBuilder(ABC):
                 query = self.to_query_object()
                 if not _query_is_plain_scan(query):
                     return None
        +        blob_sources = (
        +            blob_projection_sources(
        +                self._table.schema,
        +                query.columns,
        +                include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode),
        +            )
        +            if blob_mode == "bytes"
        +            else {}
        +        )
         
                 # Remote and in-memory tables have no Lance dataset to scan.
                 if not self._table._table._inner._is_native() or (
                     get_uri_scheme(self._table._dataset_path) == "memory"
                 ):
                     return None
        -        # Blob v2 payloads and descriptions use LanceDB's native fetch path.
        -        # Only lazy handles, legacy blobs, and scanner-only options need pylance.
        -        if (
        -            blob_mode != "lazy"
        -            and not _query_needs_lance_scanner(self)
        -            and blob_v2_projection_sources(self._table.schema, query.columns)
        +        # Bytes conversions use LanceDB's fetch path for both blob versions.
        +        # Descriptions for v2 do too; lazy handles still need the scanner.
        +        if not _query_needs_lance_scanner(self) and (
        +            (blob_mode == "bytes" and blob_sources)
        +            or (
        +                blob_mode == "descriptions"
        +                and blob_v2_projection_sources(self._table.schema, query.columns)
        +            )
                 ):
                     return None
                 try:
        @@ -1894,12 +2319,7 @@ class LanceQueryBuilder(ABC):
                 except ImportError as err:
                     raise _unsupported_blob_pandas_error(str(err)) from err
                 blob_auto_row_id = self._blob_auto_row_id_enabled()
        -        blob_sources = (
        -            blob_v2_projection_sources(self._table.schema, query.columns)
        -            if blob_mode == "bytes"
        -            else {}
        -        )
        -        if blob_sources:
        +        if blob_mode == "bytes":
                     reject_unfetchable_blob_columns(
                         self._table.schema, query.columns, blob_sources
                     )
        @@ -2055,6 +2475,11 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
             def search_effort(self, search_effort: Optional[float]) -> LanceVectorQueryBuilder:
                 """Set the initial IVF search effort to a finite value in [0, 1].
         
        +        Efforts 0.1 and 0.25 target empirical mean partition-routing recall of
        +        80% and 90% for L2, cosine and dot through k=100000. The probe budget
        +        adapts to the metric and k. Hamming and larger k remain uncalibrated;
        +        100000 is not an API limit. Remote queries also require server support.
        +
                 None (the default) uses Auto, internally 0.5. Zero starts at the caller
                 minimum; one searches all partitions within the caller maximum. Later
                 probing may continue when too few candidates are found. Any explicit
        @@ -2228,14 +2653,40 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
                 blob_mode: str, default "lazy"
                     ``"lazy"`` returns blob v2 descriptors that carry the row id
                     ``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
        -            ``"bytes"`` returns payload bytes and raises for legacy blob columns
        -            and blobs inside lists.
        +            ``"bytes"`` returns payload bytes for supported row-addressable blob
        +            columns and raises for blobs inside lists.
                 """
        -        blob_sources = self._validated_blob_sources(blob_mode)
        +        blob_sources, schema = self._prepare_blob_execution(blob_mode)
        +        if blob_mode != "lazy":
        +            # Materialize in lazy mode so reranking runs once over the full
        +            # result before the requested aggregate blob conversion.
        +            return self._finalize_blob_query_table(
        +                self._to_batches_prepared(
        +                    batch_size=None,
        +                    timeout=timeout,
        +                    blob_mode="lazy",
        +                    blob_sources=blob_sources,
        +                    schema=schema,
        +                ).read_all(),
        +                blob_mode=blob_mode,
        +                blob_sources=blob_sources,
        +                schema=schema,
        +            )
        +
        +        self._ensure_fragment_constraints_supported("to_arrow()")
        +        results = self._execute_arrow_prepared(
        +            self._query_for_scan(blob_sources, schema), timeout=timeout
        +        )
        +        if self._reranker is not None:
        +            source = results
        +            results = self._reranker.rerank_vector(self._str_query, results)
        +            check_reranker_result(results)
        +            results = _merge_query_snapshot(results, source)
                 return self._finalize_blob_query_table(
        -            self.to_batches(timeout=timeout).read_all(),
        +            results,
                     blob_mode=blob_mode,
                     blob_sources=blob_sources,
        +            schema=schema,
                 )
         
             def to_query_object(self) -> Query:
        @@ -2275,6 +2726,31 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
                     order_by=self._order_by,
                 )
         
        +    def _to_batches_prepared(
        +        self,
        +        *,
        +        batch_size: Optional[int],
        +        timeout: Optional[timedelta],
        +        blob_mode: BlobMode,
        +        blob_sources: dict[str, str],
        +        schema: Optional[pa.Schema],
        +    ) -> pa.RecordBatchReader:
        +        query = self._query_for_scan(blob_sources, schema)
        +        result_set = self._execute_query_prepared(
        +            query, batch_size=batch_size, timeout=timeout
        +        )
        +        if self._reranker is not None:
        +            rs_table = result_set.read_all()
        +            result_set = self._reranker.rerank_vector(self._str_query, rs_table)
        +            check_reranker_result(result_set)
        +            result_set = _merge_query_snapshot(result_set, rs_table)
        +            # convert result_set back to RecordBatchReader
        +            result_set = pa.RecordBatchReader.from_batches(
        +                result_set.schema, result_set.to_batches()
        +            )
        +
        +        return self._batches_in_mode(result_set, blob_mode, blob_sources, schema)
        +
             def to_batches(
                 self,
                 /,
        @@ -2293,6 +2769,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
                 timeout: timedelta, default None
                     The maximum time to wait for the query to complete.
                     If None, wait indefinitely.
        +            The timeout also covers reading the batches, so consuming them
        +            slowly can exceed it.
                 blob_mode: str, default "lazy"
                     Controls blob conversion as described in
                     :meth:`LanceQueryBuilder.to_batches`.
        @@ -2301,24 +2779,14 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
                 -------
                 pa.RecordBatchReader
                 """
        -        blob_sources = self._validated_blob_sources(blob_mode)
        -        vector = self._query if isinstance(self._query, list) else self._query.tolist()
        -        if isinstance(vector[0], np.ndarray):
        -            vector = [v.tolist() for v in vector]
        -        query = self._query_for_scan()
        -        result_set = self._table._execute_query(
        -            query, batch_size=batch_size, timeout=timeout
        +        blob_sources, schema = self._prepare_blob_execution(blob_mode)
        +        return self._to_batches_prepared(
        +            batch_size=batch_size,
        +            timeout=timeout,
        +            blob_mode=blob_mode,
        +            blob_sources=blob_sources,
        +            schema=schema,
                 )
        -        if self._reranker is not None:
        -            rs_table = result_set.read_all()
        -            result_set = self._reranker.rerank_vector(self._str_query, rs_table)
        -            check_reranker_result(result_set)
        -            # convert result_set back to RecordBatchReader
        -            result_set = pa.RecordBatchReader.from_batches(
        -                result_set.schema, result_set.to_batches()
        -            )
        -
        -        return self._batches_in_mode(result_set, blob_mode, blob_sources)
         
             def where(
                 self, where: Union[str, Expr], prefilter: bool = None
        @@ -2434,6 +2902,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
                 super().__init__(table)
                 self._query = query
                 self._phrase_query = False
        +        self._operator: Optional[FullTextOperator] = None
                 # Deprecated compatibility parameter. Native FTS ordering is now
                 # configured through order_by(); LanceQueryBuilder.create emits the warning.
                 _ = ordering_field_name
        @@ -2443,6 +2912,37 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
                     fts_columns = [fts_columns]
                 self._fts_columns = fts_columns
         
        +    def operator(
        +        self, operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]]
        +    ) -> LanceFtsQueryBuilder:
        +        """Combine terms in a string query with ``"AND"`` or ``"OR"``.
        +
        +        The default is OR. AND requires every term to match. For example,
        +        ``table.search("gripper closed", query_type="fts").operator("AND")``.
        +        Structured queries specify their own operators. Quoted strings and
        +        ``phrase_query()`` retain their phrase semantics.
        +        """
        +        if operator is not None and not isinstance(self._query, str):
        +            raise ValueError("operator requires a string full-text query")
        +        self._operator = FullTextOperator(operator) if operator is not None else None
        +        return self
        +
        +    def count_rows(self) -> int:
        +        """Count all full-text matches satisfying the query's filter.
        +
        +        Ignores limit, offset, selection, ordering, and reranking. ``fast_search``
        +        still restricts the count to indexed data. This streams matching scores
        +        without loading document columns and may scan every match.
        +
        +        For example, ``table.search("gripper closed", query_type="fts",``
        +        ``operator="AND").where("active = true").count_rows()``.
        +        """
        +        self._ensure_fragment_constraints_supported("count_rows()")
        +        self._table._ensure_no_legacy_fts_index()
        +        query = self._table._table._sync_query_to_async(self.to_query_object())
        +        assert isinstance(query, AsyncFTSQuery)
        +        return LOOP.run(query.count_rows())
        +
             def phrase_query(self, phrase_query: bool = True) -> LanceFtsQueryBuilder:
                 """Set whether to use phrase query.
         
        @@ -2499,7 +2999,9 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
                     fragment_ids=self._fragment_ids,
                     use_rte=self._use_rte,
                     full_text_query=FullTextSearchQuery(
        -                query=self._query_with_phrase_semantics(), columns=self._fts_columns
        +                query=self._query_with_phrase_semantics(),
        +                columns=self._fts_columns,
        +                operator=self._operator,
                     ),
                     offset=self._offset,
                     fast_search=self._fast_search,
        @@ -2520,16 +3022,25 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
                 timeout: Optional[timedelta] = None,
                 blob_mode: BlobMode = "lazy",
             ) -> pa.Table:
        -        blob_sources = self._validated_blob_sources(blob_mode)
        +        blob_sources, schema = self._prepare_blob_execution(blob_mode)
                 self._table._ensure_no_legacy_fts_index()
         
        -        query = self._query_for_scan()
        -        results = self._table._execute_query(query, timeout=timeout).read_all()
        +        self._ensure_fragment_constraints_supported("to_arrow()")
        +        query = self._query_for_scan(blob_sources, schema)
        +        if blob_mode == "lazy":
        +            results = self._execute_arrow_prepared(query, timeout=timeout)
        +        else:
        +            results = self._execute_query_prepared(query, timeout=timeout).read_all()
                 if self._reranker is not None:
        +            source = results
                     results = self._reranker.rerank_fts(self._query, results)
                     check_reranker_result(results)
        +            results = _merge_query_snapshot(results, source)
                 return self._finalize_blob_query_table(
        -            results, blob_mode=blob_mode, blob_sources=blob_sources
        +            results,
        +            blob_mode=blob_mode,
        +            blob_sources=blob_sources,
        +            schema=schema,
                 )
         
             def to_batches(
        @@ -2568,13 +3079,85 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
                 timeout: Optional[timedelta] = None,
                 blob_mode: BlobMode = "lazy",
             ) -> pa.Table:
        -        blob_sources = self._validated_blob_sources(blob_mode)
        +        blob_sources, schema = self._prepare_blob_execution(blob_mode)
        +        if blob_mode == "bytes" and blob_sources:
        +            return self._to_batches_prepared(
        +                batch_size=None,
        +                timeout=timeout,
        +                blob_mode="bytes",
        +                blob_sources=blob_sources,
        +                schema=schema,
        +            ).read_all()
        +        if blob_mode != "lazy":
        +            return self._finalize_blob_query_table(
        +                self._to_batches_prepared(
        +                    batch_size=None,
        +                    timeout=timeout,
        +                    blob_mode="lazy",
        +                    blob_sources=blob_sources,
        +                    schema=schema,
        +                ).read_all(),
        +                blob_mode=blob_mode,
        +                blob_sources=blob_sources,
        +                schema=schema,
        +            )
        +
        +        self._ensure_fragment_constraints_supported("to_arrow()")
                 return self._finalize_blob_query_table(
        -            self.to_batches(timeout=timeout).read_all(),
        +            self._execute_arrow_prepared(
        +                self._query_for_scan(blob_sources, schema), timeout=timeout
        +            ),
                     blob_mode=blob_mode,
                     blob_sources=blob_sources,
        +            schema=schema,
                 )
         
        +    def scan_in_order(self, ordered: bool = True) -> Self:
        +        """Control whether an ordinary scan must preserve storage order.
        +
        +        Parameters
        +        ----------
        +        ordered: bool, default True
        +            ``True`` requires manifest order: fragments in manifest order, then
        +            rows in fragment order. ``False`` allows the backend to scan
        +            unordered. Leave the method uncalled to preserve the backend
        +            default.
        +
        +        An unfiltered plain base-only scan of an Embedded table, pinned to one
        +        dataset version, returns manifest order by default. RTE tables scan the
        +        LSM by default and do not provide this guarantee unless
        +        ``use_rte(False)`` selects the base table. Explicit ``True`` also
        +        disables scalar-index filter planning, because legacy scalar-index plans
        +        can return a different sequence; default filtered scans can still use
        +        those plans and may not preserve manifest order. Filters still apply,
        +        but the scan can read more data. ``with_fragments()`` is not supported
        +        with ``True`` because fragment objects cannot be validated against the
        +        pinned dataset version; use ``fragment_ids()`` instead, which resolves
        +        ids from the manifest and remains ordered. Compaction, updates, or
        +        opening a newer version can change that order, so pin the table version
        +        when positions must remain stable across executions. An explicit
        +        ``order_by()`` replaces manifest order with a global sort, and vector,
        +        full-text, hybrid, or reranked queries return ranked results; combining
        +        those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise
        +        tables and RTE/LSM reads raise ``NotImplementedError`` because they
        +        cannot uphold the order; set ``use_rte(False)`` to read the RTE base
        +        table in storage order. When ``QueryTable`` pushdown is enabled, the
        +        backend default may not preserve order; requesting ``True`` executes
        +        against Embedded storage instead, because the namespace request has no
        +        order field.
        +
        +        Examples
        +        --------
        +        >>> import lancedb
        +        >>> db = lancedb.connect("memory://")
        +        >>> table = db.create_table("scan_in_order", [{"id": 1}])
        +        >>> query = table.search().scan_in_order(True).select(["id"])
        +        >>> query.to_arrow()["id"].to_pylist()
        +        [1]
        +        """
        +        self._scan_in_order = ordered
        +        return self
        +
             def to_query_object(self) -> Query:
                 return Query(
                     columns=self._columns,
        @@ -2587,6 +3170,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
                     use_rte=self._use_rte,
                     offset=self._offset,
                     order_by=self._order_by,
        +            scan_in_order=self._scan_in_order,
                 )
         
             def output_schema(self) -> pa.Schema:
        @@ -2601,12 +3185,14 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
                 *,
                 blob_mode: BlobMode = "lazy",
             ) -> pa.RecordBatchReader:
        -        blob_sources = self._validated_blob_sources(blob_mode)
        -        query = self._query_for_scan()
        -        reader = self._table._execute_query(
        -            query, batch_size=batch_size, timeout=timeout
        +        blob_sources, schema = self._prepare_blob_execution(blob_mode)
        +        return self._to_batches_prepared(
        +            batch_size=batch_size,
        +            timeout=timeout,
        +            blob_mode=blob_mode,
        +            blob_sources=blob_sources,
        +            schema=schema,
                 )
        -        return self._batches_in_mode(reader, blob_mode, blob_sources)
         
             def rerank(self, reranker: Reranker) -> LanceEmptyQueryBuilder:
                 """Rerank the results using the specified reranker.
        @@ -2665,6 +3251,29 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
                 # the reranker's own use, so it cannot answer "did the caller ask?".
                 self._caller_requested_row_id = False
         
        +    def order_by(self, ordering: _OrderingInput = None) -> Self:
        +        """
        +        Set the ordering for the results.
        +
        +        Hybrid results are fused and reranked, so ordering the two search legs
        +        does not define the final result order. Order the returned rows after
        +        reranking instead.
        +
        +        Parameters
        +        ----------
        +        ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]]
        +            Must be ``None`` or an empty list. Any non-empty ordering raises
        +            ``NotImplementedError``.
        +        """
        +        normalized = _normalize_ordering(ordering)
        +        if normalized:
        +            raise NotImplementedError(
        +                "order_by is not supported for hybrid queries; "
        +                "sort the returned results after reranking instead."
        +            )
        +        self._order_by = None
        +        return self
        +
             def _validate_query(self, query, vector=None, text=None):
                 if query is not None and (vector is not None or text is not None):
                     raise ValueError(
        @@ -2728,11 +3337,14 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
                 timeout: Optional[timedelta] = None,
                 blob_mode: BlobMode = "lazy",
             ) -> pa.Table:
        -        blob_sources = self._validated_blob_sources(blob_mode)
        +        blob_sources, schema = self._prepare_blob_execution(blob_mode)
                 # WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s.
                 return _wal_hybrid.with_pk_fallback(
                     lambda: self._run_hybrid(
        -                timeout=timeout, blob_mode=blob_mode, blob_sources=blob_sources
        +                timeout=timeout,
        +                blob_mode=blob_mode,
        +                blob_sources=blob_sources,
        +                schema=schema,
                     ),
                     self._table,
                     fused=lambda: self._pk_fusion is not None,
        @@ -2745,6 +3357,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
                 timeout: Optional[timedelta] = None,
                 blob_mode: BlobMode,
                 blob_sources: dict[str, str],
        +        schema: Optional[pa.Schema],
             ) -> pa.Table:
                 self._create_query_builders()
                 fts_query, vector_query = self._fts_query, self._vector_query
        @@ -2772,8 +3385,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
                     with_row_ids=True,
                     offset=self._offset,
                 )
        +        results = _merge_query_snapshot(results, fts_results, vector_results)
                 return self._finish_hybrid_results(
        -            results, blob_mode=blob_mode, blob_sources=blob_sources
        +            results,
        +            blob_mode=blob_mode,
        +            blob_sources=blob_sources,
        +            schema=schema,
                 )
         
             def _finish_hybrid_results(
        @@ -2782,6 +3399,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
                 *,
                 blob_mode: BlobMode,
                 blob_sources: dict[str, str],
        +        schema: Optional[pa.Schema],
             ) -> pa.Table:
                 if self._pk_fusion is not None:  # WAL-PK-FUSION: delete.
                     return self._apply_arrow_blob_mode(
        @@ -2789,9 +3407,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
                     )
                 if self._user_requested_row_id():
                     return self._apply_arrow_blob_mode(results, blob_mode, blob_sources)
        -        if self._blob_auto_row_id_enabled():
        +        if self._blob_auto_row_id_enabled(schema):
                     return self._finalize_blob_query_table(
        -                results, blob_mode=blob_mode, blob_sources=blob_sources
        +                results,
        +                blob_mode=blob_mode,
        +                blob_sources=blob_sources,
        +                schema=schema,
                     )
                 if "_rowid" in results.column_names:
                     # Fetch bytes before dropping _rowid.
        @@ -3014,6 +3635,11 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
             def search_effort(self, search_effort: Optional[float]) -> LanceHybridQueryBuilder:
                 """Set the initial IVF search effort to a finite value in [0, 1].
         
        +        Efforts 0.1 and 0.25 target empirical mean partition-routing recall of
        +        80% and 90% for L2, cosine and dot through k=100000. The probe budget
        +        adapts to the metric and k. Hamming and larger k remain uncalibrated;
        +        100000 is not an API limit. Remote queries also require server support.
        +
                 None (the default) uses Auto, internally 0.5. Zero starts at the caller
                 minimum; one searches all partitions within the caller maximum. Later
                 probing may continue when too few candidates are found. Any explicit
        @@ -3319,6 +3945,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
         
             def _create_query_builders(self):
                 """Set up and configure the vector and FTS query builders."""
        +        self._ensure_fragment_constraints_supported("this hybrid query")
                 vector_query, fts_query = self._validate_query(
                     self._query, self._vector, self._text
                 )
        @@ -3419,6 +4046,8 @@ class AsyncQueryBase(object):
                 self._with_row_id = None
                 self._blob_auto_row_id = False
                 self._blob_paths: tuple[str, ...] = ()
        +        # Set by the sync table path, which has already prepared blob row ids.
        +        self._blob_row_id_prepared = False
         
             def to_query_object(self) -> Query:
                 """
        @@ -3437,6 +4066,19 @@ class AsyncQueryBase(object):
             def _user_requested_row_id(self) -> bool:
                 return self._with_row_id is True
         
        +    def _ensure_fragment_constraints_supported(self, operation: str) -> None:
        +        _raise_unsupported_fragment_constraints(
        +            self._fragments,
        +            self._fragment_ids,
        +            operation=operation,
        +        )
        +
        +    def _inherit_fragment_constraints(self, query: Any) -> Any:
        +        """Carry a fragment selection across an async query conversion."""
        +        query._fragments = self._fragments
        +        query._fragment_ids = self._fragment_ids
        +        return query
        +
             def _blob_auto_row_id_enabled(self) -> bool:
                 return self._blob_auto_row_id
         
        @@ -3468,6 +4110,41 @@ class AsyncQueryBase(object):
                 self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
                 self._inner.with_row_id()
         
        +    def _maybe_add_blob_row_id_sync(self) -> None:
        +        if self._table is None:
        +            self._blob_auto_row_id = False
        +            self._blob_paths = ()
        +            return
        +
        +        req = self._inner.to_query_request()
        +        schema = self._table._schema_sync()
        +        projection = _query_request_projection(req)
        +        self._blob_auto_row_id = blob_auto_row_id_for_scan(
        +            schema,
        +            projection,
        +            with_row_id=self._with_row_id,
        +        )
        +        if not self._blob_auto_row_id:
        +            self._blob_paths = ()
        +            return
        +        self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
        +        self._inner.with_row_id()
        +
        +    async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
        +        if blob_mode != "bytes" or self._table is None:
        +            return False
        +        try:
        +            query = self.to_query_object()
        +        except NotImplementedError:
        +            return False
        +        return (
        +            _query_is_plain_blob_scan(query)
        +            and getattr(self, "_reranker", None) is None
        +            and not _query_needs_lance_scanner(self)
        +            and self._table._inner._is_native()
        +            and _supports_blob_fetch(self._table, self._table._pushdown_operations)
        +        )
        +
             def select(self, columns: Union[List[str], dict[str, str]]) -> Self:
                 """
                 Return only the specified columns.
        @@ -3532,15 +4209,32 @@ class AsyncQueryBase(object):
                 return self
         
             def with_fragments(self, fragments: Any) -> Self:
        -        """
        -        Restrict scanner-backed plain query results to the given Lance fragments.
        +        """Restrict an embedded plain-scan blob query to the given Lance fragments.
        +
        +        Fragment selection is supported only when ``to_pandas()`` uses the
        +        embedded Lance plain-scan path: the table is an embedded, non-memory
        +        Lance dataset, the query is a plain scan (no vector, full-text, take,
        +        postfilter, or ordering), and the selected output includes a blob
        +        column. The constraint is preserved when converting between async
        +        query types. Other terminals and remote tables raise
        +        ``NotImplementedError`` before scanning instead of silently scanning
        +        the full table. Blob-specific ``to_pandas()`` fallbacks keep their
        +        existing validation errors. Use ``fragment_ids()`` instead when
        +        ``scan_in_order(True)`` is set; fragment objects cannot be validated
        +        against the pinned dataset version.
                 """
                 self._fragments = fragments
                 return self
         
             def fragment_ids(self, fragment_ids: List[int]) -> Self:
        -        """
        -        Restrict scanner-backed plain query results to the given Lance fragment ids.
        +        """Restrict an embedded plain-scan blob query to the given fragment ids.
        +
        +        Fragment selection uses the same supported ``to_pandas()`` path as
        +        ``with_fragments()``. On that path, an empty list selects no rows and
        +        missing ids raise ``ValueError``. Other terminals and remote tables
        +        raise ``NotImplementedError`` before scanning instead of silently
        +        scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep
        +        their existing validation errors.
                 """
                 self._fragment_ids = fragment_ids
                 return self
        @@ -3555,6 +4249,11 @@ class AsyncQueryBase(object):
                 """
                 Execute the query and return the results as an Apache Arrow RecordBatchReader.
         
        +        A remote table decodes batches as they arrive when the server streams
        +        query results. If the response stops partway, reading raises
        +        [ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError]
        +        after the batches already returned, which are valid but incomplete.
        +
                 Parameters
                 ----------
         
        @@ -3567,11 +4266,14 @@ class AsyncQueryBase(object):
                     The maximum time to wait for the query to complete.
                     If not specified, no timeout is applied. If the query does not
                     complete within the specified time, an error will be raised.
        +            The timeout also covers reading the batches, so consuming them
        +            slowly can exceed it.
                 blob_mode: str, default "lazy"
        -            ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
        -            ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
        -            payloads one batch at a time, without requiring pylance. Bytes mode
        -            has the same restrictions as :meth:`to_arrow`.
        +            ``"lazy"`` keeps blob v2 descriptors and auto row ids for manual
        +            fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches
        +            supported row-addressable blob payloads one batch at a time, without
        +            requiring pylance. Bytes mode has the same restrictions as
        +            :meth:`to_arrow`.
         
                 Examples
                 --------
        @@ -3580,13 +4282,16 @@ class AsyncQueryBase(object):
                 """
                 blob_sources = await self._validated_blob_sources(blob_mode)
                 reader = await self._execute_batches(
        -            max_batch_length=max_batch_length, timeout=timeout
        +            max_batch_length=max_batch_length,
        +            timeout=timeout,
        +            blob_sources=blob_sources,
                 )
                 if blob_mode == "lazy":
                     return reader
         
                 async def convert(tbl: pa.Table) -> pa.Table:
        -            tbl = self._finalize_blob_query_table(tbl)
        +            if not (blob_mode == "bytes" and blob_sources):
        +                tbl = self._finalize_blob_query_table(tbl)
                     tbl = await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources)
                     if not self._user_requested_row_id() and "_rowid" in tbl.column_names:
                         tbl = tbl.drop_columns(["_rowid"])
        @@ -3602,13 +4307,56 @@ class AsyncQueryBase(object):
         
                 return AsyncRecordBatchReader._from_batches(schema, batches())
         
        +    async def _execute_eager(
        +        self,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        """Execute with the native eager collector used by ``to_arrow``."""
        +        self._ensure_fragment_constraints_supported("to_arrow()")
        +        if not self._blob_row_id_prepared:
        +            await self._maybe_add_blob_row_id()
        +        reader = await self._inner.execute_to_reader(None, timeout)
        +        return pa.Table.from_batches(reader, schema=reader.schema)
        +
        +    def _execute_eager_sync(
        +        self,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        """Execute with the synchronous native eager collector."""
        +        self._ensure_fragment_constraints_supported("to_arrow()")
        +        if not self._blob_row_id_prepared:
        +            self._maybe_add_blob_row_id_sync()
        +        reader = self._inner.execute_to_reader_sync(None, timeout)
        +        return pa.Table.from_batches(reader, schema=reader.schema)
        +
             async def _execute_batches(
                 self,
                 *,
                 max_batch_length: Optional[int] = None,
                 timeout: Optional[timedelta] = None,
        +        blob_sources: Optional[dict[str, str]] = None,
             ) -> AsyncRecordBatchReader:
        -        await self._maybe_add_blob_row_id()
        +        self._ensure_fragment_constraints_supported("to_batches()")
        +        if (
        +            blob_sources
        +            and not self._user_requested_row_id()
        +            and await self._can_fetch_plain_legacy_blobs("bytes")
        +        ):
        +            # Build a separate query so the hidden row id needed for byte
        +            # conversion cannot leak into later executions of this builder.
        +            query = self.to_query_object()
        +            query.with_row_id = True
        +            if self._table is None:
        +                raise RuntimeError("blob query is not bound to a table")
        +            row_id_query = self._table._sync_query_to_async(query)
        +            return await row_id_query._execute_batches(
        +                max_batch_length=max_batch_length,
        +                timeout=timeout,
        +            )
        +        if not self._blob_row_id_prepared:
        +            await self._maybe_add_blob_row_id()
                 return AsyncRecordBatchReader(
                     await self._inner.execute(
                         max_batch_length=max_batch_length, timeout=timeout
        @@ -3624,7 +4372,7 @@ class AsyncQueryBase(object):
                 return await self._inner.output_schema()
         
             async def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
        -        """Map projected blob v2 outputs to their source columns.
        +        """Map projected blob outputs to their source columns.
         
                 Bytes mode is checked here, before the query runs.
                 """
        @@ -3634,15 +4382,22 @@ class AsyncQueryBase(object):
                     return {}
                 schema = await self._table.schema()
                 projection = _query_request_projection(self._inner.to_query_request())
        -        blob_sources = blob_v2_projection_sources(schema, projection)
        +        blob_sources = blob_projection_sources(
        +            schema,
        +            projection,
        +            include_legacy=await self._can_fetch_plain_legacy_blobs(blob_mode),
        +        )
                 if blob_mode != "bytes":
                     return blob_sources
                 reject_unfetchable_blob_columns(schema, projection, blob_sources)
        -        if blob_sources and not _supports_local_blob_fetch(
        +        if blob_sources and not _supports_blob_fetch(
                     self._table, self._table._pushdown_operations
                 ):
                     raise _blob_bytes_without_snapshot_error()
        -        reject_unmatched_blob_outputs(await self._blob_output_schema(), blob_sources)
        +        if self._table._inner._is_native():
        +            reject_unmatched_blob_outputs(
        +                await self._blob_output_schema(), blob_sources
        +            )
                 return blob_sources
         
             async def _blob_output_schema(self) -> pa.Schema:
        @@ -3655,9 +4410,21 @@ class AsyncQueryBase(object):
                     return tbl
                 if blob_mode == "descriptions":
                     return strip_auto_row_ids(tbl, blob_sources)
        -        return await replace_v2_blob_columns_with_bytes(
        -            tbl, blob_sources, self._table.fetch_blobs
        -        )
        +        reject_unmatched_blob_outputs(tbl.schema, blob_sources)
        +        if (
        +            self._table is not None
        +            and not self._table._inner._is_native()
        +            and blob_sources
        +        ):
        +            version, identity = _remote_blob_snapshot(tbl.schema)
        +
        +            async def fetch_blobs(column, row_ids):
        +                return await self._table._inner.fetch_blobs(
        +                    column, row_ids, version=version, snapshot_identity=identity
        +                )
        +        else:
        +            fetch_blobs = self._table.fetch_blobs
        +        return await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
         
             async def to_arrow(
                 self,
        @@ -3681,15 +4448,26 @@ class AsyncQueryBase(object):
                 blob_mode: str, default "lazy"
                     ``"lazy"`` returns blob v2 descriptors that carry the row id
                     ``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
        -            ``"bytes"`` returns payload bytes and raises for legacy blob columns
        -            and blobs inside lists.
        -            LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``.
        +            ``"bytes"`` returns payload bytes for supported row-addressable blob
        +            columns and raises for blobs inside lists.
        +            Enterprise queries fetch bytes at the version reported by the query
        +            response. Namespace query pushdown refuses ``"bytes"``.
                 """
                 blob_sources = await self._validated_blob_sources(blob_mode)
        -        batch_iter = await self.to_batches(timeout=timeout)
        -        tbl = self._finalize_blob_query_table(
        -            pa.Table.from_batches(await batch_iter.read_all(), schema=batch_iter.schema)
        -        )
        +        if blob_mode == "bytes" and blob_sources:
        +            reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode)
        +            return pa.Table.from_batches(await reader.read_all(), schema=reader.schema)
        +        if blob_mode != "lazy":
        +            batch_iter = await self.to_batches(timeout=timeout)
        +            tbl = self._finalize_blob_query_table(
        +                pa.Table.from_batches(
        +                    await batch_iter.read_all(), schema=batch_iter.schema
        +                )
        +            )
        +        else:
        +            tbl = self._finalize_blob_query_table(
        +                await self._execute_eager(timeout=timeout)
        +            )
                 return await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources)
         
             async def to_list(
        @@ -3758,13 +4536,13 @@ class AsyncQueryBase(object):
                 blob_mode: str, default "lazy"
                     Controls how blob columns are returned. Local blob v2 queries support
                     ``"bytes"`` and ``"descriptions"`` without pylance. Eligible local
        -            plain scans use pylance's scanner for lazy blob handles in ``"lazy"``
        -            mode and for legacy blob columns. Other local blob v2
        -            queries return descriptors in ``"lazy"`` and ``"descriptions"``
        -            modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
        -            LanceDB Enterprise blob queries support only ``"descriptions"`` until a
        -            stable
        -            table snapshot can bind the query and blob fetches.
        +            plain scans also support ``"bytes"`` for row-addressable legacy blob
        +            columns without pylance. Other local blob v2 queries return
        +            descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
        +            in ``"bytes"`` mode, through :meth:`to_arrow`.
        +            Enterprise queries support ``"bytes"`` at the query response's
        +            snapshot and ``"descriptions"`` without payload reads. Remote
        +            ``"lazy"`` handles are not supported.
                 **kwargs
                     Forwarded to pyarrow.Table.to_pandas after query execution and
                     optional flattening.
        @@ -3772,6 +4550,9 @@ class AsyncQueryBase(object):
                 validate_blob_mode(blob_mode)
                 if self._table is not None and not self._table._inner._is_native():
                     await self._validated_blob_sources(blob_mode)
        +            if blob_mode == "bytes":
        +                tbl = await self.to_arrow(timeout=timeout, blob_mode=blob_mode)
        +                return flatten_columns(tbl, flatten).to_pandas(**kwargs)
                     return await self._remote_to_pandas(
                         flatten=flatten, timeout=timeout, blob_mode=blob_mode, **kwargs
                     )
        @@ -3839,21 +4620,27 @@ class AsyncQueryBase(object):
                     with_row_id=self._with_row_id,
                 )
                 blob_sources = (
        -            blob_v2_projection_sources(schema, query.columns)
        +            blob_projection_sources(
        +                schema,
        +                query.columns,
        +                include_legacy=await self._can_fetch_plain_legacy_blobs(blob_mode),
        +            )
                     if blob_mode == "bytes"
                     else {}
                 )
        -        if blob_sources:
        +        if blob_mode == "bytes":
                     reject_unfetchable_blob_columns(schema, query.columns, blob_sources)
                 # Remote and in-memory tables have no Lance dataset to scan.
                 if not self._table._inner._is_native() or (
                     get_uri_scheme(await self._table.uri()) == "memory"
                 ):
                     return None
        -        if (
        -            blob_mode != "lazy"
        -            and not _query_needs_lance_scanner(self)
        -            and blob_v2_projection_sources(schema, query.columns)
        +        if not _query_needs_lance_scanner(self) and (
        +            (blob_mode == "bytes" and blob_sources)
        +            or (
        +                blob_mode == "descriptions"
        +                and blob_v2_projection_sources(schema, query.columns)
        +            )
                 ):
                     return None
                 try:
        @@ -3967,6 +4754,7 @@ class AsyncQueryBase(object):
                 -------
                 plan : str
                 """  # noqa: E501
        +        self._ensure_fragment_constraints_supported("explain_plan()")
                 return await self._inner.explain_plan(verbose)
         
             async def analyze_plan(
        @@ -3984,6 +4772,7 @@ class AsyncQueryBase(object):
                 -------
                 plan : str
                 """
        +        self._ensure_fragment_constraints_supported("analyze_plan()")
                 return await self._inner.analyze_plan(distributed_metrics)
         
         
        @@ -4019,9 +4808,11 @@ class AsyncStandardQuery(AsyncQueryBase):
                 >>> predicate = "x > 10"
                 >>> predicate = "y > 0 AND y < 100"
                 >>> predicate = "x > 5 OR y = 'test'"
        +        >>> predicate = "ST_Intersects(geom, ST_GeomFromText('POINT (1 2)'))"
         
                 Filtering performance can often be improved by creating a scalar index
        -        on the filter column(s).
        +        on the filter column(s). Spatial predicates on GeoArrow columns use an
        +        [RTree][lancedb.index.RTree] index.
         
                 Calling this multiple times combines the filters with a logical AND
                 rather than replacing the previous filter.
        @@ -4054,20 +4845,36 @@ class AsyncStandardQuery(AsyncQueryBase):
                 self._inner.offset(offset)
                 return self
         
        -    def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self:
        +    def order_by(self, ordering: _OrderingInput = None) -> Self:
                 """
                 Set the ordering for the results.
         
                 Parameters
                 ----------
        -        ordering: Optional[List[ColumnOrdering]]
        -            The ordering to use for the results.  If None, then the default ordering
        -            will be used.
        +        ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]]
        +            The ordering to use for the results. Each entry can be a column
        +            name, a ``(column_name, "asc"|"desc")`` tuple, a
        +            [ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a
        +            ``column_name`` key. A bare tuple is a single direction pair, while
        +            a list contains separate orderings, so ``("a", "desc")`` sorts by
        +            ``a`` descending and ``["a", "desc"]`` sorts by both columns.
        +            Pass ``None`` or an empty list to clear the ordering.
        +
        +        Examples
        +        --------
        +        >>> import lancedb
        +        >>> db = await lancedb.connect_async("memory://")  # doctest: +SKIP
        +        >>> table = await db.create_table(  # doctest: +SKIP
        +        ...     "ordering", [{"name": "b"}, {"name": "a"}]
        +        ... )
        +        >>> await table.query().order_by(["name"]).to_list()  # doctest: +SKIP
        +        [{'name': 'a'}, {'name': 'b'}]
                 """
        -        if ordering is None:
        +        normalized = _normalize_ordering(ordering)
        +        if normalized is None:
                     self._inner.order_by(None)
                 else:
        -            self._inner.order_by([o.model_dump() for o in ordering])
        +            self._inner.order_by([o.model_dump() for o in normalized])
                 return self
         
             def fast_search(self) -> Self:
        @@ -4138,6 +4945,72 @@ class AsyncQuery(AsyncStandardQuery):
                 super().__init__(inner, table)
                 self._inner = inner
         
        +    def _execute_batches_sync(
        +        self,
        +        *,
        +        max_batch_length: Optional[int] = None,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.RecordBatchReader:
        +        """Execute a plain local scan with one Rust fetch per batch.
        +
        +        The query starts once; each iteration asks the same Rust stream for a
        +        single batch instead of submitting one Python future per batch to the
        +        background event loop. The public reader type and schema come from the
        +        same stream, so Arrow export and exception behavior stay unchanged.
        +        """
        +        self._ensure_fragment_constraints_supported("to_batches()")
        +        stream = self._inner.execute_sync(max_batch_length, timeout)
        +        return pa.RecordBatchReader.from_batches(stream.schema, stream)
        +
        +    def scan_in_order(self, ordered: bool = True) -> Self:
        +        """Control whether an ordinary scan must preserve storage order.
        +
        +        Parameters
        +        ----------
        +        ordered: bool, default True
        +            ``True`` requires manifest order: fragments in manifest order, then
        +            rows in fragment order. ``False`` allows the backend to scan
        +            unordered. Leave the method uncalled to preserve the backend
        +            default.
        +
        +        An unfiltered plain base-only scan of an Embedded table, pinned to one
        +        dataset version, returns manifest order by default. RTE tables scan the
        +        LSM by default and do not provide this guarantee unless
        +        ``use_rte(False)`` selects the base table. Explicit ``True`` also
        +        disables scalar-index filter planning, because legacy scalar-index plans
        +        can return a different sequence; default filtered scans can still use
        +        those plans and may not preserve manifest order. Filters still apply,
        +        but the scan can read more data. ``with_fragments()`` is not supported
        +        with ``True`` because fragment objects cannot be validated against the
        +        pinned dataset version; use ``fragment_ids()`` instead, which resolves
        +        ids from the manifest and remains ordered. Compaction, updates, or
        +        opening a newer version can change that order, so pin the table version
        +        when positions must remain stable across executions. An explicit
        +        ``order_by()`` replaces manifest order with a global sort, and vector,
        +        full-text, hybrid, or reranked queries return ranked results; combining
        +        those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise
        +        tables and RTE/LSM reads raise ``NotImplementedError`` because they
        +        cannot uphold the order; set ``use_rte(False)`` to read the RTE base
        +        table in storage order. When ``QueryTable`` pushdown is enabled, the
        +        backend default may not preserve order; requesting ``True`` executes
        +        against Embedded storage instead, because the namespace request has no
        +        order field.
        +
        +        Examples
        +        --------
        +        >>> import asyncio
        +        >>> import lancedb
        +        >>> async def example():
        +        ...     db = await lancedb.connect_async("memory://")
        +        ...     table = await db.create_table("scan_in_order_async", [{"id": 1}])
        +        ...     query = table.query().scan_in_order(True).select(["id"])
        +        ...     return (await query.to_arrow())["id"].to_pylist()
        +        >>> asyncio.run(example())
        +        [1]
        +        """
        +        self._inner.scan_in_order(ordered)
        +        return self
        +
             @classmethod
             def _query_vec_to_array(self, vec: Union[VEC, Tuple]):
                 if isinstance(vec, list):
        @@ -4221,15 +5094,25 @@ class AsyncQuery(AsyncStandardQuery):
                     new_self = self._inner.nearest_to(query_vectors[0])
                     for v in query_vectors[1:]:
                         new_self.add_query_vector(v)
        -            return AsyncVectorQuery(new_self, self._table)
        +            return self._inherit_fragment_constraints(
        +                AsyncVectorQuery(new_self, self._table)
        +            )
                 else:
        -            return AsyncVectorQuery(
        -                self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)),
        -                self._table,
        +            return self._inherit_fragment_constraints(
        +                AsyncVectorQuery(
        +                    self._inner.nearest_to(
        +                        AsyncQuery._query_vec_to_array(query_vector)
        +                    ),
        +                    self._table,
        +                )
                     )
         
             def nearest_to_text(
        -        self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None
        +        self,
        +        query: str | FullTextQuery,
        +        columns: Union[str, List[str], None] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> AsyncFTSQuery:
                 """
                 Find the documents that are most relevant to the given text query.
        @@ -4250,19 +5133,33 @@ class AsyncQuery(AsyncStandardQuery):
                 columns: str or list of str, default None
                     The columns to search in. If None, all indexed columns are searched.
                     For now only one column can be searched at a time.
        +        operator: "AND" or "OR", optional
        +            Combine terms in a string query. Defaults to OR. Quoted strings use
        +            phrase semantics and require an index built with positions.
                 """
        +        fts_query = FullTextSearchQuery(query=query, operator=operator)
                 if isinstance(columns, str):
                     columns = [columns]
                 if columns is None:
                     columns = []
         
                 if isinstance(query, str):
        -            return AsyncFTSQuery(
        -                self._inner.nearest_to_text({"query": query, "columns": columns}),
        -                self._table,
        +            return self._inherit_fragment_constraints(
        +                AsyncFTSQuery(
        +                    self._inner.nearest_to_text(
        +                        {
        +                            "query": query,
        +                            "columns": columns,
        +                            "operator": fts_query.operator,
        +                        }
        +                    ),
        +                    self._table,
        +                )
                     )
                 # FullTextQuery object
        -        return AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table)
        +        return self._inherit_fragment_constraints(
        +            AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table)
        +        )
         
         
         class AsyncFTSQuery(AsyncStandardQuery):
        @@ -4273,6 +5170,23 @@ class AsyncFTSQuery(AsyncStandardQuery):
                 self._inner = inner
                 self._reranker = None
         
        +    async def count_rows(self) -> int:
        +        """Count all full-text matches satisfying the query's filter.
        +
        +        Ignores limit, offset, selection, ordering, and reranking. ``fast_search``
        +        still restricts the count to indexed data. Matching scores are streamed
        +        without loading document columns, so counting may scan every match.
        +
        +        For example, ``await table.query().nearest_to_text("gripper closed",``
        +        ``operator="AND").where("active = true").count_rows()``.
        +        """
        +        self._ensure_fragment_constraints_supported("count_rows()")
        +        try:
        +            return await self._inner.count_rows()
        +        except Exception as error:
        +            _add_fts_position_error_note(error)
        +            raise
        +
             def get_query(self) -> str:
                 return self._inner.get_query()
         
        @@ -4352,23 +5266,72 @@ class AsyncFTSQuery(AsyncStandardQuery):
                     new_self = self._inner.nearest_to(query_vectors[0])
                     for v in query_vectors[1:]:
                         new_self.add_query_vector(v)
        -            return AsyncHybridQuery(new_self, self._table)
        -        else:
        -            return AsyncHybridQuery(
        -                self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)),
        -                self._table,
        +            return self._inherit_fragment_constraints(
        +                AsyncHybridQuery(new_self, self._table)
                     )
        +        else:
        +            return self._inherit_fragment_constraints(
        +                AsyncHybridQuery(
        +                    self._inner.nearest_to(
        +                        AsyncQuery._query_vec_to_array(query_vector)
        +                    ),
        +                    self._table,
        +                )
        +            )
        +
        +    async def _execute_eager(
        +        self,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        try:
        +            results = await super()._execute_eager(timeout=timeout)
        +        except Exception as error:
        +            _add_fts_position_error_note(error)
        +            raise
        +        if self._reranker:
        +            source = results
        +            results = self._reranker.rerank_fts(self.get_query(), results)
        +            results = _merge_query_snapshot(results, source)
        +        return results
        +
        +    def _execute_eager_sync(
        +        self,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        try:
        +            results = super()._execute_eager_sync(timeout=timeout)
        +        except Exception as error:
        +            _add_fts_position_error_note(error)
        +            raise
        +        if self._reranker:
        +            source = results
        +            results = self._reranker.rerank_fts(self.get_query(), results)
        +            results = _merge_query_snapshot(results, source)
        +        return results
         
             async def _execute_batches(
                 self,
                 *,
                 max_batch_length: Optional[int] = None,
                 timeout: Optional[timedelta] = None,
        +        blob_sources: Optional[dict[str, str]] = None,
             ) -> AsyncRecordBatchReader:
        -        reader = await super()._execute_batches(timeout=timeout)
        -        results = pa.Table.from_batches(await reader.read_all(), reader.schema)
        +        try:
        +            reader = await super()._execute_batches(
        +                max_batch_length=max_batch_length,
        +                timeout=timeout,
        +                blob_sources=blob_sources,
        +            )
        +            results = pa.Table.from_batches(await reader.read_all(), reader.schema)
        +        except Exception as error:
        +            _add_fts_position_error_note(error)
        +            raise
                 if self._reranker:
        +            source = results
                     results = self._reranker.rerank_fts(self.get_query(), results)
        +            results = _merge_query_snapshot(results, source)
                 return AsyncRecordBatchReader(results, max_batch_length=max_batch_length)
         
         
        @@ -4421,6 +5384,11 @@ class AsyncVectorQueryBase:
             def search_effort(self, search_effort: Optional[float]) -> Self:
                 """Set the initial IVF search effort to a finite value in [0, 1].
         
        +        Efforts 0.1 and 0.25 target empirical mean partition-routing recall of
        +        80% and 90% for L2, cosine and dot through k=100000. The probe budget
        +        adapts to the metric and k. Hamming and larger k remain uncalibrated;
        +        100000 is not an API limit. Remote queries also require server support.
        +
                 None preserves Auto (internally 0.5) and fixed nprobes. Any explicit
                 effort, including 0.5, overrides nprobes in either call order; explicit
                 minimum and maximum bounds remain effective. Zero starts at the caller
        @@ -4637,7 +5605,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
                 return self
         
             def nearest_to_text(
        -        self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None
        +        self,
        +        query: str | FullTextQuery,
        +        columns: Union[str, List[str], None] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> AsyncHybridQuery:
                 """
                 Find the documents that are most relevant to the given text query,
        @@ -4662,32 +5634,76 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
                 columns: str or list of str, default None
                     The columns to search in. If None, all indexed columns are searched.
                     For now only one column can be searched at a time.
        +        operator: "AND" or "OR", optional
        +            Combine terms in a string query. Defaults to OR.
                 """
        +        fts_query = FullTextSearchQuery(query=query, operator=operator)
                 if isinstance(columns, str):
                     columns = [columns]
                 if columns is None:
                     columns = []
         
                 if isinstance(query, str):
        -            return AsyncHybridQuery(
        -                self._inner.nearest_to_text({"query": query, "columns": columns}),
        -                self._table,
        +            return self._inherit_fragment_constraints(
        +                AsyncHybridQuery(
        +                    self._inner.nearest_to_text(
        +                        {
        +                            "query": query,
        +                            "columns": columns,
        +                            "operator": fts_query.operator,
        +                        }
        +                    ),
        +                    self._table,
        +                )
                     )
                 # FullTextQuery object
        -        return AsyncHybridQuery(
        -            self._inner.nearest_to_text({"query": query}), self._table
        +        return self._inherit_fragment_constraints(
        +            AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table)
                 )
         
        +    async def _execute_eager(
        +        self,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        results = await super()._execute_eager(timeout=timeout)
        +        if self._reranker:
        +            source = results
        +            results = self._reranker.rerank_vector(self._query_string, results)
        +            results = _merge_query_snapshot(results, source)
        +        return results
        +
        +    def _execute_eager_sync(
        +        self,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        results = super()._execute_eager_sync(timeout=timeout)
        +        if self._reranker:
        +            source = results
        +            results = self._reranker.rerank_vector(self._query_string, results)
        +            results = _merge_query_snapshot(results, source)
        +        return results
        +
             async def _execute_batches(
                 self,
                 *,
                 max_batch_length: Optional[int] = None,
                 timeout: Optional[timedelta] = None,
        +        blob_sources: Optional[dict[str, str]] = None,
             ) -> AsyncRecordBatchReader:
        -        reader = await super()._execute_batches(timeout=timeout)
        +        reader = await super()._execute_batches(
        +            max_batch_length=max_batch_length,
        +            timeout=timeout,
        +            blob_sources=blob_sources,
        +        )
        +        if self._reranker is None:
        +            return reader
                 results = pa.Table.from_batches(await reader.read_all(), reader.schema)
                 if self._reranker:
        +            source = results
                     results = self._reranker.rerank_vector(self._query_string, results)
        +            results = _merge_query_snapshot(results, source)
                 return AsyncRecordBatchReader(results, max_batch_length=max_batch_length)
         
         
        @@ -4758,6 +5774,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
                 the hybrid query itself. The key the legs are fused on, if any, is left
                 on `self._pk_fusion`.
                 """
        +        self._ensure_fragment_constraints_supported("this hybrid query")
                 fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table)
                 vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table)
         
        @@ -4807,16 +5824,28 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
         
                 return fts_query, vec_query, limit, offset
         
        +    async def _execute_eager(
        +        self,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        self._ensure_fragment_constraints_supported("to_arrow()")
        +        reader = await self._execute_batches(timeout=timeout)
        +        return pa.Table.from_batches(await reader.read_all(), schema=reader.schema)
        +
             async def _execute_batches(
                 self,
                 *,
                 max_batch_length: Optional[int] = None,
                 timeout: Optional[timedelta] = None,
        +        blob_sources: Optional[dict[str, str]] = None,
             ) -> AsyncRecordBatchReader:
                 # WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s.
                 return await _wal_hybrid.with_pk_fallback_async(
                     lambda: self._run_hybrid(
        -                max_batch_length=max_batch_length, timeout=timeout
        +                max_batch_length=max_batch_length,
        +                timeout=timeout,
        +                blob_sources=blob_sources,
                     ),
                     self._table,
                     fused=lambda: self._pk_fusion is not None,
        @@ -4828,19 +5857,18 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
                 *,
                 max_batch_length: Optional[int] = None,
                 timeout: Optional[timedelta] = None,
        +        blob_sources: Optional[dict[str, str]] = None,
             ) -> AsyncRecordBatchReader:
                 fts_query, vec_query, limit, offset = await self._create_child_queries()
         
                 req = fts_query._inner.to_query_request()
        -        blob_auto_row_id = False
        +        blob_auto_row_id = bool(blob_sources)
                 blob_paths: tuple[str, ...] = ()
                 if self._table is not None:
                     schema = await self._table.schema()
                     projection = _query_request_projection(req)
        -            blob_auto_row_id = blob_auto_row_id_for_scan(
        -                schema,
        -                projection,
        -                with_row_id=self._with_row_id,
        +            blob_auto_row_id = blob_auto_row_id or blob_auto_row_id_for_scan(
        +                schema, projection, with_row_id=self._with_row_id
                     )
                     if blob_auto_row_id:
                         blob_paths = tuple(
        @@ -4877,6 +5905,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
                 ):
                     result = result.drop(["_rowid"])
         
        +        result = _merge_query_snapshot(result, fts_results, vector_results)
                 return AsyncRecordBatchReader(result, max_batch_length=max_batch_length)
         
             async def explain_plan(self, verbose: Optional[bool] = False):
        @@ -5051,15 +6080,26 @@ class BaseQueryBuilder(object):
                 return self
         
             def with_fragments(self, fragments: Any) -> Self:
        -        """
        -        Restrict scanner-backed plain query results to the given Lance fragments.
        +        """Restrict execution to the given Lance fragments.
        +
        +        Fragment selection is supported only by embedded plain-scan blob
        +        queries through ``to_pandas()``. Other terminals and remote tables
        +        raise ``NotImplementedError`` before scanning instead of silently
        +        scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep
        +        their existing validation errors.
                 """
                 self._inner.with_fragments(fragments)
                 return self
         
             def fragment_ids(self, fragment_ids: List[int]) -> Self:
        -        """
        -        Restrict scanner-backed plain query results to the given Lance fragment ids.
        +        """Restrict execution to the given Lance fragment ids.
        +
        +        Fragment selection is supported only by embedded plain-scan blob
        +        queries through ``to_pandas()``. On that path, an empty list selects no
        +        rows and missing ids raise ``ValueError``. Other terminals and remote
        +        tables raise ``NotImplementedError`` before scanning instead of
        +        silently scanning the full table. Blob-specific ``to_pandas()``
        +        fallbacks keep their existing validation errors.
                 """
                 self._inner.fragment_ids(fragment_ids)
                 return self
        @@ -5094,6 +6134,8 @@ class BaseQueryBuilder(object):
                     The maximum time to wait for the query to complete.
                     If not specified, no timeout is applied. If the query does not
                     complete within the specified time, an error will be raised.
        +            The timeout also covers reading the batches, so consuming them
        +            slowly can exceed it.
                 blob_mode: str, default "lazy"
                     Controls blob conversion as described in
                     :meth:`AsyncQueryBase.to_batches`.
        @@ -5135,8 +6177,7 @@ class BaseQueryBuilder(object):
                 blob_mode: str, default "lazy"
                     ``"lazy"`` returns blob v2 descriptors that carry the row id
                     ``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
        -            ``"bytes"`` returns payload bytes and raises for legacy blob columns
        -            and blobs inside lists.
        +            ``"bytes"`` is not supported for remote or pushdown blob queries.
                 """
                 return LOOP.run(self._inner.to_arrow(timeout, blob_mode=blob_mode))
         
        diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py
        index 8453de125..439e89100 100644
        --- a/python/python/lancedb/remote/db.py
        +++ b/python/python/lancedb/remote/db.py
        @@ -4,6 +4,8 @@
         
         from __future__ import annotations
         
        +from lancedb.server_info import ServerInfo
        +
         from dataclasses import replace
         from datetime import timedelta
         import json
        @@ -37,8 +39,8 @@ import pyarrow as pa
         
         from ..common import DATA
         from lancedb.listing import Listing, NamespaceListing, TableListing
        -from ..db import DBConnection, LOOP
        -from ..functions import FunctionVersion, UdfDefinition
        +from ..db import DBConnection, LOOP, _normalize_function_version
        +from ..functions import FunctionVersion, FunctionDefinition
         from ..graph import EdgeTable, NodeTable, PropertyGraph
         from ..job import AsyncJob, Job
         from ..sql import Query as SqlQuery
        @@ -60,6 +62,7 @@ from lance_namespace import (
         from ..pydantic import LanceModel
         from ..table import Table
         from ..util import validate_table_name
        +from ..resources import _resource_options
         
         
         def _duration_seconds(value: Optional[timedelta]) -> Optional[float]:
        @@ -214,6 +217,7 @@ class RemoteDBConnection(DBConnection):
                 client_config,
                 oauth_config,
                 sql_host_override,
        +        storage_options,
             ):
                 config = (
                     ClientConfig(**client_config)
        @@ -233,7 +237,7 @@ class RemoteDBConnection(DBConnection):
                 result.region = "us-east-1"
                 result.host_override = endpoint
                 result.sql_host_override = sql_host_override
        -        result.storage_options = None
        +        result.storage_options = storage_options
                 result.client_config = replace(config, extra_headers=headers)
                 result._catalog_oauth = oauth_config is not None
                 result._conn = inner
        @@ -430,7 +434,11 @@ class RemoteDBConnection(DBConnection):
                 page_token: Optional[str] = None,
                 limit: Optional[int] = None,
             ) -> TableListing:
        -        """List a page of tables in this database.
        +        """Iterate over all tables in this database, fetching pages as needed.
        +
        +        The ``tables`` attribute contains only the current page (100 names by
        +        default). Iterate over the listing to visit all pages, or use
        +        ``table_exists([name])`` to check for a particular table.
         
                 Parameters
                 ----------
        @@ -468,7 +476,9 @@ class RemoteDBConnection(DBConnection):
                 """List the names of all tables in the database.
         
                 .. deprecated::
        -            Use :meth:`list_tables` instead, which provides proper pagination support.
        +            Iterate over :meth:`list_tables` to get all names, or use
        +            :meth:`table_exists` to check for a particular table. The listing's
        +            ``tables`` attribute contains only one page.
         
                 Parameters
                 ----------
        @@ -488,7 +498,8 @@ class RemoteDBConnection(DBConnection):
                 import warnings
         
                 warnings.warn(
        -            "table_names() is deprecated, use list_tables() instead",
        +            "table_names() is deprecated, iterate list_tables() for all names "
        +            "or use table_exists([name]) to check existence",
                     DeprecationWarning,
                     stacklevel=2,
                 )
        @@ -566,6 +577,7 @@ class RemoteDBConnection(DBConnection):
                 source_version: Optional[int] = None,
                 source_tag: Optional[str] = None,
                 is_shallow: bool = True,
        +        exist_ok: bool = False,
             ) -> Table:
                 """Clone a table from a source table.
         
        @@ -585,6 +597,8 @@ class RemoteDBConnection(DBConnection):
                 is_shallow: bool, default True
                     Whether to perform a shallow clone (True) or deep clone (False).
                     Currently only shallow clone is supported.
        +        exist_ok: bool, default False
        +            Return the existing target unchanged instead of cloning over it.
         
                 Returns
                 -------
        @@ -602,6 +616,7 @@ class RemoteDBConnection(DBConnection):
                         source_version=source_version,
                         source_tag=source_tag,
                         is_shallow=is_shallow,
        +                exist_ok=exist_ok,
                     )
                 )
                 return RemoteTable(
        @@ -627,6 +642,8 @@ class RemoteDBConnection(DBConnection):
                 storage_options: Optional[Dict[str, str]] = None,
                 data_storage_version: Optional[str] = None,
                 enable_v2_manifest_paths: Optional[bool] = None,
        +        initial_bases: Optional[List[Any]] = None,
        +        allow_external_blob_outside_bases: bool = False,
             ) -> Table:
                 """Create a [Table][lancedb.table.Table] in the database.
         
        @@ -672,6 +689,10 @@ class RemoteDBConnection(DBConnection):
                     Not supported in LanceDB Enterprise. Raises NotImplementedError.
                 enable_v2_manifest_paths: bool, optional
                     Not supported in LanceDB Enterprise. Raises NotImplementedError.
        +        initial_bases: list, optional
        +            Not supported in LanceDB Enterprise. Raises NotImplementedError.
        +        allow_external_blob_outside_bases: bool, default False
        +            Not supported in LanceDB Enterprise. Raises NotImplementedError.
         
                 Returns
                 -------
        @@ -747,6 +768,16 @@ class RemoteDBConnection(DBConnection):
                             f"{option} is not supported for table creation in "
                             "LanceDB Enterprise"
                         )
        +        if initial_bases:
        +            raise NotImplementedError(
        +                "initial_bases is not supported for table creation in "
        +                "LanceDB Enterprise"
        +            )
        +        if allow_external_blob_outside_bases:
        +            raise NotImplementedError(
        +                "allow_external_blob_outside_bases is not supported for table "
        +                "creation in LanceDB Enterprise"
        +            )
                 if exist_ok:
                     if mode == "create":
                         mode = "exist_ok"
        @@ -782,27 +813,48 @@ class RemoteDBConnection(DBConnection):
             def create_materialized_view(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: SelectArg = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
        +        exist_ok: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> MaterializedView:
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 from .table import RemoteTable
         
                 view = LOOP.run(
                     self._conn.create_materialized_view(
                         name,
                         source,
        +                query=query,
                         select=select,
                         where=where,
                         limit=limit,
                         with_no_data=with_no_data,
        +                exist_ok=exist_ok,
                         auto_refresh_enabled=auto_refresh_enabled,
                         auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                total_gpu_count=total_gpu_count,
        +                gpu_class=gpu_class,
        +                gpu_count=gpu_count,
                     )
                 )
                 return MaterializedView(
        @@ -818,25 +870,46 @@ class RemoteDBConnection(DBConnection):
             def create_materialized_view_async(
                 self,
                 name: str,
        -        source: MaterializedViewSource,
        +        source: Optional[MaterializedViewSource] = None,
                 *,
        +        query: Optional[str] = None,
                 select: SelectArg = None,
                 where: Optional[str] = None,
                 limit: Optional[int] = None,
                 with_no_data: bool = False,
        +        exist_ok: bool = False,
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[float] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> Job[None]:
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 job = LOOP.run(
                     self._conn.create_materialized_view_async(
                         name,
                         source,
        +                query=query,
                         select=select,
                         where=where,
                         limit=limit,
                         with_no_data=with_no_data,
        +                exist_ok=exist_ok,
                         auto_refresh_enabled=auto_refresh_enabled,
                         auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                total_gpu_count=total_gpu_count,
        +                gpu_class=gpu_class,
        +                gpu_count=gpu_count,
                     )
                 )
                 return Job(job)
        @@ -958,6 +1031,13 @@ class RemoteDBConnection(DBConnection):
                 """
                 return Job(LOOP.run(self._conn.open_job(job_id)))
         
        +    @override
        +    def server_info(self) -> ServerInfo:
        +        """Read the responding server's build information. See
        +        [DBConnection.server_info][lancedb.db.DBConnection.server_info].
        +        """
        +        return LOOP.run(self._conn.server_info())
        +
             @override
             def list_gpu_classes(self) -> List[GpuClass]:
                 """List configured Function GPU classes. See
        @@ -968,14 +1048,20 @@ class RemoteDBConnection(DBConnection):
             @override
             def create_function_async(
                 self,
        -        definition: UdfDefinition,
        +        definition: FunctionDefinition,
                 *,
                 secrets: Optional[Sequence[EnvVarSecret]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
        +        refresh_lock: bool = False,
             ) -> Job[FunctionVersion]:
                 job = LOOP.run(
                     self._conn.create_function_async(
        -                definition, secrets=secrets, namespace_path=namespace_path
        +                definition,
        +                secrets=secrets,
        +                exist_ok=exist_ok,
        +                namespace_path=namespace_path,
        +                refresh_lock=refresh_lock,
                     )
                 )
                 return Job(job)
        @@ -985,9 +1071,10 @@ class RemoteDBConnection(DBConnection):
                 self,
                 name: str,
                 *,
        -        version: str,
        +        version: Optional[Union[int, str]] = None,
                 namespace_path: Optional[List[str]] = None,
             ) -> FunctionVersion:
        +        version = _normalize_function_version(version)
                 return LOOP.run(
                     self._conn.get_function(
                         name, version=version, namespace_path=namespace_path
        @@ -1024,11 +1111,14 @@ class RemoteDBConnection(DBConnection):
                 version: str,
                 namespace_path: Optional[List[str]] = None,
             ) -> bool:
        -        return LOOP.run(
        -            self._conn.drop_function(
        +        dropped, drop_warnings = LOOP.run(
        +            self._conn._drop_function_with_warnings(
                         name, version=version, namespace_path=namespace_path
                     )
                 )
        +        for warning in drop_warnings:
        +            warnings.warn(warning, UserWarning, stacklevel=2)
        +        return dropped
         
             @override
             def drop_function_async(
        @@ -1060,8 +1150,12 @@ class RemoteDBConnection(DBConnection):
                 azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
                 azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
                 azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
        +        azure_storage_account_access_key_secret: Optional[
        +            Union[str, SecretReference]
        +        ] = None,
                 gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
                 huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
        +        exist_ok: bool = False,
                 namespace_path: Optional[List[str]] = None,
             ) -> StorageIntegrationInfo:
                 return LOOP.run(
        @@ -1077,8 +1171,10 @@ class RemoteDBConnection(DBConnection):
                         azure_tenant_id_secret=azure_tenant_id_secret,
                         azure_client_id_secret=azure_client_id_secret,
                         azure_client_secret_secret=azure_client_secret_secret,
        +                azure_storage_account_access_key_secret=azure_storage_account_access_key_secret,
                         gcp_credentials_json_secret=gcp_credentials_json_secret,
                         huggingface_token_secret=huggingface_token_secret,
        +                exist_ok=exist_ok,
                         namespace_path=namespace_path,
                     )
                 )
        @@ -1117,9 +1213,18 @@ class RemoteDBConnection(DBConnection):
         
             @override
             def create_secret(
        -        self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        value: str,
        +        *,
        +        exist_ok: bool = False,
        +        namespace_path: Optional[List[str]] = None,
             ) -> None:
        -        LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
        +        LOOP.run(
        +            self._conn.create_secret(
        +                name, value, exist_ok=exist_ok, namespace_path=namespace_path
        +            )
        +        )
         
             @override
             def alter_secret(
        @@ -1163,10 +1268,17 @@ class RemoteDBConnection(DBConnection):
         
             @override
             def create_view(
        -        self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
        +        self,
        +        name: str,
        +        query: str,
        +        *,
        +        exist_ok: bool = False,
        +        namespace_path: Optional[List[str]] = None,
             ) -> ViewDescription:
                 return LOOP.run(
        -            self._conn.create_view(name, query, namespace_path=namespace_path)
        +            self._conn.create_view(
        +                name, query, exist_ok=exist_ok, namespace_path=namespace_path
        +            )
                 )
         
             @override
        @@ -1267,16 +1379,52 @@ class RemoteDBConnection(DBConnection):
         
             @override
             def list_jobs(
        -        self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
        +        self,
        +        *,
        +        page_token: Optional[str] = None,
        +        page_limit: Optional[int] = None,
        +        table: Optional[str] = None,
        +        namespace_path: Optional[List[str]] = None,
        +        state: Optional[
        +            Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
        +        ] = None,
        +        job_type: Optional[str] = None,
        +        job_types: Optional[List[str]] = None,
        +        created_at_gte_millis: Optional[int] = None,
        +        created_at_lt_millis: Optional[int] = None,
             ) -> Listing[JobInfo]:
        -        """List server-side jobs across the database's tables.
        +        """List server-side jobs, optionally filtered before pagination.
         
        -        Returns a lazy iterator. ``page_limit`` limits each request, not the total;
        -        ``page_token`` resumes from a saved token. Requests and errors occur during
        -        iteration. See [pagination state][lancedb.listing.AsyncListing].
        +        ``table`` names a table in ``namespace_path`` (the root by default).
        +        Listings include all branches of the table. A namespace filter requires
        +        ``table``.
        +        ``state`` uses registry states such as ``in_progress``, ``succeeded``,
        +        ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
        +        ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
        +        Creation-time bounds are Unix milliseconds, inclusive at
        +        ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
        +
        +        Returns a lazy iterator. ``page_limit`` limits each request, not the total.
        +        Resume a ``page_token`` with the same filters. Requests and errors occur
        +        during iteration. See [pagination state][lancedb.listing.AsyncListing].
        +
        +        For example, to inspect up to five jobs without fetching all history::
        +
        +            jobs = db.list_jobs(table="events", page_limit=5)
        +            first_five = jobs[:5]
                 """
                 return Listing(
        -            self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
        +            self._conn.list_jobs(
        +                page_token=page_token,
        +                page_limit=page_limit,
        +                table=table,
        +                namespace_path=namespace_path,
        +                state=state,
        +                job_type=job_type,
        +                job_types=job_types,
        +                created_at_gte_millis=created_at_gte_millis,
        +                created_at_lt_millis=created_at_lt_millis,
        +            )
                 )
         
             @override
        @@ -1312,6 +1460,9 @@ class RemoteDBConnection(DBConnection):
                 *,
                 default_namespace_path: Optional[List[str]] = None,
                 parameters: Optional[QueryParameters] = None,
        +        timeout: Optional[timedelta] = None,
        +        read_timeout: Optional[timedelta] = None,
        +        cancel_on_drop: bool = False,
             ) -> SqlQuery:
                 """Start executing SQL through this LanceDB Enterprise connection.
         
        @@ -1327,6 +1478,9 @@ class RemoteDBConnection(DBConnection):
                             query,
                             default_namespace_path=default_namespace_path,
                             parameters=parameters,
        +                    timeout=timeout,
        +                    read_timeout=read_timeout,
        +                    cancel_on_drop=cancel_on_drop,
                         )
                     )
                 )
        diff --git a/python/python/lancedb/remote/errors.py b/python/python/lancedb/remote/errors.py
        index 56b5cc34d..ee92ddf53 100644
        --- a/python/python/lancedb/remote/errors.py
        +++ b/python/python/lancedb/remote/errors.py
        @@ -149,6 +149,8 @@ def _http_error_class(
                     return input_class
             if error_code == "already_exists":
                 return AlreadyExistsError
        +    if status_code == 409:
        +        return ConflictError
             if error_code != "not_found" or resource_kind is None:
                 return None
             return {
        @@ -268,6 +270,80 @@ class AlreadyExistsError(HttpError):
             """A remote resource already exists."""
         
         
        +class ConflictError(HttpError):
        +    """A remote operation conflicts with the current state of a resource.
        +
        +    For example, deleting a branch whose files are still needed by another
        +    branch raises this error. The server's reason is included in the message.
        +
        +    Examples
        +    --------
        +    >>> error = HttpError("main depends on the branch's files", "req-1", 409)
        +    >>> isinstance(error, ConflictError)
        +    True
        +    >>> error.status_code
        +    409
        +    """
        +
        +
        +class ResponseInterruptedError(HttpError):
        +    """A streamed query response stopped before the server finished sending it.
        +
        +    The batches already returned are valid, but the result is incomplete. The
        +    query is not retried automatically, because a new attempt would return those
        +    rows a second time. To read the same data in a new attempt, check out
        +    ``table_version`` first.
        +
        +    Attributes
        +    ----------
        +    batches: int
        +        The number of batches returned before the interruption.
        +    rows: int
        +        The number of rows in those batches.
        +    table_version: int or None
        +        The table version the response reflected, if the server reported it.
        +
        +    Examples
        +    --------
        +    >>> error = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7)
        +    >>> isinstance(error, HttpError)
        +    True
        +    >>> (error.rows, error.table_version)
        +    (2048, 7)
        +    """
        +
        +    # HttpError.__new__ takes HttpError's arguments, to choose a subclass.
        +    def __new__(cls, *args, **kwargs):
        +        return RuntimeError.__new__(cls)
        +
        +    def __init__(
        +        self,
        +        message: str,
        +        request_id: str,
        +        batches: int,
        +        rows: int,
        +        table_version: Optional[int] = None,
        +        is_transport_error: bool = False,
        +    ):
        +        super().__init__(message, request_id, is_transport_error=is_transport_error)
        +        self.batches = batches
        +        self.rows = rows
        +        self.table_version = table_version
        +
        +    def __reduce__(self) -> tuple[type, tuple]:
        +        return (
        +            self.__class__,
        +            (
        +                str(self),
        +                self.request_id,
        +                self.batches,
        +                self.rows,
        +                self.table_version,
        +                self.is_transport_error,
        +            ),
        +        )
        +
        +
         class TableNotFoundError(HttpError, ValueError, _NamespaceTableNotFoundError):
             """A remote table was not found.
         
        diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py
        index db74c5375..eee954345 100644
        --- a/python/python/lancedb/remote/table.py
        +++ b/python/python/lancedb/remote/table.py
        @@ -24,6 +24,7 @@ from typing import (
         import warnings
         
         from lancedb import __version__
        +from lancedb.sql import QueryParameters
         from lancedb._blob import BlobFile
         
         from lancedb._lancedb import (
        @@ -34,6 +35,7 @@ from lancedb._lancedb import (
             DeleteResult,
             DropColumnsResult,
             FtsToken,
        +    FunctionColumnStatus,
             IndexConfig,
             RTEWriteSpec,
             MergeResult,
        @@ -47,8 +49,15 @@ from lancedb.index import (
             Bitmap,
             LabelList,
         )
        +from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
        +from lancedb.cleanup import CleanupPlan, CleanupResult
         from lancedb.job import Job
        -from lancedb.functions import FunctionApplication, RefreshColumnResult
        +from lancedb.functions import (
        +    FunctionProvenance,
        +    FunctionApplication,
        +    FunctionRetryPolicy,
        +    RefreshColumnResult,
        +)
         from lancedb.remote.db import LOOP
         from lancedb.table import IndexConfigType, _maybe_add_fts_error_note
         import pyarrow as pa
        @@ -60,6 +69,7 @@ from lancedb.embeddings import EmbeddingFunctionRegistry
         from lancedb.table import _normalize_progress
         
         from ..query import (
        +    FullTextOperator,
             AnalyzePlanDistributedMetrics,
             DocumentGranularity,
             FullTextQuery,
        @@ -71,9 +81,11 @@ from ..table import (
             BlobMode,
             Branches,
             CompactionOptions,
        +    CompactionResult,
             IndexStatistics,
             Query,
             Table,
        +    TableDelta,
             Tags,
         )
         from ..types import BaseTokenizerType, ScalarIndexType
        @@ -276,6 +288,19 @@ class RemoteTable(Table):
                 """List all versions of the table"""
                 return LOOP.run(self._table.list_versions())
         
        +    def delta(
        +        self,
        +        from_version: int | str,
        +        to_version: Optional[int | str] = None,
        +    ) -> TableDelta:
        +        """Compare two versions or tags.
        +
        +        Streamed version deltas are not supported by LanceDB Enterprise tables;
        +        this raises ``NotImplementedError``.
        +        """
        +        async_delta = LOOP.run(self._table.delta(from_version, to_version))
        +        return TableDelta(async_delta._inner)
        +
             def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table:
                 """to_arrow() is not supported in LanceDB Enterprise."""
                 validate_blob_mode(blob_mode)
        @@ -307,6 +332,16 @@ class RemoteTable(Table):
                 )
         
             def checkout(self, version: Union[int, str]):
        +        """Check out a version number or tag as a read-only view in place.
        +
        +        A tag must belong to this handle's current branch. To read a tag on
        +        another branch, first obtain that branch's handle with
        +        `table.branches.checkout("branch_name")`, then call `checkout(tag)` on
        +        that handle. A tag on another branch raises an error without changing
        +        the current selection.
        +
        +        Call `checkout_latest()` to return to the latest version of this branch.
        +        """
                 result = LOOP.run(self._table.checkout(version))
                 self._checkout_version = self.version
                 return result
        @@ -364,6 +399,7 @@ class RemoteTable(Table):
                 index_type: ScalarIndexType = "BTREE",
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
             ):
                 """Create a scalar index on a column.
         
        @@ -390,6 +426,7 @@ class RemoteTable(Table):
                     self._table.create_index(
                         column,
                         replace=replace,
        +                exist_ok=exist_ok,
                         config=config,
                         wait_timeout=wait_timeout,
                         name=name,
        @@ -428,6 +465,7 @@ class RemoteTable(Table):
                 document_granularity: DocumentGranularity = DocumentGranularity.ROW,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
             ):
                 """Create a full-text search index on a column.
         
        @@ -487,6 +525,7 @@ class RemoteTable(Table):
                         self._table.create_index(
                             field_names,
                             replace=replace,
        +                    exist_ok=exist_ok,
                             config=config,
                             name=name,
                             wait_timeout=wait_timeout,
        @@ -511,6 +550,7 @@ class RemoteTable(Table):
                 replace: bool = ...,
                 wait_timeout: Optional[timedelta] = ...,
                 name: Optional[str] = ...,
        +        exist_ok: bool = ...,
                 train: bool = ...,
             ) -> None: ...
         
        @@ -536,6 +576,7 @@ class RemoteTable(Table):
                 *,
                 wait_timeout: Optional[timedelta] = ...,
                 name: Optional[str] = ...,
        +        exist_ok: bool = ...,
                 train: bool = ...,
                 target_partition_size: Optional[int] = ...,
             ) -> None: ...
        @@ -567,6 +608,7 @@ class RemoteTable(Table):
                 config: Optional[IndexConfigType] = None,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
                 train: bool = True,
                 target_partition_size: Optional[int] = None,
             ):
        @@ -587,7 +629,7 @@ class RemoteTable(Table):
                 config : IndexConfigType, optional
                     The index configuration object. If provided, uses the new unified API.
                     Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
        -            BTree, Bitmap, LabelList, Fm, FTS.
        +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
                 replace : bool, default True
                     Whether to replace an existing index on this column.
                 wait_timeout : timedelta, optional
        @@ -670,6 +712,7 @@ class RemoteTable(Table):
                     self._table.create_index(
                         column,
                         replace=replace,
        +                exist_ok=exist_ok,
                         config=config,
                         wait_timeout=wait_timeout,
                         name=name,
        @@ -685,6 +728,7 @@ class RemoteTable(Table):
                 replace: Optional[bool] = None,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
                 train: bool = True,
             ) -> Job:
                 """Create an index, returning a handle to the indexing job.
        @@ -697,6 +741,7 @@ class RemoteTable(Table):
                         self._table.create_index_async(
                             column,
                             replace=replace,
        +                    exist_ok=exist_ok,
                             config=config,
                             wait_timeout=wait_timeout,
                             name=name,
        @@ -714,6 +759,7 @@ class RemoteTable(Table):
                 progress: Optional[Union[bool, Callable, Any]] = None,
                 write_parallelism: Optional[int] = None,
                 allow_external_blob_outside_bases: bool = False,
        +        retries: Optional[int] = None,
             ) -> AddResult:
                 """Add more data to the [Table][lancedb.table.Table].
         
        @@ -748,6 +794,9 @@ class RemoteTable(Table):
                     using too much memory.
                 allow_external_blob_outside_bases: bool, default False
                     Not supported in LanceDB Enterprise. Setting this raises.
        +        retries: int, optional
        +            Override the retry budget for this call (0 to 255). Zero disables
        +            retries, including multipart parts. Ambiguous commits are never replayed.
         
                 Returns
                 -------
        @@ -765,6 +814,7 @@ class RemoteTable(Table):
                             progress=progress,
                             write_parallelism=write_parallelism,
                             allow_external_blob_outside_bases=allow_external_blob_outside_bases,
        +                    retries=retries,
                         )
                     )
                 finally:
        @@ -779,6 +829,8 @@ class RemoteTable(Table):
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
                 fast_search: Optional[bool] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> LanceQueryBuilder:
                 """Create a search query to find the nearest neighbors
                 of the given query vector. We currently support
        @@ -837,6 +889,10 @@ class RemoteTable(Table):
         
                     - *default None*, which leaves fast search disabled.
         
        +        operator: "AND" or "OR", optional
        +            Combine terms in a string full-text query; the default is OR.
        +            Use ``query_type="fts"`` when the table also has embeddings.
        +
                 Returns
                 -------
                 LanceQueryBuilder
        @@ -873,6 +929,7 @@ class RemoteTable(Table):
                     ordering_field_name=ordering_field_name,
                     fts_columns=fts_columns or [],
                     fast_search=fast_search,
        +            operator=operator,
                 )
         
             def _execute_query(
        @@ -895,6 +952,14 @@ class RemoteTable(Table):
         
                 return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
         
        +    def _execute_arrow(
        +        self,
        +        query: Query,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        return LOOP.run(self._table._execute_arrow(query, timeout=timeout))
        +
             def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
                 return LOOP.run(self._table._explain_plan(query, verbose))
         
        @@ -925,9 +990,10 @@ class RemoteTable(Table):
                 new_data: DATA,
                 on_bad_vectors: str,
                 fill_value: float,
        +        retries: Optional[int] = None,
             ) -> MergeResult:
                 return LOOP.run(
        -            self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
        +            self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
                 )
         
             @_deprecated_keyword("predicate", "where")
        @@ -1060,7 +1126,8 @@ class RemoteTable(Table):
                 cleanup_old_versions() is a no-op in LanceDB Enterprise.
                 """
                 warnings.warn(
        -            "cleanup_old_versions() is a no-op in LanceDB Enterprise.",
        +            "cleanup_old_versions() is a no-op in LanceDB Enterprise. "
        +            "Use cleanup_async() to submit durable cleanup explicitly.",
                     stacklevel=2,
                 )
                 pass
        @@ -1075,6 +1142,26 @@ class RemoteTable(Table):
                 )
                 pass
         
        +    def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
        +        """Preview cleanup without submitting a job or deleting files."""
        +        return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds))
        +
        +    def cleanup_async(
        +        self, *, min_age_seconds: Optional[int] = None
        +    ) -> Job[CleanupResult]:
        +        """Submit cleanup. See
        +
        +        [Table.cleanup_async][lancedb.table.Table.cleanup_async].
        +        """
        +        return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds)))
        +
        +    def compact_async(
        +        self, *, compaction_options: Optional[CompactionOptions] = None
        +    ) -> Job[CompactionResult]:
        +        return Job(
        +            LOOP.run(self._table.compact_async(compaction_options=compaction_options))
        +        )
        +
             def optimize(
                 self,
                 *,
        @@ -1087,10 +1174,13 @@ class RemoteTable(Table):
                 Enterprise job. Pruning old versions and index optimization are not
                 yet supported remotely, so this call skips them and returns
                 successfully with zeroed pruning statistics once the compaction job
        -        has been submitted; it does not wait for that job to finish. Passing
        -        a non-default ``compaction_options`` raises ``NotImplementedError``
        -        before anything is submitted, since there is no way yet to forward
        -        those settings to the server.
        +        has been submitted; it does not wait for that job to finish. The
        +        per-job options ``target_rows_per_fragment``, ``max_source_rows``,
        +        ``io_buffer_size``, and ``batch_size`` are supported on compatible
        +        servers. Omitted fields inherit table tuning, then deployment/built-in
        +        defaults. Other non-default settings raise ``NotImplementedError``
        +        before submission. Errors from older servers are propagated without
        +        retrying with the settings removed.
                 """
                 return LOOP.run(
                     self._table.optimize(
        @@ -1120,6 +1210,9 @@ class RemoteTable(Table):
                 computed: Dict[str, str] | None = None,
                 auto_refresh_enabled: bool | None = None,
                 auto_refresh_interval_seconds: int | None = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
             ) -> AddColumnsResult:
                 return LOOP.run(
                     self._table.add_columns(
        @@ -1127,6 +1220,9 @@ class RemoteTable(Table):
                         computed=computed,
                         auto_refresh_enabled=auto_refresh_enabled,
                         auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                total_gpu_count=total_gpu_count,
                     )
                 )
         
        @@ -1134,16 +1230,60 @@ class RemoteTable(Table):
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[Dict[str, int]] = None,
        +        planning_workers: Optional[Dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
        -        gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        error_policy: Optional[Literal["fail", "skip"]] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ):
                 return LOOP.run(
                     self._table.refresh_column(
                         column,
        +                where=where,
                         batch_size=batch_size,
        +                max_concurrency=max_concurrency,
        +                publication_interval_rows=publication_interval_rows,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                supervisor_resources=supervisor_resources,
        +                planning_workers=planning_workers,
                         gpu_class=gpu_class,
        -                gpu_count=gpu_count,
        +                total_gpu_count=total_gpu_count,
        +                retry_policy=retry_policy,
        +                error_policy=error_policy,
        +                max_failed_fraction=max_failed_fraction,
        +                max_failed_rows=max_failed_rows,
        +                row_timeout_seconds=row_timeout_seconds,
        +                init_timeout_seconds=init_timeout_seconds,
        +                num_workers=num_workers,
        +                max_job_attempts=max_job_attempts,
        +                max_executor_processes_per_worker=max_executor_processes_per_worker,
        +                retry_errors=retry_errors,
        +                retry_job_id=retry_job_id,
        +                retry_error_type=retry_error_type,
        +                include_quarantined=include_quarantined,
        +                function_version=function_version,
        +                recompute=recompute,
                     )
                 )
         
        @@ -1151,31 +1291,129 @@ class RemoteTable(Table):
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[Dict[str, int]] = None,
        +        planning_workers: Optional[Dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
        -        gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        error_policy: Optional[Literal["fail", "skip"]] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> Job[RefreshColumnResult]:
                 return Job(
                     LOOP.run(
                         self._table.refresh_column_async(
                             column,
        +                    where=where,
                             batch_size=batch_size,
        +                    max_concurrency=max_concurrency,
        +                    publication_interval_rows=publication_interval_rows,
        +                    total_cpu_millis=total_cpu_millis,
        +                    total_memory_bytes=total_memory_bytes,
        +                    supervisor_resources=supervisor_resources,
        +                    planning_workers=planning_workers,
                             gpu_class=gpu_class,
        -                    gpu_count=gpu_count,
        +                    total_gpu_count=total_gpu_count,
        +                    retry_policy=retry_policy,
        +                    error_policy=error_policy,
        +                    max_failed_fraction=max_failed_fraction,
        +                    max_failed_rows=max_failed_rows,
        +                    row_timeout_seconds=row_timeout_seconds,
        +                    init_timeout_seconds=init_timeout_seconds,
        +                    num_workers=num_workers,
        +                    max_job_attempts=max_job_attempts,
        +                    max_executor_processes_per_worker=max_executor_processes_per_worker,
        +                    retry_errors=retry_errors,
        +                    retry_job_id=retry_job_id,
        +                    retry_error_type=retry_error_type,
        +                    include_quarantined=include_quarantined,
        +                    function_version=function_version,
        +                    recompute=recompute,
                         )
                     )
                 )
         
        +    def resume_refresh(self, job_id: str) -> Job[RefreshColumnResult]:
        +        return Job(LOOP.run(self._table.resume_refresh(job_id)))
        +
             def function_errors(
                 self,
                 job_id: Optional[str] = None,
                 column: Optional[str] = None,
                 limit: Optional[int] = None,
        +        history: bool = False,
        +        page_token: Optional[str] = None,
             ):
                 return LOOP.run(
        -            self._table.function_errors(job_id=job_id, column=column, limit=limit)
        +            self._table.function_errors(
        +                job_id=job_id,
        +                column=column,
        +                limit=limit,
        +                history=history,
        +                page_token=page_token,
        +            )
        +        ).as_sync(self)
        +
        +    def quarantine_failed(
        +        self,
        +        column: str,
        +        *,
        +        error_type: Optional[str] = None,
        +        job_id: Optional[str] = None,
        +        after_attempts: Optional[int] = None,
        +        quarantined: bool = True,
        +    ) -> int:
        +        return LOOP.run(
        +            self._table.quarantine_failed(
        +                column,
        +                error_type=error_type,
        +                job_id=job_id,
        +                after_attempts=after_attempts,
        +                quarantined=quarantined,
        +            )
                 )
         
        +    def function_provenance(
        +        self,
        +        column: str,
        +        *,
        +        limit: Optional[int] = None,
        +        version: Optional[int] = None,
        +    ) -> FunctionProvenance:
        +        return LOOP.run(
        +            self._table.function_provenance(column, limit=limit, version=version)
        +        )
        +
        +    def column_statuses(
        +        self, column: Optional[str] = None
        +    ) -> list[FunctionColumnStatus]:
        +        return LOOP.run(self._table.column_statuses(column=column))
        +
        +    def column_status(self, column: str) -> FunctionColumnStatus:
        +        return LOOP.run(self._table.column_status(column))
        +
        +    def wait_fresh(
        +        self, column: str, timeout: Optional[timedelta] = None
        +    ) -> FunctionColumnStatus:
        +        return LOOP.run(self._table.wait_fresh(column, timeout))
        +
             def alter_columns(
                 self, *alterations: Iterable[Dict[str, str]]
             ) -> AlterColumnsResult:
        @@ -1210,7 +1448,11 @@ class RemoteTable(Table):
                 return LOOP.run(self._table.get_table_overrides())
         
             def update_table_overrides(self, **overrides: Any) -> dict[str, Any]:
        -        """Merge Enterprise table overrides into the current table overrides."""
        +        """Merge Enterprise table overrides using a non-atomic read-modify-write.
        +
        +        See [the async method][lancedb.AsyncTable.update_table_overrides]
        +        for merge behavior and concurrency limitations.
        +        """
                 return LOOP.run(self._table.update_table_overrides(**overrides))
         
             def reset_table_overrides(self) -> dict[str, Any]:
        @@ -1272,7 +1514,14 @@ class RemoteTable(Table):
                 """
                 return LOOP.run(self._table.prewarm_index(name))
         
        -    def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
        +    def prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> None:
                 """Prewarm data for the table.
         
                 This is a hint to the database that the given columns will be accessed
        @@ -1280,7 +1529,8 @@ class RemoteTable(Table):
                 Currently only supported in LanceDB Enterprise.
         
                 This call initiates prewarming and returns once the request is accepted.
        -        It is idempotent and safe to call from multiple clients concurrently.
        +        Uses SQL PREWARM and requires Flight SQL connectivity. To track the
        +        durable warming job, use ``prewarm_data_async()``.
         
                 This operation has a large upfront cost but can speed up future queries
                 that need to fetch the given columns.  Large columns such as embeddings
        @@ -1291,8 +1541,62 @@ class RemoteTable(Table):
                 ----------
                 columns: list of str, optional
                     The columns to prewarm. If None, all columns are prewarmed.
        +        filter: str, optional
        +            A single SQL predicate for conservative metadata pruning.
        +        parameters: sequence, mapping, or one-row Arrow batch/table, optional
        +            Scalar values for ``$1``/``$name`` placeholders in ``filter``.
        +            Values are sent separately from SQL; requires server support.
        +        concurrency: int, optional
        +            Positive per-executor warming concurrency; omitted uses the server default.
        +
        +        Examples
        +        --------
        +        >>> table.prewarm_data(  # doctest: +SKIP
        +        ...     ["payload"], filter="quality > 0.7", concurrency=4)
                 """
        -        return LOOP.run(self._table.prewarm_data(columns))
        +        return LOOP.run(
        +            self._table.prewarm_data(
        +                columns, filter=filter, concurrency=concurrency, parameters=parameters
        +            )
        +        )
        +
        +    def explain_prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> PrewarmDataPlan:
        +        """Preview prewarm without submitting a warming job.
        +
        +        See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data]
        +        for options, permissions, snapshot semantics, and limitations.
        +        """
        +        return LOOP.run(
        +            self._table.explain_prewarm_data(
        +                columns, filter=filter, concurrency=concurrency, parameters=parameters
        +            )
        +        )
        +
        +    def prewarm_data_async(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> Job[PrewarmDataResult]:
        +        return Job(
        +            LOOP.run(
        +                self._table.prewarm_data_async(
        +                    columns,
        +                    filter=filter,
        +                    concurrency=concurrency,
        +                    parameters=parameters,
        +                )
        +            )
        +        )
         
             def wait_for_index(
                 self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
        @@ -1311,9 +1615,15 @@ class RemoteTable(Table):
                 return LOOP.run(self._table.uri())
         
             def take_offsets(
        -        self, offsets: list[int], *, with_row_id: bool = False
        +        self,
        +        offsets: list[int],
        +        *,
        +        with_row_id: bool = False,
        +        preserve_order: bool = False,
             ) -> LanceTakeQueryBuilder:
        -        builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
        +        builder = LanceTakeQueryBuilder(
        +            self._table.take_offsets(offsets, preserve_order=preserve_order)
        +        )
                 if with_row_id:
                     builder.with_row_id()
                 return builder
        @@ -1349,13 +1659,20 @@ class RemoteTable(Table):
                 self,
                 column: str,
                 row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
        +        *,
        +        buffer_size: Optional[int] = None,
             ) -> "list[Optional[BlobFile]]":
        -        return LOOP.run(self._table.fetch_blob_files(column, row_ids))
        +        return LOOP.run(
        +            self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
        +        )
         
             def open_blob_file(
        -        self, descriptor: Union[dict, pa.StructScalar, None]
        +        self,
        +        descriptor: Union[dict, pa.StructScalar, None],
        +        *,
        +        buffer_size: Optional[int] = None,
             ) -> Optional[BlobFile]:
        -        return LOOP.run(self._table.open_blob_file(descriptor))
        +        return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size))
         
             def head(self, n=5) -> pa.Table:
                 """
        diff --git a/python/python/lancedb/resources.py b/python/python/lancedb/resources.py
        new file mode 100644
        index 000000000..f37d48612
        --- /dev/null
        +++ b/python/python/lancedb/resources.py
        @@ -0,0 +1,48 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import re
        +from typing import Any, Optional, Union
        +
        +
        +def _validate_gpu_class_name(value: Any) -> str:
        +    if not isinstance(value, str) or not re.fullmatch(
        +        r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", value
        +    ):
        +        raise ValueError(
        +            "gpu_class must be a lowercase name of at most 63 letters, digits, or "
        +            "hyphens, and cannot start or end with a hyphen"
        +        )
        +    return value
        +
        +
        +def _resource_options(
        +    cpu: Optional[int],
        +    memory: Optional[int],
        +    gpu: Optional[int],
        +    *,
        +    gpu_class: Optional[str] = None,
        +    gpu_count: Optional[int] = None,
        +) -> dict[str, Union[int, str]]:
        +    result: dict[str, Union[int, str]] = {}
        +    for name, value, maximum, minimum in (
        +        ("total_cpu_millis", cpu, 2**64 - 1, 1),
        +        ("total_memory_bytes", memory, 2**64 - 1, 1),
        +        ("total_gpu_count", gpu, 2**32 - 1, 0),
        +        ("gpu_count", gpu_count, 2**32 - 1, 1),
        +    ):
        +        if value is None:
        +            continue
        +        if isinstance(value, bool) or not isinstance(value, int):
        +            raise ValueError(f"{name} must be an integer")
        +        if not minimum <= value <= maximum:
        +            raise ValueError(f"{name} must be between {minimum} and {maximum}")
        +        result[name] = value
        +    if gpu_class is not None:
        +        result["gpu_class"] = _validate_gpu_class_name(gpu_class)
        +    if gpu is not None and (
        +        (gpu_count is not None and gpu_count > gpu)
        +        or (gpu_class is not None and gpu == 0)
        +    ):
        +        raise ValueError("total_gpu_count cannot fit one Function worker")
        +    return result
        diff --git a/python/python/lancedb/schema.py b/python/python/lancedb/schema.py
        index d92f7f692..40be49114 100644
        --- a/python/python/lancedb/schema.py
        +++ b/python/python/lancedb/schema.py
        @@ -6,6 +6,7 @@
         
         import ctypes
         import importlib
        +from dataclasses import dataclass
         from typing import TYPE_CHECKING, Iterable, Optional
         
         import pyarrow as pa
        @@ -27,6 +28,78 @@ _BLOB_V2_STORAGE_TYPE = pa.struct(
             ]
         )
         _resolved_blob_type = None
        +_UINT32_MAX = 0xFFFF_FFFF
        +_UINT64_MAX = 0xFFFF_FFFF_FFFF_FFFF
        +
        +
        +@dataclass(frozen=True)
        +class BasePath:
        +    """A storage base registered on a table at creation time.
        +
        +    Use with the ``initial_bases`` argument of
        +    [create_table][lancedb.db.DBConnection.create_table] to make
        +    external blob URIs resolve under a shared prefix: descriptors that fall
        +    under ``path`` are stored relative to it instead of as absolute URIs.
        +
        +    This is a lightweight stand-in for ``lance.DatasetBasePath`` that does
        +    not require pylance. Both classes, and equivalent dictionaries, are
        +    accepted by the create APIs.
        +
        +    Parameters
        +    ----------
        +    path:
        +        Full URI of the base (for example ``s3://bucket/prefix`` or a
        +        ``file://`` URI). A blob URI under this prefix is stored relative to
        +        it.
        +    name:
        +        Optional human-readable name for the base.
        +    is_dataset_root:
        +        Whether the base uses the dataset-root layout. Defaults to ``False``.
        +        Bases registered here must leave this ``False``: Lance only resolves
        +        external blob URIs against non-root bases.
        +    id:
        +        Base ID used by scoped storage options such as ``base_.region``.
        +        ``None`` lets Lance assign a non-zero ID. ``0`` is reserved for
        +        absolute (unregistered) URIs and is rejected.
        +
        +        When supplying IDs for multiple bases, use distinct explicit non-zero
        +        IDs. The pinned Lance release can collide when one base uses automatic
        +        allocation and another supplies an explicit ID; the create fails, the
        +        table name can remain listed but unopenable, and retrying with distinct
        +        explicit IDs succeeds. Automatic allocation for every base is
        +        supported.
        +    """
        +
        +    path: str
        +    name: Optional[str] = None
        +    is_dataset_root: bool = False
        +    id: Optional[int] = None
        +
        +    def __post_init__(self) -> None:
        +        if not isinstance(self.path, str):
        +            raise TypeError(f"path must be a string, got {type(self.path).__name__}")
        +        if not self.path:
        +            raise ValueError("path must not be empty")
        +        if self.name is not None and not isinstance(self.name, str):
        +            raise TypeError(f"name must be a string, got {type(self.name).__name__}")
        +        if not isinstance(self.is_dataset_root, bool):
        +            raise TypeError(
        +                "is_dataset_root must be a bool, got "
        +                f"{type(self.is_dataset_root).__name__}"
        +            )
        +        if self.id is None:
        +            return
        +        if isinstance(self.id, bool) or not isinstance(self.id, int):
        +            raise TypeError(f"id must be an int or None, got {type(self.id).__name__}")
        +        if self.id == 0:
        +            raise ValueError(
        +                "id=0 is reserved for unregistered blob URIs; "
        +                "pass id=None to let Lance assign an ID"
        +            )
        +        if self.id < 0:
        +            raise ValueError("id must be a positive integer")
        +        if self.id > _UINT32_MAX:
        +            raise ValueError("id must fit in a 32-bit unsigned integer")
         
         
         class _FallbackBlobType(pa.ExtensionType):
        @@ -122,6 +195,15 @@ def blob_v2_column_paths(schema: pa.Schema) -> list[str]:
             return [path for path, _ in _collect_blob_paths(schema, is_blob_v2_field)]
         
         
        +def row_addressable_blob_paths(schema: pa.Schema) -> list[str]:
        +    """Blob v1 and v2 paths with one blob addressable by table row id."""
        +    return [
        +        path
        +        for path, has_list_ancestor in _collect_blob_paths(schema, is_blob_like_field)
        +        if not has_list_ancestor
        +    ]
        +
        +
         def row_addressable_blob_v2_paths(schema: pa.Schema) -> list[str]:
             """Blob v2 paths with one blob addressable by table row id.
         
        @@ -335,6 +417,132 @@ def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray:
             return pa.ExtensionArray.from_storage(blob_type, storage)
         
         
        +def _blob_uint64(value: object, what: str) -> int:
        +    if isinstance(value, bool) or not isinstance(value, int):
        +        raise TypeError(f"{what} must be an int, got {type(value).__name__}")
        +    if value < 0:
        +        raise ValueError(f"{what} must be non-negative")
        +    if value > _UINT64_MAX:
        +        raise OverflowError(f"{what} must fit in a uint64")
        +    return value
        +
        +
        +def blob_uri_array(
        +    uris: Iterable[Optional[str]],
        +    *,
        +    positions: Optional[Iterable[Optional[int]]] = None,
        +    sizes: Optional[Iterable[Optional[int]]] = None,
        +) -> pa.ExtensionArray:
        +    """Build a Lance blob v2 extension array from external URIs.
        +
        +    Produces the standard four-field blob v2 storage (``data=None``, ``uri``,
        +    nullable ``position`` and ``size``) without requiring pylance, so the
        +    result can be used directly in Arrow record batches and combined with
        +    field metadata such as ``lancedb:logical_type="mp4"``.
        +
        +    A row without ``position`` and ``size`` references the whole object; a
        +    row with both reads exactly that byte range. Register the object prefix
        +    with [BasePath][lancedb.schema.BasePath] at table creation to store a
        +    matched URI relative to a base, or enable
        +    ``allow_external_blob_outside_bases`` on the write that inserts the row to
        +    keep the absolute URI when no base matches. The opt-in covers that one
        +    write; a later ``add()`` must enable it again.
        +
        +    Parameters
        +    ----------
        +    uris:
        +        An iterable of absolute URI strings or ``None`` for a null blob. A
        +        URI under a registered base is matched and stored in the descriptor
        +        relative to that base. An unmatched URI requires the write that
        +        inserts the row to opt in with
        +        ``allow_external_blob_outside_bases``, and must always be a valid
        +        absolute URI.
        +    positions:
        +        Optional byte offsets, one per URI. Provide together with ``sizes``;
        +        each entry is an ``int`` or ``None``. A range requires both fields.
        +    sizes:
        +        Optional range lengths in bytes, one per URI. Must be positive when
        +        ``position`` is set.
        +
        +    Returns
        +    -------
        +    pa.ExtensionArray
        +        external blob values ready to use in Arrow tables or record batches.
        +
        +    Raises
        +    ------
        +    TypeError
        +        If a URI, position, or size has the wrong type.
        +    ValueError
        +        If lengths differ, only one of ``positions``/``sizes`` is given, a
        +        range is incomplete, a size is not positive, or a range is given for
        +        a null URI.
        +    OverflowError
        +        If a position or size does not fit in a uint64.
        +
        +    Examples
        +    --------
        +    >>> import pyarrow as pa
        +    >>> from lancedb.schema import blob, blob_uri_array
        +    >>> schema = pa.schema([blob("video")])
        +    >>> videos = blob_uri_array(
        +    ...     ["s3://bucket/a.mp4", "hf://datasets/org/repo@abc/b.mp4"],
        +    ...     positions=[0, 8],
        +    ...     sizes=[4, 4],
        +    ... )
        +    >>> batch = pa.RecordBatch.from_arrays([videos], schema=schema)
        +    >>> batch.num_rows
        +    2
        +    """
        +    uri_list = list(uris)
        +    if positions is None and sizes is None:
        +        ranges = [(None, None)] * len(uri_list)
        +    elif positions is None or sizes is None:
        +        raise ValueError("positions and sizes must be provided together")
        +    else:
        +        position_list = list(positions)
        +        size_list = list(sizes)
        +        if len(position_list) != len(uri_list):
        +            raise ValueError(
        +                "positions must have the same length as uris, got "
        +                f"{len(position_list)} and {len(uri_list)}"
        +            )
        +        if len(size_list) != len(uri_list):
        +            raise ValueError(
        +                "sizes must have the same length as uris, got "
        +                f"{len(size_list)} and {len(uri_list)}"
        +            )
        +        ranges = list(zip(position_list, size_list, strict=True))
        +
        +    descriptors = []
        +    for index, (uri, (position, size)) in enumerate(zip(uri_list, ranges, strict=True)):
        +        if uri is None:
        +            if position is not None or size is not None:
        +                raise ValueError(
        +                    f"uris[{index}] is None but a position or size was provided"
        +                )
        +            descriptors.append(None)
        +            continue
        +        if not isinstance(uri, str):
        +            raise TypeError(f"uris[{index}] must be a string, got {type(uri).__name__}")
        +        if position is None and size is None:
        +            descriptors.append({"uri": uri})
        +            continue
        +        if position is None or size is None:
        +            raise ValueError(
        +                f"uris[{index}] must set both position and size or neither"
        +            )
        +        position = _blob_uint64(position, f"positions[{index}]")
        +        size = _blob_uint64(size, f"sizes[{index}]")
        +        if size == 0:
        +            raise ValueError(f"sizes[{index}] must be positive to read a byte range")
        +        descriptors.append({"uri": uri, "position": position, "size": size})
        +
        +    blob_type = _resolve_blob_type()()
        +    storage = pa.array(descriptors, type=blob_type.storage_type)
        +    return pa.ExtensionArray.from_storage(blob_type, storage)
        +
        +
         def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType:
             """A help function to create a vector type.
         
        diff --git a/python/python/lancedb/secrets.py b/python/python/lancedb/secrets.py
        index 75ac9e340..ebafadbc5 100644
        --- a/python/python/lancedb/secrets.py
        +++ b/python/python/lancedb/secrets.py
        @@ -72,7 +72,7 @@ class EnvVarSecret:
         
             Pass these in the ``secrets`` sequence of
             [DBConnection.create_function][lancedb.db.DBConnection.create_function]. The
        -    Function's source is unchanged by binding: it reads ``OPENAI_API_KEY`` the
        +    Function's source is unchanged by binding: it reads ``MODEL_API_KEY`` the
             way it always did, and the binding is what puts a value there.
         
             This is a local value. Constructing it contacts no server, so it always
        @@ -101,10 +101,10 @@ class EnvVarSecret:
             --------
             >>> from lancedb import EnvVarSecret
             >>> binding = EnvVarSecret(
        -    ...     secret_name="openai-prod", env_variable="OPENAI_API_KEY"
        +    ...     secret_name="model-api-key", env_variable="MODEL_API_KEY"
             ... )
             >>> binding.secret_name, binding.env_variable
        -    ('openai-prod', 'OPENAI_API_KEY')
        +    ('model-api-key', 'MODEL_API_KEY')
             """
         
             __slots__ = ("_secret_name", "_env_variable", "_secret_namespace_path")
        diff --git a/python/python/lancedb/server_info.py b/python/python/lancedb/server_info.py
        new file mode 100644
        index 000000000..d53c6c380
        --- /dev/null
        +++ b/python/python/lancedb/server_info.py
        @@ -0,0 +1,33 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +"""Remote server build information returned as JSON-compatible dictionaries."""
        +
        +from typing import Optional, TypedDict
        +
        +
        +class ServerBuildInfo(TypedDict):
        +    """Immutable identity compiled into a server executable."""
        +
        +    release: str
        +    git_sha: str
        +    build_date: Optional[str]
        +
        +
        +class ServerInfo(TypedDict):
        +    """The responding query node and its configured Function runtime.
        +
        +    ``query_node`` can be ``None`` when the executable has no build metadata.
        +    ``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling
        +    upgrade, separate requests can reach different query-node builds.
        +    Configured images do not establish the version of a running job.
        +    """
        +
        +    query_node: Optional[ServerBuildInfo]
        +    lance_version: str
        +    lancedb_version: str
        +    function_worker_protocol_version: int
        +    configured_query_node_image: Optional[str]
        +    configured_job_worker_image: Optional[str]
        +    configured_sql_job_image: Optional[str]
        +    configured_gpu_worker_image: Optional[str]
        diff --git a/python/python/lancedb/sql.py b/python/python/lancedb/sql.py
        index 7498cddcc..5da4d35dd 100644
        --- a/python/python/lancedb/sql.py
        +++ b/python/python/lancedb/sql.py
        @@ -104,6 +104,15 @@ class AsyncQuery:
                 """The stable identifier scoped to the connection that submitted it."""
                 return self._inner.id
         
        +    @property
        +    def job_id(self) -> Optional[str]:
        +        """The durable Job Registry id once the server reports this query as a job.
        +
        +        A running query reports it after :meth:`describe` observes the latest
        +        server status. This is separate from the connection-scoped ``id``.
        +        """
        +        return self._inner.job_id
        +
             async def describe(self) -> QueryDescription:
                 """Get a point-in-time description of the query."""
                 return await self._inner.describe()
        @@ -118,7 +127,12 @@ class AsyncQuery:
                 return AsyncRecordBatchReader(await self._inner.reader())
         
             async def cancel(self) -> None:
        -        """Request cancellation of the query."""
        +        """Request cancellation of this query's Flight execution.
        +
        +        A durable server-side job may reject this operation because its Flight
        +        waiter cannot cancel the registry job. Use ``connection.cancel_job()``
        +        with ``job_id`` to cancel that job.
        +        """
                 await self._inner.cancel()
         
         
        @@ -133,6 +147,15 @@ class Query:
                 """The stable identifier scoped to the connection that submitted it."""
                 return self._inner.id
         
        +    @property
        +    def job_id(self) -> Optional[str]:
        +        """The durable Job Registry id once the server reports this query as a job.
        +
        +        A running query reports it after :meth:`describe` observes the latest
        +        server status. This is separate from the connection-scoped ``id``.
        +        """
        +        return self._inner.job_id
        +
             def describe(self) -> QueryDescription:
                 """Get a point-in-time description of the query."""
                 return LOOP.run(self._inner.describe())
        @@ -159,7 +182,12 @@ class Query:
                 return pa.RecordBatchReader.from_batches(reader.schema, batches())
         
             def cancel(self) -> None:
        -        """Request cancellation of the query."""
        +        """Request cancellation of this query's Flight execution.
        +
        +        A durable server-side job may reject this operation because its Flight
        +        waiter cannot cancel the registry job. Use ``connection.cancel_job()``
        +        with ``job_id`` to cancel that job.
        +        """
                 LOOP.run(self._inner.cancel())
         
         
        diff --git a/python/python/lancedb/storage_integration.py b/python/python/lancedb/storage_integration.py
        index a9dda088b..e319a24be 100644
        --- a/python/python/lancedb/storage_integration.py
        +++ b/python/python/lancedb/storage_integration.py
        @@ -50,6 +50,7 @@ class StorageIntegrationInfo:
             azure_client_secret_secret: Optional[SecretReference] = None
             gcp_credentials_json_secret: Optional[SecretReference] = None
             huggingface_token_secret: Optional[SecretReference] = None
        +    azure_storage_account_access_key_secret: Optional[SecretReference] = None
         
             def __post_init__(self):
                 for field in (
        @@ -58,6 +59,7 @@ class StorageIntegrationInfo:
                     "azure_tenant_id_secret",
                     "azure_client_id_secret",
                     "azure_client_secret_secret",
        +            "azure_storage_account_access_key_secret",
                     "gcp_credentials_json_secret",
                     "huggingface_token_secret",
                 ):
        diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py
        index 810911e28..f568b7c7c 100644
        --- a/python/python/lancedb/streaming.py
        +++ b/python/python/lancedb/streaming.py
        @@ -28,11 +28,12 @@ import threading
         import time
         import warnings
         from collections import deque
        -from concurrent.futures import ThreadPoolExecutor
        +from concurrent.futures import Future, ThreadPoolExecutor
         from copy import deepcopy
        -from multiprocessing import RawArray, get_context
        +from multiprocessing import RawArray, get_all_start_methods, get_context
         from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union
         
        +import numpy as np
         import pyarrow as pa
         import pyarrow.compute as pc
         import torch
        @@ -47,6 +48,7 @@ from .permutation import (
             _table_from_pickle_state,
             _table_to_pickle_state,
         )
        +from .table import LanceTable
         
         logger = logging.getLogger(__name__)
         
        @@ -55,9 +57,318 @@ logger = logging.getLogger(__name__)
         # distinct seeds for any practically encountered epoch count.
         _EPOCH_PRIME = 100003
         
        +# Offsets added when seeding each split's 2-phase bounded shuffle
        +# permutation (distinct from _EPOCH_PRIME and from each other so they
        +# can't collide).
        +_SIGMA_PRIME = 1000003
        +_SIGMA_SPLIT_PRIME = 3000017
        +
         DEFAULT_READ_BATCH_SIZE = 64
         DEFAULT_PREFETCH_BATCHES = 4
        +# 8 blocks of the recommended block_size=512 give max_shuffle_distance 4,096,
        +# which matched 1-phase validation loss in GPT-2 pretraining; S3 throughput
        +# was flat across window sizes.
        +DEFAULT_WINDOW_BLOCKS = 8
         _UNSET = object()
        +# Checkpoint keys pinning the 2-phase read order; absent in 1-phase checkpoints.
        +# block_size comes first so a 1-phase/2-phase mix reports the mode setting.
        +_TWO_PHASE_CHECKPOINT_KEYS = (
        +    "block_size",
        +    "shuffle",
        +    "max_shuffle_distance",
        +    "reshuffle_blocks_per_epoch",
        +)
        +
        +
        +def _build_bounded_permutation(n: int, max_distance: int, seed: int) -> np.ndarray:
        +    """Build a permutation of ``[0, n)`` with ``|sigma(k) - k| < max_distance``.
        +
        +    Partitions ``[0, n)`` into consecutive chunks of ``max_distance`` entries
        +    (the last chunk may be shorter) and fully shuffles each chunk
        +    independently.  Since ``k`` and ``sigma(k)`` always fall in the same
        +    chunk, this trivially satisfies the displacement bound.  Vectorized
        +    (one random key matrix, sorted per row) so it stays cheap even sized to
        +    an entire split's live-row count.
        +    """
        +    if n == 0:
        +        return np.array([], dtype=np.int64)
        +    rng = np.random.default_rng(seed)
        +    sigma = np.arange(n, dtype=np.int64)
        +    num_full = n // max_distance
        +    full_len = num_full * max_distance
        +    if num_full:
        +        # Sorting i.i.d. random keys within each row of a
        +        # (num_full, max_distance) matrix gives, per row, a uniformly
        +        # random permutation of that row's column indices -- i.e. one
        +        # independent shuffled chunk per row, all at once.
        +        keys = rng.random((num_full, max_distance))
        +        chunk_perms = np.argsort(keys, axis=1)
        +        bases = (np.arange(num_full, dtype=np.int64) * max_distance)[:, None]
        +        sigma[:full_len] = (chunk_perms + bases).reshape(-1)
        +    if full_len < n:
        +        tail = np.arange(full_len, n, dtype=np.int64)
        +        tail_perm = np.argsort(rng.random(n - full_len))
        +        sigma[full_len:] = tail[tail_perm]
        +    return sigma
        +
        +
        +class _TwoPhaseSplitReader:
        +    """Sequential-only stand-in for ``Permutation`` driving 2-phase reads.
        +
        +    Duck-types ``Permutation.__getitems__`` so 2-phase's shuffled reads flow
        +    through the same stage-1 I/O machinery (``io_queue_depth`` prefetch,
        +    ``Future``-based fetches) used by 1-phase, instead of a separate ad hoc
        +    path.
        +
        +    This split's assigned blocks, concatenated in order and restricted to
        +    live rows, give every row a dense natural rank in ``[0, num_rows)``.  A
        +    single permutation ``sigma`` of that rank space -- built once, with
        +    ``|sigma(rank) - rank| < max_shuffle_distance`` for every rank -- decides
        +    each row's output position.  A row may move anywhere within that bound,
        +    including into a different block's range entirely; the only restriction
        +    is the distance from its own natural rank, not which block it started
        +    in.  A block is evicted, and the next block assigned to this split read
        +    in to replace it, as soon as every one of its rows has been read past
        +    in the output order -- which happens naturally once ``sigma`` has been
        +    applied, without any extra bookkeeping about "generations" or "slots".
        +
        +    Only one ``__getitems__`` call executes its own gather/evict logic at a
        +    time (serialized by ``_lock``): the block cache and read plan are
        +    shared, mutable state, and letting ``io_queue_depth`` submit multiple
        +    concurrent calls for the same split would race on them.  The actual
        +    block *fetches* do run concurrently with each other and with whichever
        +    call holds ``_lock``, though: each call, after satisfying its own rows,
        +    schedules background prefetches (on a small private executor, sized by
        +    ``prefetch_depth``) for the next few not-yet-loaded blocks the read
        +    plan is about to need, up to ``prefetch_depth`` blocks in flight or
        +    already fetched but not yet consumed at once.  By the time a later call
        +    actually needs one of those blocks, its fetch has often already
        +    completed, so the call just picks up the finished result instead of
        +    blocking on storage -- overlapping this split's own I/O with whatever
        +    is consuming its previous blocks, the same way ``io_queue_depth``
        +    overlaps I/O for 1-phase.
        +    """
        +
        +    def __init__(
        +        self,
        +        block_ids: list[Any],
        +        block_live_counts: list[int],
        +        shuffle: bool,
        +        max_shuffle_distance: int,
        +        seed: int,
        +        read_block_fn: Callable[[Any], pa.Table],
        +        columns: Optional[list[str]],
        +        skip: int = 0,
        +        prefetch_depth: int = 1,
        +    ):
        +        self._block_ids = block_ids
        +        self._read_block_fn = read_block_fn
        +        self._columns = columns
        +        self._lock = threading.Lock()
        +        self._loaded: dict[int, pa.Table] = {}
        +        self._pending: dict[int, Future] = {}
        +        self._prefetch_depth = max(1, prefetch_depth)
        +
        +        counts = np.asarray(block_live_counts, dtype=np.int64)
        +        total_rows = int(counts.sum())
        +        num_blocks = len(block_ids)
        +        if not 0 <= skip <= total_rows:
        +            raise ValueError(f"skip ({skip}) out of range for {total_rows} row(s)")
        +
        +        # Natural (block, then row) order: block_pos[k]/local_offset[k]
        +        # describe the row whose dense natural rank is exactly k.  These two
        +        # arrays are retained for the reader's whole lifetime, one entry per
        +        # row in the *entire* split (not just the resident window -- see the
        +        # whole-split-memory review thread, still open) -- so their dtype is
        +        # the full per-row memory cost, not a rounding choice.  block_pos
        +        # values are block indices (bounded by num_blocks) and local_offset
        +        # values are in-block row offsets (bounded by this split's largest
        +        # block), both far smaller than the row-rank range sigma/order below
        +        # need int64 for, so int32 halves that cost in the realistic case;
        +        # falls back to int64 only if a single split's block count or block
        +        # size itself exceeds what int32 can represent.
        +        max_count = int(counts.max()) if num_blocks else 0
        +        pos_dtype = np.int32 if num_blocks < 2**31 else np.int64
        +        local_dtype = np.int32 if max_count < 2**31 else np.int64
        +        block_pos = np.repeat(np.arange(num_blocks, dtype=pos_dtype), counts)
        +        local_offset = (
        +            np.concatenate([np.arange(c, dtype=local_dtype) for c in counts])
        +            if num_blocks
        +            else np.array([], dtype=local_dtype)
        +        )
        +
        +        if shuffle and total_rows:
        +            sigma = _build_bounded_permutation(total_rows, max_shuffle_distance, seed)
        +        else:
        +            sigma = np.arange(total_rows, dtype=np.int64)
        +
        +        # sigma is itself a permutation of dense ranks, so inverting it
        +        # (argsort) directly gives, for each output position, which
        +        # natural rank -- and thus which (block, local offset) -- to draw.
        +        # Slicing off the first `skip` entries resumes at a saved absolute
        +        # position: those rows were already consumed in an earlier run, so
        +        # blocks that only appear before `skip` are simply never
        +        # referenced and never loaded.
        +        order = np.argsort(sigma, kind="stable")[skip:]
        +        self._plan_block_pos = block_pos[order]
        +        self._plan_local_offset = local_offset[order]
        +        self.num_rows = total_rows - skip
        +
        +        # Last plan position (inclusive) at which each block is still
        +        # needed, so it can be evicted as soon as we've read past it.
        +        # Computed with numpy (first occurrence in the reversed plan) rather
        +        # than a per-row Python loop: materializing the whole split's plan
        +        # as a Python list briefly costs about twice the plan arrays' memory.
        +        plan_len = len(self._plan_block_pos)
        +        if plan_len:
        +            visited, rev_first = np.unique(
        +                self._plan_block_pos[::-1], return_index=True
        +            )
        +            last_pos = plan_len - 1 - rev_first
        +            self._block_last_pos: dict[int, int] = dict(
        +                zip(visited.tolist(), last_pos.tolist())
        +            )
        +        else:
        +            self._block_last_pos = {}
        +
        +        # Distinct blocks in the order the plan first needs them. Prefetch
        +        # walks this (one entry per block) instead of rescanning raw plan
        +        # positions, which costs one Python step per *row* scanned and
        +        # dominates read time once max_shuffle_distance is large.
        +        if plan_len:
        +            _, first_pos = np.unique(self._plan_block_pos, return_index=True)
        +            self._block_visit_order = self._plan_block_pos[np.sort(first_pos)].tolist()
        +        else:
        +            self._block_visit_order = []
        +        # Prefetch's starting point in _block_visit_order. Every entry
        +        # before it is a block whose last use is already behind the read
        +        # watermark, so rescanning that ever-growing prefix on each top-up
        +        # would make prefetch cost quadratic in the split's block count.
        +        self._visit_cursor = 0
        +        # io_queue_depth submits several calls at once and they may take
        +        # _lock out of order, so a later call's max index is not a safe
        +        # eviction point: an earlier, still-waiting call can need a block
        +        # whose last use precedes it, and evicting it forces a re-read.
        +        # Evict only behind _served_prefix, the first plan position not yet
        +        # returned by any call.
        +        self._served = np.zeros(self.num_rows, dtype=bool)
        +        self._served_prefix = 0
        +        # Created last so a failed construction leaves no threads behind.
        +        self._executor = ThreadPoolExecutor(max_workers=self._prefetch_depth)
        +
        +    def _load_block(self, block_id: Any) -> pa.Table:
        +        # A block read can arrive as several record batches. Table.take on a
        +        # multi-chunk column concatenates the whole column first, so every
        +        # later gather from this block would copy all of it; combining once
        +        # here pays that copy a single time per block instead of per call.
        +        return self._read_block_fn(block_id).combine_chunks()
        +
        +    def _advance_served_prefix(self, idx_arr: np.ndarray) -> int:
        +        """Mark ``idx_arr`` served; return the last position of the served prefix."""
        +        self._served[idx_arr] = True
        +        n = self.num_rows
        +        while self._served_prefix < n:
        +            window = self._served[self._served_prefix : self._served_prefix + 4096]
        +            if window.all():
        +                self._served_prefix += len(window)
        +            else:
        +                self._served_prefix += int(window.argmin())
        +                break
        +        return self._served_prefix - 1
        +
        +    def __getitems__(self, indices) -> pa.RecordBatch:
        +        # Fancy-indexed (not sliced) so this also supports non-contiguous
        +        # index lists, not just the contiguous range(start, start + fetch)
        +        # that the main I/O pipeline requests.
        +        idx_arr = np.asarray(indices, dtype=np.int64)
        +        with self._lock:
        +            block_pos_slice = self._plan_block_pos[idx_arr]
        +            local_off_slice = self._plan_local_offset[idx_arr]
        +            for bp in np.unique(block_pos_slice).tolist():
        +                if bp not in self._loaded:
        +                    if bp in self._pending:
        +                        # Prefetched by an earlier call: block on it only if
        +                        # it hasn't finished yet -- often it already has.
        +                        self._loaded[bp] = self._pending.pop(bp).result()
        +                    else:
        +                        # read_block_fn already returns only this block's
        +                        # live rows, in natural (ascending) order -- no
        +                        # further filtering or reordering needed here.
        +                        self._loaded[bp] = self._load_block(self._block_ids[bp])
        +
        +            # Group by source block (stable, so each block's rows keep
        +            # their relative order), gather from each, then invert the
        +            # grouping to restore this chunk's actual priority order.
        +            group_order = np.argsort(block_pos_slice, kind="stable")
        +            grouped_block_pos = block_pos_slice[group_order]
        +            grouped_local_off = local_off_slice[group_order]
        +            run_starts = np.flatnonzero(np.diff(grouped_block_pos)) + 1
        +            bounds = [0, *run_starts.tolist(), len(grouped_block_pos)]
        +            tables = [
        +                self._loaded[int(grouped_block_pos[start])].take(
        +                    grouped_local_off[start:end]
        +                )
        +                for start, end in zip(bounds[:-1], bounds[1:])
        +            ]
        +            combined = pa.concat_tables(tables)
        +            inverse = np.argsort(group_order)
        +            result = combined.take(inverse)
        +
        +            watermark = self._advance_served_prefix(idx_arr)
        +            for bp in list(self._loaded):
        +                if self._block_last_pos.get(bp, -1) <= watermark:
        +                    del self._loaded[bp]
        +
        +            # Top up the prefetch queue: scan forward from this call's end
        +            # for blocks the plan is about to need that aren't already
        +            # loaded or already being fetched, and hand them to the
        +            # background executor so a later call can often just pick up
        +            # the (by then finished) result above instead of blocking.
        +            room = self._prefetch_depth - len(self._pending)
        +            if room > 0:
        +                visit_order = self._block_visit_order
        +                while (
        +                    self._visit_cursor < len(visit_order)
        +                    and self._block_last_pos[visit_order[self._visit_cursor]]
        +                    <= watermark
        +                ):
        +                    self._visit_cursor += 1
        +                for i in range(self._visit_cursor, len(visit_order)):
        +                    if room == 0:
        +                        break
        +                    bp = visit_order[i]
        +                    if bp in self._loaded or bp in self._pending:
        +                        continue
        +                    if self._block_last_pos.get(bp, -1) <= watermark:
        +                        # Already read past: never needed again.
        +                        continue
        +                    self._pending[bp] = self._executor.submit(
        +                        self._load_block, self._block_ids[bp]
        +                    )
        +                    room -= 1
        +
        +        if self._columns is not None:
        +            result = result.select(self._columns)
        +        return result.combine_chunks().to_batches()[0]
        +
        +    def close(self) -> None:
        +        """Release this reader's background prefetch executor."""
        +        self._executor.shutdown(wait=False, cancel_futures=True)
        +
        +
        +def _default_worker_start_method() -> str:
        +    """Return the worker start method used when the caller omits a context."""
        +    if "forkserver" in get_all_start_methods():
        +        return "forkserver"
        +    return "spawn"
        +
        +
        +class _BlockSlice(NamedTuple):
        +    """Rows ``[start, stop)`` of one 2-phase block, by position within the block."""
        +
        +    block_id: int
        +    start: int
        +    stop: int
         
         
         class _WorkerSample(NamedTuple):
        @@ -261,6 +572,7 @@ class StreamingDataset(IterableDataset):
                 ``split_strategy=lambda b: b.bootstrap_sample(10_000, fixed=num_splits,
                 seed=42)`` draws 10,000 samples with replacement, divided evenly across
                 ``num_splits`` splits.
        +        Cannot be combined with ``block_size``.
             shuffle_seed:
                 Base seed for the random permutation.  Combined with ``epoch`` so
                 each epoch produces a different ordering.  Pass ``None`` to generate
        @@ -286,7 +598,8 @@ class StreamingDataset(IterableDataset):
                 once this many batches are buffered, applying backpressure when the
                 transform stage (or ``transform_queue_depth``) is the bottleneck.
                 Must be greater than zero.  Defaults to ``DEFAULT_PREFETCH_BATCHES``
        -        (4).
        +        (4).  In 2-phase mode (``block_size`` set) this also sizes each split's
        +        background block-prefetch depth.
             columns:
                 Optional list of column names to read.  When set, only those columns
                 are fetched from storage; all others are omitted.  ``None`` (the
        @@ -295,7 +608,50 @@ class StreamingDataset(IterableDataset):
                 When set, rows are shuffled in contiguous groups of this size rather
                 than individually.  Larger clumps improve I/O locality (important on
                 object storage) at the cost of reduced randomness.  ``None`` (the
        -        default) shuffles rows individually.
        +        default) shuffles rows individually.  Cannot be combined with
        +        ``block_size`` (2-phase mode has its own locality/randomness knobs,
        +        below).
        +    block_size:
        +        Enables 2-phase shuffled reads: rows are shuffled at the granularity
        +        of contiguous blocks of exactly this many live rows, and each split
        +        reads a rolling window of ``window_blocks`` blocks at a time instead
        +        of taking individual rows by row-id.  This trades some randomness
        +        for I/O that is mostly contiguous range scans (or, when ``filter``
        +        is set, sparse takes of just the live rows) rather than one row-id
        +        take per row, which is far cheaper on object storage.  ``None`` (the
        +        default) uses 1-phase shuffling, which permutes every row
        +        individually up front.  512 is a good starting point: 128-2,048
        +        matched 1-phase validation loss in GPT-2 pretraining, and S3
        +        throughput was flat from 128 to 65,536.  Throughput comes from
        +        reading many splits in parallel, so use DataLoader workers (and
        +        ``num_splits`` of at least the worker count); with no workers,
        +        2-phase can be slower than 1-phase.  Each split serves the same
        +        number of (live) rows, so a split may start or end partway through
        +        a block; as in 1-phase, fewer than ``num_splits`` rows are dropped
        +        per epoch.
        +    window_blocks:
        +        Number of blocks kept in RAM per split at once in 2-phase mode.
        +        Larger windows shuffle across more rows at the cost of more memory;
        +        must be at least 1.  Requires ``block_size``.  Defaults to
        +        ``DEFAULT_WINDOW_BLOCKS`` (8).
        +    max_shuffle_distance:
        +        Bounds how far, in rows, 2-phase shuffling may displace a row from
        +        its position in unshuffled (block, then row) order.  Requires
        +        ``block_size``.  Smaller values shuffle less but let a block's RAM
        +        be reclaimed and refilled with the next block sooner; larger values
        +        shuffle more but hold blocks in RAM longer.  Defaults to
        +        ``window_blocks * block_size``, so the default window actually
        +        holds ``window_blocks`` blocks in RAM at once; pass this explicitly
        +        to decouple the shuffle bound from ``window_blocks``.
        +    reshuffle_blocks_per_epoch:
        +        Whether ``epoch`` feeds into which blocks are assigned to which
        +        split, in addition to the row-level shuffle within each split's
        +        blocks (which always varies by epoch).  Requires ``block_size``.
        +        ``True`` (the default) reassigns blocks every epoch, matching
        +        1-phase's per-epoch row reassignment.  ``False`` keeps each
        +        split's blocks fixed across epochs -- only the row order within
        +        them changes -- which keeps a block's on-disk location, and thus
        +        its read locality, stable across an entire training run.
             filter:
                 Optional SQL filter expression (e.g. ``"label = 'dog'"``).  Only rows
                 that satisfy the predicate are included in the permutation.  The filter
        @@ -448,6 +804,10 @@ class StreamingDataset(IterableDataset):
                 io_queue_depth: int = DEFAULT_PREFETCH_BATCHES,
                 columns: Optional[list[str]] = None,
                 shuffle_clump_size: Optional[int] = None,
        +        block_size: Optional[int] = None,
        +        window_blocks: Optional[int] = None,
        +        max_shuffle_distance: Optional[int] = None,
        +        reshuffle_blocks_per_epoch: Optional[bool] = None,
                 filter: Optional[str] = None,
                 transform: Optional[Callable] = None,
                 transform_parallelism: Optional[int] = None,
        @@ -482,6 +842,30 @@ class StreamingDataset(IterableDataset):
                     )
                 if io_queue_depth <= 0:
                     raise ValueError("io_queue_depth must be greater than 0")
        +        if block_size is not None and block_size <= 1:
        +            raise ValueError("block_size must be greater than 1")
        +        if block_size is None:
        +            if window_blocks is not None:
        +                raise ValueError("window_blocks requires block_size to be set")
        +            if max_shuffle_distance is not None:
        +                raise ValueError("max_shuffle_distance requires block_size to be set")
        +            if reshuffle_blocks_per_epoch is not None:
        +                raise ValueError(
        +                    "reshuffle_blocks_per_epoch requires block_size to be set"
        +                )
        +        else:
        +            if window_blocks is not None and window_blocks < 1:
        +                raise ValueError("window_blocks must be at least 1")
        +            if max_shuffle_distance is not None and max_shuffle_distance <= 0:
        +                raise ValueError("max_shuffle_distance must be greater than 0")
        +            if split_strategy is not None:
        +                raise ValueError("split_strategy cannot be combined with block_size")
        +            if shuffle_clump_size is not None:
        +                raise ValueError(
        +                    "shuffle_clump_size cannot be combined with block_size "
        +                    "(2-phase mode uses window_blocks/max_shuffle_distance "
        +                    "instead); remove one of them"
        +                )
                 if transform_parallelism is not None and transform_parallelism <= 0:
                     raise ValueError("transform_parallelism must be greater than 0")
                 if pack_sequences is not None:
        @@ -561,6 +945,7 @@ class StreamingDataset(IterableDataset):
                 self._io_queue_depth = io_queue_depth
                 self._columns = columns
                 self._shuffle_clump_size = shuffle_clump_size
        +        self._block_size = block_size
                 self._filter = filter
                 self._transform = transform
                 self._transform_parallelism = transform_parallelism
        @@ -640,74 +1025,185 @@ class StreamingDataset(IterableDataset):
                 # this instance has never iterated have no entry.
                 self._resume_positions: dict[int, int] = {}
         
        -        # Build the permutation table once, deterministically.
        -        builder = permutation_builder(table)
        -        if filter is not None:
        -            builder = builder.filter(filter)
        -        if split_strategy is not None:
        -            # Escape hatch: lets any PermutationBuilder split strategy drive this
        -            # dataset (split_hash, split_calculated, bootstrap_sample, or any future
        -            # strategy) without StreamingDataset needing a bespoke parameter for each
        -            # one. shuffle/shuffle_seed/epoch/shuffle_clump_size are ignored in this
        -            # path -- the caller's split_strategy is solely responsible for ordering.
        -            self._perm_table = split_strategy(builder).execute()
        -            # _rank_splits below assumes split ids are exactly 0..num_splits-1 with no
        -            # gaps (every other path guarantees this by always building with
        -            # fixed=num_splits) -- a split_strategy callable has no such guarantee, and
        -            # a mismatch would otherwise silently drop rows (ids >= num_splits) or leave
        -            # some ranks reading an empty split (missing ids < num_splits).
        -            split_value_counts = (
        -                self._perm_table.to_arrow().column("split_id").value_counts()
        -            )
        -            counts_by_split = dict(
        -                zip(
        -                    split_value_counts.field("values").to_pylist(),
        -                    split_value_counts.field("counts").to_pylist(),
        -                )
        -            )
        -            expected_splits = set(range(num_splits))
        -            if set(counts_by_split) != expected_splits:
        +        if block_size is not None:
        +            # 2-phase shuffled read: the source dataset is never given a
        +            # row-level permutation.  Instead we only shuffle at the
        +            # granularity of contiguous row blocks; _perm_table (and its
        +            # row-by-row index mapping) is not built at all in this mode.
        +            #
        +            # block_size counts LIVE rows (rows passing `filter`), not raw
        +            # rows.
        +            #
        +            # Pin the exact version/branch the block plan below is computed
        +            # against, so a write to the table between construction and a
        +            # later iteration (or between epochs) cannot shift which rows a
        +            # block refers to.  Read paths in _read_block always reopen a
        +            # private handle checked out to this pin (see
        +            # _open_pinned_table) rather than reading the table's live,
        +            # possibly-since-mutated state.  Branch pinning isn't
        +            # implemented yet -- the reopened handle always lands on the
        +            # default branch (see _table_from_pickle_state) -- so a table
        +            # checked out to a non-default branch is rejected below rather
        +            # than silently pinning the wrong branch.
        +            self._pinned_branch = table.current_branch()
        +            if self._pinned_branch is not None:
                         raise ValueError(
        -                    f"split_strategy produced split ids {sorted(counts_by_split)}, "
        -                    f"but num_splits={num_splits} requires exactly "
        -                    f"{{0, ..., {num_splits - 1}}}. Pass num_splits matching the "
        -                    "strategy's own split count (e.g. `fixed=num_splits` on "
        -                    "bootstrap_sample/split_random/etc.)."
        +                    "block_size does not yet support a table checked out to "
        +                    f"a non-default branch ({self._pinned_branch!r}); check "
        +                    "out the default branch before constructing StreamingDataset"
                         )
        -            # The round-robin iteration below (and in _iter_owned) assumes every
        -            # split has the same row count -- it stops as soon as any one owned
        -            # split is exhausted (see its own comment: "all splits exhaust
        -            # simultaneously"). Every other path guarantees this by always building
        -            # with fixed=num_splits; a split_strategy using ratios/counts/split_hash
        -            # weights has no such guarantee, and unequal sizes would otherwise
        -            # silently drop rows from the larger splits -- or, with world_size > 1
        -            # where each rank owns different splits, end ranks after different row
        -            # counts and desync or hang a distributed run's end-of-epoch collectives.
        -            if len(set(counts_by_split.values())) > 1:
        +            # An RTE write spec means some acknowledged writes only exist in
        +            # the MemWAL, not yet flushed into the base table that the native
        +            # scanner/take paths below read; a version pin can't see them, so
        +            # reads here would silently omit them with no error.  1-phase
        +            # already refuses this for the same reason (unflushed rows have
        +            # no row id -- see PermutationBuilder); block_size mode has no
        +            # row ids in its read path either, but reads positionally, so it
        +            # fails differently (stale values, not a missing-row-id error)
        +            # and needs its own explicit check.
        +            if table.get_rte_spec() is not None:
                         raise ValueError(
        -                    f"split_strategy produced unequal split sizes "
        -                    f"{counts_by_split} (split id -> row count). Every split must "
        -                    "have the same row count. Use `fixed=num_splits` rather than "
        -                    "`ratios`/`counts`/weighted `split_hash`, which can produce "
        -                    "unequal sizes, or split unevenly-sized groups into separate "
        -                    "StreamingDatasets instead."
        +                    "block_size does not yet support a table with an RTE "
        +                    "write spec set; unflushed MemWAL rows are not visible "
        +                    "to a version-pinned read, so block reads could "
        +                    "silently miss acknowledged writes. Call "
        +                    "table.checkpoint_rte() and table.disable_rte() "
        +                    "first, or construct StreamingDataset without block_size"
                         )
        -        elif shuffle:
        -            perm_seed = shuffle_seed + epoch * _EPOCH_PRIME
        -            self._perm_table = builder.split_random(
        -                fixed=num_splits, seed=perm_seed, clump_size=shuffle_clump_size
        -            ).execute()
        -        else:
        -            self._perm_table = builder.split_sequential(fixed=num_splits).execute()
        -        # Only the split_strategy path needs a permutation fingerprint in the
        -        # checkpoint (see `_checkpoint_snapshot`): split_random/split_sequential are
        -        # already fully pinned by shuffle_seed/num_splits, and a fingerprint over raw
        -        # row ids would spuriously reject an otherwise-valid resume after those row
        -        # ids get renumbered by compaction (row ids are not stable by default).
        -        self._uses_split_strategy = split_strategy is not None
        -        # Lazily computed and cached by `_perm_fingerprint` -- `_perm_table` never
        -        # changes after construction, so this is correct to compute once.
        -        self._perm_fingerprint_cache: Optional[str] = None
        +            self._pinned_version = table.version
        +            # Captured once, now, rather than recomputed on every
        +            # _open_pinned_table() call: for a memory table, the "pickle
        +            # state" below IS the row data (to_arrow()), not just reopen
        +            # coordinates, so recomputing it later would silently capture
        +            # whatever the live table looks like *then* instead of the
        +            # snapshot this pin is supposed to mean.  Not used for a
        +            # RemoteTable -- see _open_pinned_table, which deep-copies it
        +            # directly instead.
        +            from .remote.table import RemoteTable as _RemoteTable
        +
        +            self._pinned_table_state: Optional[dict] = (
        +                _table_to_pickle_state(table)
        +                if self._connection_factory is None
        +                and not isinstance(table, _RemoteTable)
        +                else None
        +            )
        +
        +            pinned_for_setup = self._open_pinned_table()
        +            # Remote block reads go through take_offsets, which doesn't
        +            # guarantee its output order, so they additionally select
        +            # "_rowoffset" and sort locally by it (see _read_block); when the
        +            # caller didn't narrow columns, that means explicitly listing
        +            # every column, hence caching the full list once here.
        +            self._all_columns: Optional[list[str]] = (
        +                pinned_for_setup.schema.names if columns is None else None
        +            )
        +            self._live_offsets: Optional[np.ndarray] = None
        +            if filter is None:
        +                num_rows = pinned_for_setup.count_rows()
        +            else:
        +                self._live_offsets = self._scan_live_offsets(pinned_for_setup)
        +                num_rows = int(self._live_offsets.size)
        +
        +            # Every block holds exactly block_size live rows except a
        +            # trailing runt, so no per-block range or count list is kept:
        +            # anything sized by the block count also inflates the pickle
        +            # shipped to each DataLoader worker (see __getstate__).
        +            self._num_rows = num_rows
        +            self._num_blocks = -(-num_rows // block_size)
        +            full_blocks = num_rows // block_size
        +            if full_blocks < num_splits:
        +                raise ValueError(
        +                    f"block_size={block_size} yields only {full_blocks} "
        +                    f"block(s) from {num_rows} row(s), fewer than num_splits "
        +                    f"({num_splits}); use a smaller block_size or fewer splits"
        +                )
        +            # Whether the epoch feeds into the block shuffle (so which
        +            # blocks a split owns changes every epoch, same as 1-phase's
        +            # row assignment) or only into the row-level shuffle within
        +            # each split's fixed blocks (so blocks stay pinned to the same
        +            # split/location across epochs, and only their row order
        +            # varies).  Defaults to True: matches the pre-existing
        +            # behavior of using epoch for both.
        +            self._reshuffle_blocks_per_epoch = (
        +                reshuffle_blocks_per_epoch
        +                if reshuffle_blocks_per_epoch is not None
        +                else True
        +            )
        +            # Kept as a plain Python list for simplicity, unlike the
        +            # 1-phase row mapping below, which is Arrow-backed because it
        +            # is built and consumed through the Arrow-based permutation
        +            # table machinery; a block permutation has no such need.
        +            self._block_perm: Optional[list[int]] = self._shuffled_block_order()
        +            self._perm_table = None
        +            # Block mode has no PermutationBuilder output to fingerprint.
        +            # These fields still drive common checkpoint code.
        +            self._uses_split_strategy = False
        +            self._perm_fingerprint_cache: Optional[str] = None
        +
        +            # window_blocks is the primary residency knob: by default,
        +            # max_shuffle_distance (the displacement bound that actually
        +            # drives which blocks stay resident -- see
        +            # _TwoPhaseSplitReader) is derived from it so that a split
        +            # holds roughly window_blocks blocks in RAM at once. Passing
        +            # max_shuffle_distance explicitly overrides that derivation.
        +            self._window_blocks = (
        +                window_blocks if window_blocks is not None else DEFAULT_WINDOW_BLOCKS
        +            )
        +            self._max_shuffle_distance = (
        +                max_shuffle_distance
        +                if max_shuffle_distance is not None
        +                else self._window_blocks * block_size
        +            )
        +        else:  # 1-phase shuffled read
        +            # Build the permutation table once, deterministically.
        +            builder = permutation_builder(table)
        +            if filter is not None:
        +                builder = builder.filter(filter)
        +            if split_strategy is not None:
        +                # Escape hatch: lets any PermutationBuilder split strategy drive
        +                # this dataset without a bespoke parameter for each strategy.
        +                self._perm_table = split_strategy(builder).execute()
        +                # _rank_splits assumes split ids are exactly 0..num_splits-1.
        +                split_value_counts = (
        +                    self._perm_table.to_arrow().column("split_id").value_counts()
        +                )
        +                counts_by_split = dict(
        +                    zip(
        +                        split_value_counts.field("values").to_pylist(),
        +                        split_value_counts.field("counts").to_pylist(),
        +                    )
        +                )
        +                expected_splits = set(range(num_splits))
        +                if set(counts_by_split) != expected_splits:
        +                    raise ValueError(
        +                        f"split_strategy produced split ids {sorted(counts_by_split)}, "
        +                        f"but num_splits={num_splits} requires exactly "
        +                        f"{{0, ..., {num_splits - 1}}}. Pass num_splits matching the "
        +                        "strategy's own split count (e.g. `fixed=num_splits` on "
        +                        "bootstrap_sample/split_random/etc.)."
        +                    )
        +                # Round-robin iteration assumes every split has the same row count.
        +                if len(set(counts_by_split.values())) > 1:
        +                    raise ValueError(
        +                        f"split_strategy produced unequal split sizes "
        +                        f"{counts_by_split} (split id -> row count). Every split must "
        +                        "have the same row count. Use `fixed=num_splits` rather than "
        +                        "`ratios`/`counts`/weighted `split_hash`, which can produce "
        +                        "unequal sizes, or split unevenly-sized groups into separate "
        +                        "StreamingDatasets instead."
        +                    )
        +            elif shuffle:
        +                perm_seed = shuffle_seed + epoch * _EPOCH_PRIME
        +                self._perm_table = builder.split_random(
        +                    fixed=num_splits, seed=perm_seed, clump_size=shuffle_clump_size
        +                ).execute()
        +            else:
        +                self._perm_table = builder.split_sequential(fixed=num_splits).execute()
        +            # Only split_strategy needs a fingerprint: the built-in strategies
        +            # are pinned by shuffle_seed/num_splits, while row ids can change
        +            # across compaction.
        +            self._uses_split_strategy = split_strategy is not None
        +            self._perm_fingerprint_cache: Optional[str] = None
         
                 if self._blocks_per_epoch == "auto":
                     self._blocks_per_epoch = self._estimate_blocks_per_epoch()
        @@ -719,6 +1215,236 @@ class StreamingDataset(IterableDataset):
                     range(rank_start, rank_start + splits_per_rank)
                 )
         
        +    def _open_pinned_table(self):
        +        """Open a private table handle checked out to this dataset's pin.
        +
        +        A fresh handle so checking it out to the pinned version never
        +        mutates ``self._table``, which the caller may still be using
        +        elsewhere.  Goes through ``Table.checkout``/``take_offsets``/
        +        ``search`` -- the same backend-agnostic interface ``RemoteTable``
        +        implements -- instead of pylance's ``to_lance()``, which only
        +        works against a local table.
        +
        +        Three cases, each independent of ``self._table`` by construction:
        +
        +        - ``connection_factory`` set: call it fresh every time (the
        +          documented way to get an unrelated handle; e.g. a worker
        +          reconnect).
        +        - A ``RemoteTable``: ``_table_to_pickle_state``/
        +          ``_table_from_pickle_state`` (used below for the other two cases)
        +          special-case "remote" by returning ``self._table`` itself --
        +          correct for their original purpose (cross-process pickling, where
        +          the unpickled copy necessarily lives in a different process), but
        +          wrong here, since this runs in the *same* process: calling
        +          ``checkout()`` on that result would pin (and, since LanceDB Cloud
        +          rejects writes through a version-pinned handle, effectively make
        +          read-only) the caller's own table object.  ``deepcopy`` instead
        +          round-trips through ``RemoteTable.__getstate__``/``__setstate__``,
        +          which carries only reopen coordinates (connection state, branch,
        +          checkout version) and clears the live connection handle, so the
        +          copy reconnects independently on first real use.
        +        - Local or memory: ``self._pinned_table_state`` (captured once at
        +          construction -- see ``__init__``) is replayed here instead of
        +          recomputing ``_table_to_pickle_state(self._table)`` fresh each
        +          call.  For a local (on-disk) table this would barely matter (the
        +          state is just reopen coordinates, not data), but for a memory
        +          table the "pickle state" the helper returns *is* the row data
        +          (``to_arrow()``); recomputing it on every call would silently
        +          capture whatever the live table looks like at that later moment
        +          instead of the snapshot construction actually pinned.  A reopened
        +          memory table is always a fresh version-1 table, so there is
        +          nothing meaningful to additionally ``checkout()`` -- it already
        +          is exactly the pinned snapshot by construction.
        +        """
        +        if self._connection_factory is not None:
        +            # The factory may hand back a cached, caller-owned handle, and
        +            # checkout() pins whatever handle it is called on, so pin a copy.
        +            # Copy over the live connection rather than through pickle state:
        +            # the factory exists so workers can hold unpicklable connections
        +            # (e.g. with a Session), and an in-memory table must keep its
        +            # version history for the checkout to find the snapshot.
        +            handle = self._connection_factory(self._table.name)
        +            if isinstance(handle, LanceTable):
        +                pinned = handle._private_copy()
        +            else:
        +                pinned = deepcopy(handle)
        +            pinned.checkout(self._pinned_version)
        +            return pinned
        +
        +        if self._pinned_table_state is None:
        +            # Only a RemoteTable skips capturing _pinned_table_state (see
        +            # __init__) -- anything else reaching here is a construction
        +            # bug, not a runtime condition callers can hit.
        +            pinned = deepcopy(self._table)
        +            pinned.checkout(self._pinned_version)
        +            return pinned
        +
        +        pinned = _table_from_pickle_state(self._pinned_table_state)
        +        if self._pinned_table_state["kind"] != "memory":
        +            pinned.checkout(self._pinned_version)
        +        return pinned
        +
        +    def _pinned_lance_dataset(self, pinned_table):
        +        """Native pylance handle for ``pinned_table``, if it's an on-disk table.
        +
        +        ``to_lance()`` raises ``NotImplementedError`` on ``RemoteTable``, and
        +        -- for a different reason -- also fails on a reopened ``memory://``
        +        table: ``_open_pinned_table`` rebuilds it as an isolated store (see
        +        its docstring), which pylance's raw ``lance.dataset()`` open (what
        +        ``to_lance()`` uses) cannot resolve; only the table's own connection
        +        handle can see its data. Both cases are excluded here up front
        +        rather than only via the ``except``, since the memory failure is a
        +        ``ValueError`` indistinguishable from a real error. Cached per
        +        dataset instance (keyed by nothing -- there's only ever one pin per
        +        instance) so the conversion runs at most once rather than once per
        +        block read. ``None`` means callers must use the backend-agnostic
        +        query builder instead.
        +        """
        +        if not hasattr(self, "_pinned_lance_ds_cache"):
        +            conn_uri = getattr(getattr(pinned_table, "_conn", None), "uri", "")
        +            if conn_uri.startswith("memory://"):
        +                self._pinned_lance_ds_cache = None
        +            else:
        +                try:
        +                    self._pinned_lance_ds_cache = pinned_table.to_lance()
        +                except NotImplementedError:
        +                    self._pinned_lance_ds_cache = None
        +        return self._pinned_lance_ds_cache
        +
        +    def _scan_live_offsets(self, pinned_table) -> np.ndarray:
        +        """Ascending ``_rowoffset`` of every row matching ``filter``.
        +
        +        Lance evaluates the filter natively and returns only each live row's
        +        dataset-wide position, without materializing column data. Blocks are
        +        contiguous chunks of this array, so a block read is a sparse take of
        +        exactly its live rows. Goes through the table's own query builder
        +        rather than pylance, so this also works against a remote table.
        +        """
        +        live_offsets = (
        +            pinned_table.search()
        +            .where(self._filter)
        +            .select(["_rowoffset"])
        +            .to_arrow()
        +            .column("_rowoffset")
        +            .to_numpy()
        +        )
        +        # Block and row semantics assume ascending order, which scan
        +        # execution order doesn't guarantee.
        +        if live_offsets.size and not np.all(live_offsets[:-1] <= live_offsets[1:]):
        +            live_offsets = np.sort(live_offsets)
        +        return live_offsets
        +
        +    def _read_block(
        +        self, pinned_table, block: _BlockSlice, columns: Optional[list[str]]
        +    ) -> pa.Table:
        +        """Read one 2-phase block slice's live rows, in natural (ascending) order."""
        +        lance_ds = self._pinned_lance_dataset(pinned_table)
        +        block_start = block.block_id * self._block_size
        +        row_start = block_start + block.start
        +        row_end = block_start + block.stop
        +        if self._filter is None:
        +            if lance_ds is not None:
        +                # Local table: pylance's positional range scan returns rows in
        +                # storage order and is much faster than a take.
        +                return lance_ds.scanner(
        +                    offset=row_start, limit=row_end - row_start, columns=columns
        +                ).to_table()
        +            # Remote offset/limit pages don't guarantee a consistent row order
        +            # across requests, so independent pages can overlap or skip rows;
        +            # explicit offsets name exactly this block's rows.
        +            offsets = np.arange(row_start, row_end, dtype=np.int64)
        +        else:
        +            offsets = self._live_offsets[row_start:row_end]
        +            if lance_ds is not None:
        +                # Local table: pylance's native take() preserves the requested
        +                # offset order already, so no sort-and-rebuild pass is needed.
        +                return lance_ds.take(offsets.tolist(), columns=columns)
        +
        +        # take_offsets makes no ordering guarantee for an arbitrary index
        +        # list, so "_rowoffset" is always also selected and used to restore
        +        # the request's ascending order locally.
        +        select_cols = (columns if columns is not None else self._all_columns) + [
        +            "_rowoffset"
        +        ]
        +        table = (
        +            pinned_table.take_offsets(offsets.tolist()).select(select_cols).to_arrow()
        +        )
        +        order = pc.sort_indices(table.column("_rowoffset"))
        +        return table.take(order).drop_columns(["_rowoffset"])
        +
        +    def _shuffled_block_order(self) -> list[int]:
        +        """The epoch's block permutation, derived only from scalar config."""
        +        block_order = list(range(self._num_blocks))
        +        if self._shuffle:
        +            block_seed = self._shuffle_seed
        +            if self._reshuffle_blocks_per_epoch:
        +                block_seed += self._epoch * _EPOCH_PRIME
        +            random.Random(block_seed).shuffle(block_order)
        +        return block_order
        +
        +    def _split_blocks(self, split_idx: int) -> list[_BlockSlice]:
        +        """Block slices assigned to one split, in the split's read order.
        +
        +        The epoch's shuffled blocks, laid end to end, form one row stream;
        +        split k owns rows ``[k * n, (k + 1) * n)`` of it, where
        +        ``n = num_rows // num_splits``. Cutting by rows rather than whole
        +        blocks drops fewer than ``num_splits`` rows per epoch, like 1-phase,
        +        so a split's first and last blocks may be partial.
        +        """
        +        block_perm = np.asarray(self._block_perm, dtype=np.int64)
        +        block_rows = np.full(len(block_perm), self._block_size, dtype=np.int64)
        +        runt = self._num_rows - (self._num_blocks - 1) * self._block_size
        +        block_rows[block_perm == self._num_blocks - 1] = runt
        +        block_ends = np.cumsum(block_rows)
        +
        +        rows_per_split = self._num_rows // self._num_splits
        +        split_start = split_idx * rows_per_split
        +        split_end = split_start + rows_per_split
        +        first = int(np.searchsorted(block_ends, split_start, side="right"))
        +        last = int(np.searchsorted(block_ends, split_end, side="left"))
        +        blocks = []
        +        for pos in range(first, last + 1):
        +            block_start = int(block_ends[pos] - block_rows[pos])
        +            blocks.append(
        +                _BlockSlice(
        +                    block_id=int(block_perm[pos]),
        +                    start=max(split_start, block_start) - block_start,
        +                    stop=min(split_end, int(block_ends[pos])) - block_start,
        +                )
        +            )
        +        return blocks
        +
        +    def _make_two_phase_reader(
        +        self,
        +        split_idx: int,
        +        pinned_table,
        +        columns: Optional[list[str]],
        +        skip: int = 0,
        +    ) -> "_TwoPhaseSplitReader":
        +        """Build the 2-phase reader for one split's assigned blocks.
        +
        +        ``skip`` resumes from a saved absolute position within the split's
        +        own deterministic read order (see ``_TwoPhaseSplitReader``).
        +        """
        +        blocks = self._split_blocks(split_idx)
        +        sigma_seed = (
        +            self._shuffle_seed
        +            + self._epoch * _EPOCH_PRIME
        +            + _SIGMA_PRIME
        +            + split_idx * _SIGMA_SPLIT_PRIME
        +        )
        +        return _TwoPhaseSplitReader(
        +            block_ids=blocks,
        +            block_live_counts=[block.stop - block.start for block in blocks],
        +            shuffle=self._shuffle,
        +            max_shuffle_distance=self._max_shuffle_distance,
        +            seed=sigma_seed,
        +            read_block_fn=lambda block: self._read_block(pinned_table, block, columns),
        +            columns=columns,
        +            skip=skip,
        +            prefetch_depth=self._io_queue_depth,
        +        )
        +
             def _estimate_blocks_per_epoch(self) -> int:
                 """Estimate a fixed packed-block budget from a bounded token sample."""
                 # TODO: Replace this fallback with Lance's dedicated exact token-count
        @@ -741,37 +1467,64 @@ class StreamingDataset(IterableDataset):
                     "pass an explicit value for exact epoch sizing",
                 )
         
        -        for split in range(self._num_splits):
        -            permutation = Permutation.from_tables(
        -                self._table, self._perm_table, split=split
        -            )
        -            permutation = permutation.select_columns([token_column])
        -            permutation = permutation.with_transform(Transforms.arrow2arrow)
        -            split_rows = permutation.num_rows
        -            if split_rows == 0:
        -                raise ValueError(
        -                    "blocks_per_epoch='auto' cannot estimate an empty dataset"
        -                )
        +        def _sampled_token_count(column: Union[pa.Array, pa.ChunkedArray]) -> int:
        +            lengths = pc.list_value_length(column)
        +            if lengths.null_count:
        +                raise ValueError("pack_sequences does not support null token lists")
        +            return int(pc.sum(lengths).as_py())
         
        +        def _sample_size(split_rows: int) -> int:
                     # Sample roughly 1% from each logical split, with at least one row
                     # per split and a global target cap of 100,000 rows.
        -            sample_rows = min(
        +            return min(
                         split_rows,
                         max(1, min((split_rows + 99) // 100, sample_cap_per_split)),
                     )
        -            sample_offsets = sorted(rng.sample(range(split_rows), sample_rows))
        -            sample_batch_size = max(1, self._read_batch_size)
        -            for start in range(0, sample_rows, sample_batch_size):
        -                batch = permutation.__getitems__(
        -                    sample_offsets[start : start + sample_batch_size]
        -                )
        -                lengths = pc.list_value_length(batch.column(0))
        -                if lengths.null_count:
        -                    raise ValueError("pack_sequences does not support null token lists")
        -                sampled_tokens += int(pc.sum(lengths).as_py())
         
        -            total_sampled += sample_rows
        -            total_rows += split_rows
        +        if self._block_size is not None:
        +            # Sample whole blocks rather than scattered rows: a row sample
        +            # spread over a split touches nearly every block, so it would
        +            # read the entire token column just to estimate it.  Only a
        +            # split's first and last blocks can be partial, so a uniform
        +            # sample of the split's own blocks still gives a near-unbiased
        +            # per-row mean over exactly the rows that split will serve.
        +            pinned_table = self._open_pinned_table()
        +            for split in range(self._num_splits):
        +                split_blocks = self._split_blocks(split)
        +                split_rows = sum(block.stop - block.start for block in split_blocks)
        +                num_sample_blocks = min(
        +                    len(split_blocks),
        +                    -(-_sample_size(split_rows) // self._block_size),
        +                )
        +                for block in rng.sample(split_blocks, num_sample_blocks):
        +                    table = self._read_block(pinned_table, block, [token_column])
        +                    sampled_tokens += _sampled_token_count(table.column(0))
        +                    total_sampled += table.num_rows
        +                total_rows += split_rows
        +        else:
        +            for split in range(self._num_splits):
        +                permutation = Permutation.from_tables(
        +                    self._table, self._perm_table, split=split
        +                )
        +                permutation = permutation.select_columns([token_column])
        +                permutation = permutation.with_transform(Transforms.arrow2arrow)
        +                split_rows = permutation.num_rows
        +                if split_rows == 0:
        +                    raise ValueError(
        +                        "blocks_per_epoch='auto' cannot estimate an empty dataset"
        +                    )
        +
        +                sample_rows = _sample_size(split_rows)
        +                sample_offsets = sorted(rng.sample(range(split_rows), sample_rows))
        +                sample_batch_size = max(1, self._read_batch_size)
        +                for start in range(0, sample_rows, sample_batch_size):
        +                    batch = permutation.__getitems__(
        +                        sample_offsets[start : start + sample_batch_size]
        +                    )
        +                    sampled_tokens += _sampled_token_count(batch.column(0))
        +
        +                total_sampled += sample_rows
        +                total_rows += split_rows
         
                 # Pool the samples into one global average. Each document contributes
                 # one EOS token.
        @@ -858,34 +1611,83 @@ class StreamingDataset(IterableDataset):
                 if not my_splits:
                     return
         
        -        # Set identity transform on each Permutation so __getitems__ returns
        -        # the raw RecordBatch.  Stage 2 applies the real transform.
        -        permutations: list[Permutation] = []
        -        initial_samples: list[int] = []
        -        initial_positions: list[int] = []
        -        for split_idx in my_splits:
        -            perm = Permutation.from_tables(
        -                self._table, self._perm_table, split=split_idx
        -            )
        -            if self._columns is not None:
        -                perm = perm.select_columns(self._columns)
        -            perm = perm.with_transform(Transforms.arrow2arrow)
        -            sample_count = self._resume_samples.get(split_idx, self._resume_offset)
        -            # Both modes resume from absolute permutation positions. Packing
        -            # stores them separately because it also checkpoints partial blocks.
        -            start_pos = (
        -                self._pack_consumed[split_idx]
        -                if self._pack_sequences is not None
        -                else self._resume_positions.get(split_idx, sample_count)
        -            )
        -            if start_pos > 0:
        -                perm = perm.with_skip(start_pos)
        -            initial_samples.append(sample_count)
        -            initial_positions.append(start_pos)
        -            permutations.append(perm)
        +        if self._block_size is None:
        +            # 1-phase: set identity transform on each Permutation so
        +            # __getitems__ returns the raw RecordBatch.  Stage 2 applies the
        +            # real transform.
        +            permutations: list[Permutation] = []
        +            initial_samples: list[int] = []
        +            initial_positions: list[int] = []
        +            for split_idx in my_splits:
        +                perm = Permutation.from_tables(
        +                    self._table, self._perm_table, split=split_idx
        +                )
        +                if self._columns is not None:
        +                    perm = perm.select_columns(self._columns)
        +                perm = perm.with_transform(Transforms.arrow2arrow)
        +                sample_count = self._resume_samples.get(split_idx, self._resume_offset)
        +                # Both modes resume from absolute permutation positions. Packing
        +                # stores them separately because it also checkpoints partial blocks.
        +                start_pos = (
        +                    self._pack_consumed[split_idx]
        +                    if self._pack_sequences is not None
        +                    else self._resume_positions.get(split_idx, sample_count)
        +                )
        +                if start_pos > 0:
        +                    perm = perm.with_skip(start_pos)
        +                initial_samples.append(sample_count)
        +                initial_positions.append(start_pos)
        +                permutations.append(perm)
         
        -        n = len(permutations)
        -        split_sizes = [perm.num_rows for perm in permutations]
        +            n = len(permutations)
        +            split_sizes = [perm.num_rows for perm in permutations]
        +        else:
        +            # 2-phase: each split owns an equal, contiguous run of rows from
        +            # the epoch's shuffled block order (see _split_blocks); the
        +            # fewer than num_splits leftover rows are dropped, as in 1-phase.
        +            #
        +            # Each split's blocks are wrapped in a _TwoPhaseSplitReader,
        +            # which duck-types Permutation.__getitems__ -- so from here on,
        +            # 2-phase flows through the exact same stage-1 I/O machinery
        +            # (_fill_io/_submit_io/_drain_io, io_queue_depth prefetch) as
        +            # 1-phase.  No 2-phase-specific code exists past this point.
        +            pinned_table = self._open_pinned_table()
        +
        +            permutations: list[_TwoPhaseSplitReader] = []
        +            initial_samples = []
        +            initial_positions = []
        +            for split_idx in my_splits:
        +                # Same absolute-position resume convention as 1-phase: a
        +                # loaded checkpoint's positions_consumed_per_split (falling
        +                # back to the sample count, then to the global offset) is
        +                # this split's saved absolute position in its own
        +                # deterministic read order.  Packing stores its own cursor
        +                # separately (it also checkpoints partial blocks), so it
        +                # must be consulted here too, exactly as the 1-phase branch
        +                # above does -- otherwise a packed resume silently ignores
        +                # _pack_consumed and replays already-consumed documents.
        +                sample_count = self._resume_samples.get(split_idx, self._resume_offset)
        +                start_pos = (
        +                    self._pack_consumed[split_idx]
        +                    if self._pack_sequences is not None
        +                    else self._resume_positions.get(split_idx, sample_count)
        +                )
        +                try:
        +                    reader = self._make_two_phase_reader(
        +                        split_idx, pinned_table, self._columns, skip=start_pos
        +                    )
        +                except BaseException:
        +                    # The consumer loop's finally, which closes the readers'
        +                    # prefetch executors, hasn't been entered yet.
        +                    for built in permutations:
        +                        built.close()
        +                    raise
        +                permutations.append(reader)
        +                initial_samples.append(sample_count)
        +                initial_positions.append(start_pos)
        +
        +            n = len(permutations)
        +            split_sizes = [reader.num_rows for reader in permutations]
                 local_consumed = [0] * n
                 # Permutation position each split has consumed through (absolute,
                 # i.e. counted from the start of the unskipped split).  Runs ahead of
        @@ -1325,6 +2127,13 @@ class StreamingDataset(IterableDataset):
                             self._fetch_head_ref = None
                             self._split_sizes_ref = None
                             self._local_consumed_ref = None
        +                    if self._block_size is not None:
        +                        # Each _TwoPhaseSplitReader owns a private prefetch
        +                        # executor; a fresh set is built on every
        +                        # _iter_owned call, so these must be shut down here
        +                        # or their threads leak across epochs/iterations.
        +                        for reader in permutations:
        +                            reader.close()
         
             @property
             def bytes_loaded(self) -> int:
        @@ -1455,9 +2264,11 @@ class StreamingDataset(IterableDataset):
                     state["_table"] = _table_to_pickle_state(self._table)
                 # _perm_table: always in-memory; serialise as Arrow data (mirrors
                 # how Permutation.__getstate__ handles its permutation_table).
        +        # None in 2-phase mode, which never builds one.
                 state["_perm_table"] = (
        -            self._perm_table.name,
        -            self._perm_table.to_arrow(),
        +            (self._perm_table.name, self._perm_table.to_arrow())
        +            if self._perm_table is not None
        +            else None
                 )
                 for key in (
                     "_raw_batches_ref",
        @@ -1468,6 +2279,22 @@ class StreamingDataset(IterableDataset):
                 ):
                     state[key] = None
                 state["_consumer_iterator_lock"] = None
        +        # Rebuilt in __setstate__.  Spawn/forkserver workers receive this
        +        # pickle through a pipe; once it outgrows the 64 KiB pipe buffer,
        +        # each Popen blocks until its child has imported torch and read it,
        +        # so a payload that scales with the block count serializes worker
        +        # startup (minutes at 128 workers with small blocks).
        +        if state.get("_block_perm") is not None:
        +            state["_block_perm"] = None
        +        # One entry per live row, so it would grow the pickle the same way;
        +        # each worker rescans it from the pinned snapshot in __setstate__.
        +        if state.get("_live_offsets") is not None:
        +            state["_live_offsets"] = None
        +        # Non-picklable Rust-backed handle (see _pinned_lance_dataset);
        +        # dropped rather than set to None so the worker's first _read_block
        +        # call recomputes it fresh against its own reconnected table instead
        +        # of permanently misreading an absent cache as "confirmed remote".
        +        state.pop("_pinned_lance_ds_cache", None)
                 return state
         
             def __setstate__(self, state):
        @@ -1476,17 +2303,27 @@ class StreamingDataset(IterableDataset):
         
                 table_name = state.pop("_table_name")
                 table_state = state.pop("_table")
        -        perm_name, perm_data = state.pop("_perm_table")
        +        perm_table_state = state.pop("_perm_table")
                 self.__dict__.update(state)
                 self._consumer_iterator_lock = threading.Lock()
        +        if "_block_perm" in state:
        +            self._block_perm = self._shuffled_block_order()
                 if self._connection_factory is not None:
                     self._table = self._connection_factory(table_name)
                 else:
                     self._table = _table_from_pickle_state(table_state)
        -            if table_state["kind"] == "memory":
        +            if table_state["kind"] == "memory" and perm_table_state is not None:
                         # Rebuilt from Arrow, so the recorded pin cannot resolve on it.
        -                perm_data = _drop_base_version(perm_data)
        -        self._perm_table = _connect("memory://").create_table(perm_name, perm_data)
        +                perm_name, perm_data = perm_table_state
        +                perm_table_state = (perm_name, _drop_base_version(perm_data))
        +        if perm_table_state is not None:
        +            perm_name, perm_data = perm_table_state
        +            self._perm_table = _connect("memory://").create_table(perm_name, perm_data)
        +        else:
        +            # 2-phase mode never builds a permutation table.
        +            self._perm_table = None
        +        if self._block_size is not None and self._filter is not None:
        +            self._live_offsets = self._scan_live_offsets(self._open_pinned_table())
         
             def state_dict(self) -> dict:
                 """Snapshot the dataset's consumption state.
        @@ -1577,6 +2414,22 @@ class StreamingDataset(IterableDataset):
                     self._perm_fingerprint_cache = hasher.hexdigest()
                 return self._perm_fingerprint_cache
         
        +    def _two_phase_checkpoint_config(self) -> dict:
        +        """The 2-phase settings a saved position is only meaningful under."""
        +        if self._block_size is None:
        +            return {}
        +        return {key: getattr(self, f"_{key}") for key in _TWO_PHASE_CHECKPOINT_KEYS}
        +
        +    def _check_two_phase_checkpoint_config(self, state: dict, source: str) -> None:
        +        ours = self._two_phase_checkpoint_config()
        +        for key in _TWO_PHASE_CHECKPOINT_KEYS:
        +            if state.get(key) != ours.get(key):
        +                raise ValueError(
        +                    f"{key} mismatch: {source} has {state.get(key)}, "
        +                    f"current dataset has {ours.get(key)}; saved positions "
        +                    "index a different 2-phase read order"
        +                )
        +
             def _checkpoint_snapshot(self) -> dict:
                 # Only recorded for split_strategy: split_random/split_sequential are
                 # already fully pinned by shuffle_seed/num_splits below, and row ids are not
        @@ -1592,6 +2445,7 @@ class StreamingDataset(IterableDataset):
                         "shuffle_seed": self._shuffle_seed,
                         "num_splits": self._num_splits,
                         **perm_fingerprint,
        +                **self._two_phase_checkpoint_config(),
                         "epoch": self._epoch,
                         "pack_sequences": self._pack_sequences,
                         "eos_id": self._eos_id,
        @@ -1613,6 +2467,7 @@ class StreamingDataset(IterableDataset):
                     "shuffle_seed": self._shuffle_seed,
                     "num_splits": self._num_splits,
                     **perm_fingerprint,
        +            **self._two_phase_checkpoint_config(),
                     "epoch": self._epoch,
                     "samples_consumed_per_split": samples,
                     "positions_consumed_per_split": positions,
        @@ -1683,6 +2538,7 @@ class StreamingDataset(IterableDataset):
                             f"{key} mismatch in worker checkpoint: "
                             f"{state.get(key)} != {expected}"
                         )
        +        self._check_two_phase_checkpoint_config(state, "worker checkpoint")
                 packed = "pack_buffers" in state
                 if packed != (self._pack_sequences is not None):
                     raise ValueError("worker checkpoint mode does not match the dataset")
        @@ -1752,7 +2608,10 @@ class StreamingDataset(IterableDataset):
                 across compaction, so it would reject an otherwise-valid resume), and
                 continue to rely on ``shuffle_seed``/``num_splits`` alone as before.
                 Packed checkpoints pin ``pack_sequences``, ``eos_id``, ``pad_id``,
        -        ``blocks_per_epoch``, and ``epoch``.
        +        ``blocks_per_epoch``, and ``epoch``. Checkpoints from a ``block_size``
        +        dataset pin ``shuffle``, ``block_size``, ``max_shuffle_distance`` and
        +        ``reshuffle_blocks_per_epoch``, and are rejected by a 1-phase dataset
        +        and vice versa.
                 """
                 if state["num_splits"] != self._num_splits:
                     raise ValueError(
        @@ -1765,6 +2624,11 @@ class StreamingDataset(IterableDataset):
                         f"current dataset has {self._shuffle_seed}"
                     )
                 checkpoint_fingerprint = state.get("perm_fingerprint")
        +        if checkpoint_fingerprint is not None and self._perm_table is None:
        +            raise ValueError(
        +                "permutation mismatch: the checkpoint records a split_strategy "
        +                "fingerprint, but this block_size dataset has no permutation table"
        +            )
                 if (
                     checkpoint_fingerprint is not None
                     and checkpoint_fingerprint != self._perm_fingerprint
        @@ -1777,6 +2641,7 @@ class StreamingDataset(IterableDataset):
                         "Resuming would apply saved per-split positions to the wrong "
                         "rows."
                     )
        +        self._check_two_phase_checkpoint_config(state, "checkpoint")
                 self._consumer_checkpoint_requires_uniform = False
         
                 if "pack_buffers" in state or self._pack_sequences is not None:
        @@ -1890,6 +2755,13 @@ class StreamingDataset(IterableDataset):
                 for state in states[1:]:
                     if ("pack_buffers" in state) != packed:
                         raise ValueError("cannot merge packed and unpacked state dicts")
        +            # Absent on purpose in 1-phase states, so compare presence too.
        +            for key in _TWO_PHASE_CHECKPOINT_KEYS:
        +                if state.get(key) != first.get(key):
        +                    raise ValueError(
        +                        f"{key} mismatch across state dicts: "
        +                        f"{state.get(key)} != {first.get(key)}"
        +                    )
                     for key in config_keys:
                         if key not in state:
                             continue
        @@ -1999,6 +2871,14 @@ class StreamingDataLoader(DataLoader):
             because the custom iterator cannot provide the exact per-yield checkpoint
             snapshots required by this loader.
         
        +    When ``num_workers > 0`` and ``multiprocessing_context`` is omitted or
        +    ``None``, workers default to the ``forkserver`` start method when the
        +    platform provides it, and to ``spawn`` otherwise. Explicit start-method
        +    names and context objects are used unchanged. With ``num_workers == 0``,
        +    no context is selected, leaving PyTorch's single-process behavior intact.
        +    Callbacks and worker state must be picklable under the selected start
        +    method, following PyTorch's DataLoader rules.
        +
             Examples
             --------
             >>> # dataset = StreamingDataset(table, num_splits=2)
        @@ -2028,6 +2908,10 @@ class StreamingDataLoader(DataLoader):
                     )
                 self._streaming_dataset = dataset
                 super().__init__(_StreamingDatasetAdapter(dataset), *args, **kwargs)
        +        # Fill the default only after DataLoader has handled an explicit context;
        +        # num_workers=0 keeps whatever PyTorch decided.
        +        if self.num_workers > 0 and self.multiprocessing_context is None:
        +            self.multiprocessing_context = _default_worker_start_method()
                 if self.drop_last:
                     raise ValueError(
                         "StreamingDataLoader does not support drop_last=True because "
        diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py
        index c3d5cb41a..da55fc610 100644
        --- a/python/python/lancedb/table.py
        +++ b/python/python/lancedb/table.py
        @@ -35,19 +35,24 @@ from urllib.parse import urlparse
         from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable
         
         from . import __version__
        -from ._lancedb import _parse_field_path
        +from ._lancedb import FunctionColumnStatus, _parse_field_path
         from ._blob import (
             BlobFile,
             _normalize_blob_descriptor,
             _normalize_blob_row_ids,
        +    _validate_blob_buffer_size,
             _wrap_blob_files,
             strip_auto_row_ids,
             validate_blob_mode,
         )
         from .types import BlobMode
        -from lancedb.arrow import peek_reader
        +from lancedb.arrow import AsyncRecordBatchReader, peek_reader
        +from lancedb.sql import QueryParameters, to_parameter_batch
         from lancedb.background_loop import LOOP, embedding_executor
        +from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
         from lancedb.job import AsyncJob, Job, _typed_job
        +from lancedb.compaction import CompactionResult
        +from lancedb.cleanup import CleanupPlan, CleanupResult, _validate_min_age_seconds
         from .dependencies import (
             _check_for_hugging_face,
             _check_for_lance,
        @@ -75,6 +80,9 @@ from .index import (
             LabelList,
             Fm,
             NGram,
        +    ZoneMap,
        +    RTree,
        +    ScalarPlugin,
             HnswPq,
             HnswSq,
             HnswFlat,
        @@ -82,12 +90,17 @@ from .index import (
         )
         from .expr import Expr
         from .functions import (
        +    FunctionErrors,
        +    AsyncFunctionErrors,
        +    FunctionProvenance,
        +    FunctionRetryPolicy,
             FunctionApplication,
             RefreshColumnResult as RefreshColumnJobResult,
         )
         from .merge import LanceMergeInsertBuilder
         from .pydantic import LanceModel, model_to_dict
         from .query import (
        +    FullTextOperator,
             AnalyzePlanDistributedMetrics,
             AsyncFTSQuery,
             AsyncHybridQuery,
        @@ -120,6 +133,7 @@ from .schema import (
             row_addressable_blob_v2_paths,
             schema_has_blob_field,
         )
        +from .resources import _resource_options
         
         
         def _should_push_down_query_table(
        @@ -132,8 +146,20 @@ def _requires_local_namespace_execution(query: Query) -> bool:
             # The namespace QueryTable request does not support these query options.
             return (
                 query.take_offsets is not None
        +        or query.take_row_ids is not None
                 or query.search_effort is not None
                 or query.approx_mode is not None
        +        # The namespace QueryTable request has no order_by field. Pushing a
        +        # nonempty ordering down would drop it and return the wrong top-K rows.
        +        or bool(query.order_by)
        +        # An ordered scan is a local manifest-order guarantee. The request has
        +        # no scan-order field, so run it locally where storage is available.
        +        or query.scan_in_order is True
        +        or (
        +            query.full_text_query is not None
        +            and query.fast_search is True
        +            and query.vector is None
        +        )
             )
         
         
        @@ -164,6 +190,36 @@ def _validate_index_accelerator(accelerator: Any) -> None:
                 raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err
         
         
        +def _create_accelerated_index(dataset, *, exist_ok=False, name=None, **options):
        +    if exist_ok:
        +        parts = _parse_field_path(options["column"])
        +        default_name = ".".join(parts)
        +        if any("." in part for part in parts):
        +            default_name = ".".join(
        +                "`" + part.replace("`", "``") + "`"
        +                if any(
        +                    not character.isalnum() and character != "_" for character in part
        +                )
        +                else part
        +                for part in parts
        +            )
        +        name = name or f"{default_name}_idx"
        +        dataset.checkout_latest()
        +        if any(index["name"] == name for index in dataset.list_indices()):
        +            return
        +        options["replace"] = False
        +        options["name"] = name
        +    _validate_index_accelerator(options.get("accelerator"))
        +    try:
        +        dataset.create_index(**options)
        +    except Exception:
        +        if exist_ok:
        +            dataset.checkout_latest()
        +            if any(index["name"] == name for index in dataset.list_indices()):
        +                return
        +        raise
        +
        +
         def _polars_predicate_pushdown_barrier(frame: Any) -> Any:
             """Return a Polars frame unchanged while blocking predicate pushdown."""
             return frame
        @@ -252,7 +308,7 @@ def _maybe_add_fts_error_note(
         
         
         if TYPE_CHECKING:
        -    from .db import LanceDBConnection
        +    from .db import DBConnection, LanceDBConnection
             from ._lancedb import (
                 Table as LanceDBTable,
                 OptimizeStats,
        @@ -260,7 +316,6 @@ if TYPE_CHECKING:
                 CompactionStats,
                 Tag,
                 AddColumnsResult,
        -        FunctionErrors,
                 RefreshColumnResult,
                 AddResult,
                 AlterColumnsResult,
        @@ -298,6 +353,9 @@ IndexConfigType = Union[
             LabelList,
             Fm,
             NGram,
        +    ZoneMap,
        +    RTree,
        +    ScalarPlugin,
             FTS,
         ]
         
        @@ -305,7 +363,12 @@ IndexConfigType = Union[
         class CompactionOptions(TypedDict, total=False):
             """Options that control file compaction during table optimization.
         
        -    Unspecified options use Lance's defaults.
        +    Unspecified options use Lance's defaults for local tables. Remote tables
        +    forward ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``,
        +    and ``batch_size`` as per-job SQL options; other non-default settings are
        +    unsupported. Omitted remote options inherit table tuning, then deployment/built-in
        +    defaults. The server must support these SQL options. These settings do not
        +    change table policy.
         
             Compaction planning is row based. Lowering ``target_rows_per_fragment``
             based on the expected row size can bound later compaction passes once
        @@ -351,7 +414,10 @@ class CompactionOptions(TypedDict, total=False):
             """Number of rows per input scan batch."""
         
             io_buffer_size: Optional[int]
        -    """Maximum number of bytes queued in the input scan I/O buffer."""
        +    """Input scan I/O read-ahead budget in bytes.
        +
        +    Zero disables byte-based I/O backpressure.
        +    """
         
             defer_index_remap: bool
             """Whether to defer index remapping during compaction (default: False)."""
        @@ -1101,7 +1167,14 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field:
                     if not any(child.name in ("data", "uri") for child in source_type):
                         raise ValueError(
                             f"blob struct input for column '{field.name}' must contain "
        -                    "a 'data' or 'uri' child"
        +                    "a 'data' or 'uri' child. A blob query returns an SDK "
        +                    "descriptor in this shape, and a descriptor is not payload "
        +                    "bytes. Use blob_mode='bytes' to materialize payloads, or "
        +                    "inspect descriptors with blob_mode='descriptions'. To copy "
        +                    "payloads, select row IDs with with_row_id(True), then call "
        +                    "table.fetch_blobs(column, row_ids) or "
        +                    "table.fetch_blob_files(column, row_ids). Keep the source "
        +                    "unchanged between selection and fetching."
                         )
                 elif not _can_coerce_to_blob(source_type) and not isinstance(
                     source_type, pa.ExtensionType
        @@ -1528,6 +1601,63 @@ class Table(ABC):
                 """The branch this table handle is scoped to, or ``None`` for ``main``."""
                 raise NotImplementedError("current_branch is not supported for this table type")
         
        +    def delta(
        +        self,
        +        from_version: int | str,
        +        to_version: Optional[int | str] = None,
        +    ) -> "TableDelta":
        +        """Compare two persisted versions of this table on its current branch.
        +
        +        ``from_version`` is exclusive and ``to_version`` is inclusive. Both
        +        accept a version number (starting at 1) or a tag on the current branch.
        +        Omitting ``to_version`` uses the version this handle currently sees,
        +        including a time-travel checkout. Endpoints are resolved once when this
        +        method is called, so moving a tag or advancing the table later does not
        +        change the delta, and this table's checkout state is left untouched.
        +
        +        The returned [TableDelta][lancedb.table.TableDelta] streams inserted,
        +        updated, upserted, and deleted rows. Those row-level readers require
        +        stable row ids at both endpoints; create the table with
        +        ``storage_options={"new_table_enable_stable_row_ids": "true"}`` to
        +        enable them. ``list_transactions()`` works without stable row ids.
        +        Equal valid versions produce empty readers with the same schemas.
        +
        +        Reversed ranges, version 0, missing versions or tags, and tags from a
        +        different branch are rejected. A row-level range that contains a
        +        ``Restore``, or whose transaction history is incomplete, is rejected
        +        because the restored snapshot can retain older row-version metadata that
        +        the delta readers would omit; recompute the checkpoint with a full
        +        rescan and reinitialize it at the end version. Remote tables raise
        +        ``NotImplementedError``.
        +
        +        Parameters
        +        ----------
        +        from_version: int | str
        +            The version or tag to compare from (exclusive).
        +        to_version: int | str, optional
        +            The version or tag to compare to (inclusive). Defaults to the
        +            currently visible version.
        +
        +        Examples
        +        --------
        +        >>> import lancedb
        +        >>> db = lancedb.connect("memory://")
        +        >>> table = db.create_table(
        +        ...     "delta_example",
        +        ...     [{"id": 1}, {"id": 2}],
        +        ...     storage_options={"new_table_enable_stable_row_ids": "true"},
        +        ... )
        +        >>> table.tags.create("baseline", table.version)
        +        >>> _ = table.add([{"id": 3}])
        +        >>> delta = table.delta("baseline")
        +        >>> inserted = delta.inserted_rows().read_all()
        +        >>> inserted["id"].to_pylist()
        +        [3]
        +        >>> [transaction["operation"] for transaction in delta.list_transactions()]
        +        ['Append']
        +        """
        +        raise NotImplementedError("delta is not supported for this table type")
        +
             def __len__(self) -> int:
                 """The number of rows in this Table"""
                 return self.count_rows(None)
        @@ -1577,8 +1707,8 @@ class Table(ABC):
                 blob_mode: str, default "lazy"
                     ``"lazy"`` returns blob v2 descriptors that carry the row id
                     ``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
        -            ``"bytes"`` returns payload bytes and raises for legacy blob columns
        -            and blobs inside lists.
        +            ``"bytes"`` returns payload bytes for supported row-addressable blob
        +            columns and raises for blobs inside lists.
         
                 Returns
                 -------
        @@ -1821,6 +1951,7 @@ class Table(ABC):
                 replace: bool = ...,
                 wait_timeout: Optional[timedelta] = ...,
                 name: Optional[str] = ...,
        +        exist_ok: bool = ...,
                 train: bool = ...,
             ) -> None: ...
         
        @@ -1846,6 +1977,7 @@ class Table(ABC):
                 *,
                 wait_timeout: Optional[timedelta] = ...,
                 name: Optional[str] = ...,
        +        exist_ok: bool = ...,
                 train: bool = ...,
                 target_partition_size: Optional[int] = ...,
             ) -> None: ...
        @@ -1877,6 +2009,7 @@ class Table(ABC):
                 config: Optional[IndexConfigType] = None,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
                 train: bool = True,
                 target_partition_size: Optional[int] = None,
             ):
        @@ -1897,9 +2030,12 @@ class Table(ABC):
                 config : IndexConfigType, optional
                     The index configuration object. If provided, uses the new unified API.
                     Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
        -            BTree, Bitmap, LabelList, Fm, NGram, FTS.
        +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
                 replace : bool, default True
                     Whether to replace an existing index on this column.
        +        exist_ok : bool, default False
        +            Preserve the existing index with the requested or derived name.
        +            Takes precedence over replace and keeps its definition and build.
                 wait_timeout : timedelta, optional
                     LanceDB Enterprise only: how long to wait for the index build to finish.
                     If not set, the call returns once the build is scheduled.
        @@ -1947,6 +2083,106 @@ class Table(ABC):
                 """
                 raise NotImplementedError("create_index is not supported for this table type")
         
        +    def prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> None:
        +        """Submit remote data prewarm and return after acceptance.
        +
        +        Omitted or empty ``columns`` warm all fields. ``filter`` is a single
        +        SQL predicate for conservative metadata pruning; ``concurrency`` is
        +        a positive per-executor integer, or omitted for the server default.
        +        The table handle supplies the namespace and branch. Requires a
        +        compatible SQL PREWARM server and Flight SQL connectivity.
        +
        +        The operation continues in the background. Use
        +        [prewarm_data_async][lancedb.table.Table.prewarm_data_async] to retain
        +        the job handle and wait for completion.
        +
        +        Examples
        +        --------
        +        >>> table.prewarm_data(  # doctest: +SKIP
        +        ...     ["payload"], filter="quality > 0.7", concurrency=4)
        +        """
        +        self.prewarm_data_async(
        +            columns, filter=filter, concurrency=concurrency, parameters=parameters
        +        )
        +
        +    def explain_prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> PrewarmDataPlan:
        +        """Preview data prewarm without creating a warming job.
        +
        +        Accepts the same columns, filter, parameters, and concurrency as
        +        ``prewarm_data_async`` and uses the table handle's namespace and branch.
        +        Requires LanceDB Enterprise with structured SQL previews, table Select,
        +        and database/namespace Usage. Historical-version and Embedded handles
        +        are unsupported.
        +
        +        Returns the source version, readable plan, and conservative pruning summary.
        +        Unknown metrics remain None; selected ranges are not exact matching rows.
        +        The preview reads metadata. A later submission plans its own snapshot.
        +
        +        Examples
        +        --------
        +        >>> plan = table.explain_prewarm_data(  # doctest: +SKIP
        +        ...     ["video"], filter="quality > $minimum", parameters={"minimum": 0.7})
        +        >>> print(plan.pruning.selected_fragments)  # doctest: +SKIP
        +        """
        +        raise NotImplementedError(
        +            "data prewarm previews are only supported on remote tables"
        +        )
        +
        +    def prewarm_data_async(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> Job[PrewarmDataResult]:
        +        """Submit a remote data-cache prewarm and return its durable job.
        +
        +        Requires a compatible SQL PREWARM server and Flight SQL connectivity.
        +        The table handle supplies the branch and namespace. ``columns`` uses
        +        Lance field paths; an omitted/empty list warms all columns. ``filter``
        +        is one SQL predicate for conservative metadata pruning, not a row scan.
        +        ``parameters`` binds ``$1``/``$name`` values using a sequence, mapping,
        +        or one-row Arrow batch/table. Values are sent separately from SQL.
        +        ``concurrency`` is a positive per-executor integer. Historical-version
        +        handles are unsupported; call ``checkout_latest()`` first.
        +
        +        Submission requires table Select and database/namespace Usage under
        +        Standard authorization. Status/wait use the generic HTTP job API;
        +        events and cancellation have their own privileges. Unsupported servers
        +        are not retried through REST or with settings removed.
        +
        +        Returns once accepted. ``job.wait()`` waits for warming to finish and
        +        returns [PrewarmDataResult][lancedb.prewarm.PrewarmDataResult].
        +        Save ``job.id()`` to resume with ``db.open_job(id)``. A wait timeout does
        +        not cancel the operation. After ``job.checkout_latest()``,
        +        ``job.spec()["table_version"]`` identifies the pinned source version.
        +
        +        Examples
        +        --------
        +        >>> job = table.prewarm_data_async(  # doctest: +SKIP
        +        ...     ["video"], filter="quality > $min", parameters={"min": 0.7},
        +        ...     concurrency=4)
        +        >>> job.wait()  # doctest: +SKIP
        +        """
        +        raise NotImplementedError(
        +            "data prewarm jobs are only supported on remote tables"
        +        )
        +
             def create_index_async(
                 self,
                 column: str,
        @@ -1955,6 +2191,7 @@ class Table(ABC):
                 replace: Optional[bool] = None,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
                 train: bool = True,
             ) -> Job:
                 """Create an index, returning a handle to the indexing job.
        @@ -1985,8 +2222,16 @@ class Table(ABC):
             def update_table_overrides(self, **overrides: Any) -> dict[str, Any]:
                 """Merge Enterprise table overrides into the current table overrides.
         
        -        Only fields supplied in ``overrides`` are changed; unrelated existing
        -        overrides are preserved by the remote service update flow.
        +        Fetches the current overrides, recursively merges nested objects locally,
        +        then sends the complete replacement using REST PUT. Other values replace
        +        existing values; unrelated fields from the read snapshot are preserved.
        +        This read-modify-write is not atomic: concurrent edits can be overwritten,
        +        even to unrelated fields. Coordinate writers when concurrent edits must
        +        be preserved. An empty update only reads and returns the current overrides.
        +
        +        Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides
        +        object without merging. Use ``reset_table_overrides()`` to clear all
        +        overrides. Supported only on remote Enterprise tables.
                 """
                 raise NotImplementedError
         
        @@ -2047,6 +2292,7 @@ class Table(ABC):
                 index_type: ScalarIndexType = "BTREE",
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
             ):
                 """Create a scalar index on a column.
         
        @@ -2131,6 +2377,7 @@ class Table(ABC):
                 document_granularity: DocumentGranularity = DocumentGranularity.ROW,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
             ):
                 """Create a full-text search index on the table.
         
        @@ -2243,6 +2490,7 @@ class Table(ABC):
                 progress: Optional[Union[bool, Callable, Any]] = None,
                 write_parallelism: Optional[int] = None,
                 allow_external_blob_outside_bases: bool = False,
        +        retries: Optional[int] = None,
             ) -> AddResult:
                 """Add more data to the [Table][lancedb.table.Table].
         
        @@ -2303,6 +2551,10 @@ class Table(ABC):
                     Store blob URIs that sit outside registered blob bases. The row
                     keeps a reference, so the object has to stay readable. Local
                     tables only.
        +        retries: int, optional
        +            Override the remote retry budget for this call (0 to 255). Zero
        +            disables retries, including multipart parts. Ambiguous commits are
        +            never replayed. Ignored by LanceDB Embedded.
         
                 Returns
                 -------
        @@ -2386,6 +2638,8 @@ class Table(ABC):
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
                 fast_search: Optional[bool] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> LanceQueryBuilder:
                 """Create a search query to find the nearest neighbors
                 of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
        @@ -2449,6 +2703,10 @@ class Table(ABC):
                     - If `query` is a string, then the query type is "vector" if the
                     table has embedding functions else the query type is "fts"
         
        +        operator: "AND" or "OR", optional
        +            Combine terms in a string full-text query; the default is OR.
        +            Use ``query_type="fts"`` when the table also has embeddings.
        +
                 Returns
                 -------
                 LanceQueryBuilder
        @@ -2466,7 +2724,11 @@ class Table(ABC):
         
             @abstractmethod
             def take_offsets(
        -        self, offsets: list[int], *, with_row_id: bool = False
        +        self,
        +        offsets: list[int],
        +        *,
        +        with_row_id: bool = False,
        +        preserve_order: bool = False,
             ) -> LanceTakeQueryBuilder:
                 """
                 Take a list of offsets from the table.
        @@ -2478,9 +2740,13 @@ class Table(ABC):
                 Offsets are mostly useful for sampling as the set of all valid offsets is easily
                 known in advance to be [0, len(table)).
         
        -        No guarantees are made regarding the order in which results are returned.
        -        Repeated offsets produce repeated rows, which makes this method suitable for
        -        sampling with replacement.
        +        By default, no guarantees are made regarding the order in which results
        +        are returned. Repeated offsets produce repeated rows, which makes this
        +        method suitable for sampling with replacement. Set ``preserve_order=True``
        +        to return found rows in input order, including repeated offsets. Missing
        +        non-negative offsets are omitted. Negative offsets are rejected and are
        +        not Python-style relative indices. ``preserve_order`` cannot be combined
        +        with an explicit ``order_by``.
         
                 Parameters
                 ----------
        @@ -2488,6 +2754,10 @@ class Table(ABC):
                     The offsets to take.
                 with_row_id: bool, default False
                     If True, include the "_rowid" column in the results.
        +        preserve_order: bool, default False
        +            If True, return found rows in input order. Rust take queries apply
        +            limit/offset after restoration; Python take builders and Query
        +            conversion do not expose pagination.
         
                 Returns
                 -------
        @@ -2556,9 +2826,8 @@ class Table(ABC):
                 Row ids are not stable and are relative to the current version of the table.
                 They can change due to compaction and updates.
         
        -        No guarantees are made regarding the order in which results are returned.  If
        -        you desire an output order that matches the order of the given ids, you will
        -        need to add the row id column to the output and align it yourself.
        +        Results follow the requested row-id order. Repeated IDs produce repeated
        +        rows; missing or deleted IDs are omitted. This also applies to remote tables.
         
                 Unlike offsets, row ids are not 0-indexed and no assumptions should be made
                 about the possible range of row ids.  In order to use this method you must
        @@ -2609,12 +2878,32 @@ class Table(ABC):
                 One missing or deleted row ID rejects the entire batch; no partial
                 results are returned.
         
        +        A query result table that carries snapshot metadata keeps the snapshot
        +        that produced it on LanceDB Enterprise. A query result without that
        +        metadata, including a legacy query response, and a plain list are read
        +        from the table's current snapshot; keep the source unchanged between
        +        selection and fetching. Partial snapshot metadata is rejected. Row
        +        positions are not row IDs: to read by position, call
        +        ``table.take_offsets(offsets, with_row_id=True)`` first and pass the
        +        resulting ``_rowid`` values.
        +
        +        On Enterprise clusters that enable direct Blob reads, large values and
        +        ranges may be fetched from short-lived object-store URLs. The client then
        +        needs network access to the object-store endpoint, including private
        +        endpoint routing, DNS, TLS trust and egress rules, in addition to the
        +        LanceDB endpoint. Small reads stay on the LanceDB proxy.
                 Blobs inside lists cannot be fetched by row id yet.
         
                 LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob
                 bytes. The client splits requests automatically and reads an individual
                 larger blob through the Range route. This method still materializes all
                 bytes in memory; for large values use :meth:`fetch_blob_files`.
        +
        +        The returned Arrow ``large_binary`` array contains payload bytes, not
        +        SQL/query descriptor dictionaries. Use ``.to_pylist()`` to obtain
        +        Python ``bytes`` or ``None`` values for copying into a blob column.
        +        Select row IDs with ``search().with_row_id(True)`` first. Selection and
        +        fetching are separate requests: keep the source unchanged between them.
                 """
         
             @abstractmethod
        @@ -2637,9 +2926,18 @@ class Table(ABC):
                 One missing or deleted row ID rejects the entire batch; no partial
                 results are returned.
         
        +        On Enterprise clusters that enable direct Blob reads, large values and
        +        ranges may be fetched from short-lived object-store URLs. The client then
        +        needs network access to the object-store endpoint, including private
        +        endpoint routing, DNS, TLS trust and egress rules, in addition to the
        +        LanceDB endpoint. Small reads stay on the LanceDB proxy.
                 Row IDs can be obtained from a query with ``with_row_id(True)``.
        -        LanceDB Enterprise reads the requested ranges through version-pinned blob
        -        handles using HTTP byte-range requests.
        +        LanceDB Enterprise uses the batched endpoint when the server advertises
        +        support, partitioning at 1024 ranges and 64 MiB, including individual
        +        larger ranges. Older servers use descriptor queries and BlobFile range
        +        reads. Both protocols read one exact branch and version without changing
        +        the table's checkout. Errors from an advertised endpoint propagate without
        +        switching protocols. The final output occupies memory.
                 """
         
             @abstractmethod
        @@ -2647,6 +2945,8 @@ class Table(ABC):
                 self,
                 column: str,
                 row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
        +        *,
        +        buffer_size: Optional[int] = None,
             ) -> "list[Optional[BlobFile]]":
                 """Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles.
         
        @@ -2656,16 +2956,37 @@ class Table(ABC):
                 ``pyarrow.Table`` carrying row identity via ``_rowid`` or a
                 ``_lance_row_id`` field on the blob descriptor. Null blob values return
                 ``None``. LanceDB Enterprise requires server version 0.5.0 or newer.
        +        ``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB).
        +        Set it to 0 for sparse reads. Explicit range reads bypass this buffer.
         
        +        On Enterprise clusters that enable direct Blob reads, large values and
        +        ranges may be fetched from short-lived object-store URLs. The client then
        +        needs network access to the object-store endpoint, including private
        +        endpoint routing, DNS, TLS trust and egress rules, in addition to the
        +        LanceDB endpoint. Small reads stay on the LanceDB proxy.
                 ``_rowid`` values stay valid after compaction when the table has stable
                 row ids.
                 One missing or deleted row ID rejects the entire batch; no partial
                 handles are returned.
        +
        +        A query result table that carries snapshot metadata keeps the snapshot
        +        that produced it on LanceDB Enterprise, so every returned handle reads
        +        that snapshot. Metadata-free query results, including legacy server
        +        responses, and plain lists are read from the table's current snapshot.
        +        Partial snapshot metadata is rejected. A snapshot-bound handle fails
        +        explicitly when the serving node cannot echo the query snapshot
        +        identity; the 0.5.0 floor covers the basic remote Blob API but not that
        +        echo. Row positions are not row IDs: call
        +        ``table.take_offsets(offsets, with_row_id=True)`` first and pass the
        +        resulting ``_rowid`` values.
                 """
         
             @abstractmethod
             def open_blob_file(
        -        self, descriptor: Union[dict, pa.StructScalar, None]
        +        self,
        +        descriptor: Union[dict, pa.StructScalar, None],
        +        *,
        +        buffer_size: Optional[int] = None,
             ) -> Optional[BlobFile]:
                 """Open a seekable file from a SQL ``blob_descriptor`` result.
         
        @@ -2674,6 +2995,7 @@ class Table(ABC):
                 not change this table's checkout. Null descriptors return ``None``.
                 Payload bytes load only when the returned handle is read. An external
                 blob with an unspecified size may require a metadata request on opening.
        +        ``buffer_size`` controls sequential read-ahead (default 512 KiB; 0 disables).
         
                 ```python
                 rows = db.execute_query(
        @@ -2684,7 +3006,9 @@ class Table(ABC):
                 ```
                 """
         
        -    def open_blob_files(self, descriptors: Iterable) -> Iterator[Optional[BlobFile]]:
        +    def open_blob_files(
        +        self, descriptors: Iterable, *, buffer_size: Optional[int] = None
        +    ) -> Iterator[Optional[BlobFile]]:
                 """Iterate over lazy files from descriptor dictionaries or Arrow scalars.
         
                 Accepts an Arrow array/chunked array or any iterable. Opens each handle
        @@ -2699,7 +3023,10 @@ class Table(ABC):
                 ```
                 """
                 for descriptor in descriptors:
        -            yield self.open_blob_file(descriptor)
        +            if buffer_size is None:
        +                yield self.open_blob_file(descriptor)
        +            else:
        +                yield self.open_blob_file(descriptor, buffer_size=buffer_size)
         
             @abstractmethod
             def _execute_query(
        @@ -2710,6 +3037,25 @@ class Table(ABC):
                 timeout: Optional[timedelta] = None,
             ) -> pa.RecordBatchReader: ...
         
        +    def _execute_pull_query(
        +        self,
        +        query: Query,
        +        *,
        +        batch_size: Optional[int] = None,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.RecordBatchReader:
        +        """Execute a pull-driven batch query, falling back to the normal path."""
        +        return self._execute_query(query, batch_size=batch_size, timeout=timeout)
        +
        +    def _execute_arrow(
        +        self,
        +        query: Query,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        """Execute a query and collect the whole result eagerly."""
        +        return self._execute_query(query, timeout=timeout).read_all()
        +
             @abstractmethod
             def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: ...
         
        @@ -2731,6 +3077,7 @@ class Table(ABC):
                 new_data: DATA,
                 on_bad_vectors: OnBadVectorsType,
                 fill_value: float,
        +        retries: Optional[int] = None,
             ) -> MergeResult: ...
         
             @abstractmethod
        @@ -2923,6 +3270,65 @@ class Table(ABC):
                 compaction for you automatically.
                 """
         
        +    def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
        +        """Preview version deletion without submitting a job or deleting files.
        +
        +        Uses the same retention, branch and Ownership boundary as cleanup_async.
        +        Estimates exclude auxiliary sweeps and reserve no snapshot for execution.
        +        """
        +        raise NotImplementedError("cleanup previews require LanceDB Enterprise")
        +
        +    def cleanup_async(
        +        self, *, min_age_seconds: Optional[int] = None
        +    ) -> Job[CleanupResult]:
        +        """Submit durable remote version cleanup through SQL VACUUM.
        +
        +        Omitted retention inherits selected table/branch then deployment policy.
        +        Requires Ownership and parent Usage. Local/historical handles are unsupported.
        +        Disable/drain automatic cleanup and prevent other cleanup, tag/branch
        +        publication and restore until completion, including direct storage clients.
        +        The server does not enforce coordination. Cancellation cannot undo deletion
        +        or prove storage I/O stopped. Preview is available without deletion.
        +
        +        Save ``job.id()`` to reopen with ``db.open_job(id)``. Waiting returns
        +        [CleanupResult][lancedb.cleanup.CleanupResult]; timeout leaves work running.
        +        Unknown totals after retry/recovery remain None. Auxiliary sweeps are
        +        best effort and excluded from the version-deletion counts.
        +
        +        >>> job = table.cleanup_async(min_age_seconds=604800)  # doctest: +SKIP
        +        >>> result = job.wait()  # doctest: +SKIP
        +        """
        +        raise NotImplementedError(
        +            "durable cleanup jobs are only supported on remote tables"
        +        )
        +
        +    def compact_async(
        +        self, *, compaction_options: Optional[CompactionOptions] = None
        +    ) -> Job[CompactionResult]:
        +        """Submit remote compaction and return a durable job after acceptance.
        +
        +        Uses SQL OPTIMIZE with the table handle's branch and namespace. Supports
        +        the four per-job settings in
        +        [CompactionOptions][lancedb.table.CompactionOptions].
        +        Requires a compatible remote server, table Ownership and parent Usage.
        +        Local and historical-version handles are unsupported. Existing
        +        ``optimize()`` retains its return-on-submission behavior remotely.
        +
        +        ``job.wait()`` waits for the actual rewrite and returns
        +        [CompactionResult][lancedb.compaction.CompactionResult]. Partial/bounded
        +        runs report uncommitted rows and ``more_work``; unknown file statistics
        +        are None. Servers without a result payload raise an error rather than
        +        returning fabricated zero statistics. Wait timeouts do not cancel work.
        +        Save ``job.id()`` and reopen with ``db.open_job(id)``. Monitoring and
        +        cancellation use generic HTTP job APIs and their existing permissions.
        +
        +        >>> job = table.compact_async(  # doctest: +SKIP
        +        ...     compaction_options={"target_rows_per_fragment": 1000})
        +        >>> result = job.wait()  # doctest: +SKIP
        +        >>> print(result.rows_succeeded)  # doctest: +SKIP
        +        """
        +        raise NotImplementedError("compaction jobs are only supported on remote tables")
        +
             @abstractmethod
             def optimize(
                 self,
        @@ -2942,9 +3348,13 @@ class Table(ABC):
                     are silently skipped there instead of being attempted, so this
                     call returns successfully, with zeroed pruning statistics, once
                     the compaction job has been submitted; it does not wait for that
        -            job to finish. A non-default ``compaction_options`` raises
        -            ``NotImplementedError`` before anything is submitted, since
        -            there is no way yet to forward those settings to the server.
        +            job to finish. Remote compaction supports per-job
        +            ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``,
        +            and ``batch_size``. Omitted fields inherit table tuning, then
        +            deployment/built-in defaults. Other non-default compaction settings raise
        +            ``NotImplementedError`` before submission. The server must support
        +            these SQL options; older-server errors are propagated without
        +            dropping the requested settings.
         
                 Modeled after ``VACUUM`` in PostgreSQL.
         
        @@ -3064,6 +3474,11 @@ class Table(ABC):
                 computed: Dict[str, str] | None = None,
                 auto_refresh_enabled: bool | None = None,
                 auto_refresh_interval_seconds: int | None = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ):
                 """
                 Add new columns with defined values.
        @@ -3080,10 +3495,11 @@ class Table(ABC):
                     new columns with the specified data types. The new columns will
                     be initialized with null values.
         
        -            A mapping with one ``FunctionApplication`` value keeps its scalar
        -            or named-struct result in the named table column. A bare
        -            named-struct application expands its ordered result fields as one
        -            atomic binding; aliases come from ``rename(columns=...)``.
        +            A mapping of column names to ``FunctionApplication`` values declares
        +            all bindings in one schema commit. Each column holds its scalar
        +            or entire named-struct result. A bare named-struct application expands
        +            its ordered result fields as one atomic binding. Set field aliases
        +            with ``rename(columns=...)``.
                     Function columns are supported only in LanceDB
                     Enterprise.
         
        @@ -3132,7 +3548,12 @@ class Table(ABC):
                     When omitted, the server determines when to refresh. Applies to every
                     computed output in this call.
                     Scheduling options require computed or Function columns.
        -
        +        total_cpu_millis: int, optional
        +            Default total CPU budget for manual and automatic Function refreshes.
        +        total_memory_bytes: int, optional
        +            Default total memory budget for these refreshes, in bytes.
        +        total_gpu_count: int, optional
        +            Default total GPU budget across the Function workers.
                 Returns
                 -------
                 AddColumnsResult
        @@ -3157,15 +3578,45 @@ class Table(ABC):
                 >>> table.to_arrow()["score"].to_pylist()
                 [0.25, 0.75]
                 """
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
         
             @abstractmethod
             def refresh_column(
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[Dict[str, int]] = None,
        +        planning_workers: Optional[Dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
                 gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        error_policy: Optional[Literal["fail", "skip"]] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> "RefreshColumnResult":
                 """
                 Fill the rows of a computed column that hold no value yet.
        @@ -3186,19 +3637,97 @@ class Table(ABC):
                 ----------
                 column: str
                     The name of the computed column to fill.
        +        where: str, optional
        +            SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN
        +            ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB
        +            Enterprise only; local refreshes reject this option.
                 batch_size: int, optional
                     Maximum rows per Function call on the remote server. Must be
                     greater than zero. None uses the server default. Has no effect on
                     local expression-backed columns.
        +        max_concurrency: int, optional
        +            Override the registered Function's maximum concurrent user-code
        +            calls for this logical execution. Must be between 1 and
        +            4294967295. None uses the registration default. This is not an
        +            account-wide quota. LanceDB Enterprise only; local refreshes
        +            reject this option.
        +        publication_interval_rows: int, optional
        +            Opt-in publication threshold for completed Function outputs. Must
        +            be greater than zero. None keeps whole-fragment publication. The
        +            actual publication boundary can be larger than this threshold
        +            because it also depends on completed work and Function batching.
        +            LanceDB Enterprise only; local refreshes reject this option.
        +        total_cpu_millis: int, optional
        +            Override the total CPU budget in millicores for this refresh.
        +        total_memory_bytes: int, optional
        +            Override the total memory budget in bytes for this refresh.
        +        supervisor_resources: dict[str, int], optional
        +            CPU, memory, and ephemeral-storage limits for the Function refresh
        +            supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
        +            ``ephemeral_storage_bytes``; all are required and positive.
        +            LanceDB Enterprise only; local refreshes reject it.
        +        planning_workers: dict[str, object], optional
        +            Resources and sizing for the Function refresh planning fleet.
        +            ``resources`` has the same keys as ``supervisor_resources``; the
        +            other keys are ``max_workers``, ``rows_per_worker`` and
        +            ``fragments_per_worker``. LanceDB Enterprise only; local refreshes
        +            reject it.
                 gpu_class: str, optional
                     GPU class for Function workers. Must be a lowercase name of 1-63
                     letters, digits, or hyphens, without a leading or trailing hyphen.
                     None keeps the Function's registered class or the deployment
                     default. LanceDB Enterprise only.
        -        gpu_count: int, optional
        -            Positive aggregate GPU budget for Function workers. None leaves
        -            the server's configured budget unchanged. LanceDB Enterprise
        -            only.
        +        total_gpu_count: int, optional
        +            Nonnegative total GPU budget for Function workers without changing
        +            the other resource limits. Unspecified resources inherit column defaults,
        +            then Function defaults, then deployment defaults. LanceDB Enterprise only.
        +        retry_policy: FunctionRetryPolicy, optional
        +            Override retries of failed user-code calls. Only use when repeating
        +            partial work is safe. Set max_attempts=1 to disable retries.
        +            Enterprise Functions only; local refreshes reject this option.
        +        error_policy: {"fail", "skip"}, optional
        +            Action after failure or retry exhaustion. Skip records the error
        +            and attempt count, subject to the server's failure limits.
        +            Workflow version 1 servers default to skip with a 5% failure ceiling
        +            and publish successful output before reporting a threshold failure.
        +            Older deployments retain their existing defaults.
        +        max_failed_fraction: float, optional
        +            Under a skip policy, fail the job once more than this share of
        +            rows (0 to 1) has failed. LanceDB Enterprise only.
        +        max_failed_rows: int, optional
        +            Under a skip policy, fail the job once more than this many rows
        +            have failed. LanceDB Enterprise only.
        +        row_timeout_seconds: float, optional
        +            Deadline for one Function call. LanceDB Enterprise only.
        +        init_timeout_seconds: float, optional
        +            Deadline for Function initialization. LanceDB Enterprise only.
        +        num_workers: int, optional
        +            Worker count for an expression column; registered Function
        +            columns reject it and set the corresponding ``total_*`` options. LanceDB
        +            Enterprise only.
        +        max_job_attempts: int, optional
        +            Total automatic Function refresh attempts, including the initial job.
        +            Set to 1 to disable automatic job recovery.
        +        max_executor_processes_per_worker: int, optional
        +            Cap on executor processes per Function worker. LanceDB
        +            Enterprise only.
        +        retry_errors: bool, default False
        +            Select current failed rows on the server. Cannot be combined with
        +            ``where``. Requires Enterprise workflow version 1 or later.
        +        retry_job_id: str, optional
        +            Restrict a failed-row retry to errors recorded by this job.
        +        retry_error_type: str, optional
        +            Restrict a failed-row retry to this exception class.
        +        include_quarantined: bool, default False
        +            Explicitly release and include quarantined rows in a failed-row retry.
        +        function_version: str, optional
        +            Atomically rebind this column's Function to the specified immutable
        +            version. Requires Enterprise workflow version 1 or later.
        +        recompute: {"failed", "all", "none"}, optional
        +            Which rows to recompute during an upgrade. Requires
        +            ``function_version``; the default is ``all``. ``failed`` selects
        +            current failures, and ``none`` preserves existing values. Quarantined
        +            rows stay excluded unless explicitly included in a failed-row retry.
         
                 Returns
                 -------
        @@ -3212,9 +3741,32 @@ class Table(ABC):
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[Dict[str, int]] = None,
        +        planning_workers: Optional[Dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
                 gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        error_policy: Optional[Literal["fail", "skip"]] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> Job[RefreshColumnJobResult]:
                 """
                 Like :meth:`refresh_column`, but returns a handle to the refresh job
        @@ -3233,20 +3785,98 @@ class Table(ABC):
                 ----------
                 column: str
                     The name of the computed column to fill.
        +        where: str, optional
        +            SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN
        +            ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB
        +            Enterprise only; local refreshes reject this option.
                 batch_size: int, optional
                     Maximum rows per Function call on the remote server. Must be
                     greater than zero. None uses the server default. Lower this for
                     slow Functions to stay within the executor's per-call deadline.
                     Has no effect on local expression-backed columns.
        +        max_concurrency: int, optional
        +            Override the registered Function's maximum concurrent user-code
        +            calls for this logical execution. Must be between 1 and
        +            4294967295. None uses the registration default. This is not an
        +            account-wide quota. LanceDB Enterprise only; local refreshes
        +            reject this option.
        +        publication_interval_rows: int, optional
        +            Opt-in publication threshold for completed Function outputs. Must
        +            be greater than zero. None keeps whole-fragment publication. The
        +            actual publication boundary can be larger than this threshold
        +            because it also depends on completed work and Function batching.
        +            LanceDB Enterprise only; local refreshes reject this option.
        +        total_cpu_millis: int, optional
        +            Override the total CPU budget in millicores for this refresh.
        +        total_memory_bytes: int, optional
        +            Override the total memory budget in bytes for this refresh.
        +        supervisor_resources: dict[str, int], optional
        +            CPU, memory, and ephemeral-storage limits for the Function refresh
        +            supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
        +            ``ephemeral_storage_bytes``; all are required and positive.
        +            LanceDB Enterprise only; local refreshes reject it.
        +        planning_workers: dict[str, object], optional
        +            Resources and sizing for the Function refresh planning fleet.
        +            ``resources`` has the same keys as ``supervisor_resources``; the
        +            other keys are ``max_workers``, ``rows_per_worker`` and
        +            ``fragments_per_worker``. LanceDB Enterprise only; local refreshes
        +            reject it.
                 gpu_class: str, optional
                     GPU class for Function workers. Must be a lowercase name of 1-63
                     letters, digits, or hyphens, without a leading or trailing hyphen.
                     None keeps the Function's registered class or the deployment
                     default. LanceDB Enterprise only.
        -        gpu_count: int, optional
        -            Positive aggregate GPU budget for Function workers. None leaves
        -            the server's configured budget unchanged. LanceDB Enterprise
        -            only.
        +        total_gpu_count: int, optional
        +            Nonnegative total GPU budget for Function workers without changing
        +            the other resource limits. Unspecified resources inherit column defaults,
        +            then Function defaults, then deployment defaults. LanceDB Enterprise only.
        +        retry_policy: FunctionRetryPolicy, optional
        +            Override retries of failed user-code calls. Only use when repeating
        +            partial work is safe. Set max_attempts=1 to disable retries.
        +            Enterprise Functions only; local refreshes reject this option.
        +        error_policy: {"fail", "skip"}, optional
        +            Action after failure or retry exhaustion. Skip records the error
        +            and attempt count, subject to the server's failure limits.
        +            Workflow version 1 servers default to skip with a 5% failure ceiling
        +            and publish successful output before reporting a threshold failure.
        +            Older deployments retain their existing defaults.
        +        max_failed_fraction: float, optional
        +            Under a skip policy, fail the job once more than this share of
        +            rows (0 to 1) has failed. LanceDB Enterprise only.
        +        max_failed_rows: int, optional
        +            Under a skip policy, fail the job once more than this many rows
        +            have failed. LanceDB Enterprise only.
        +        row_timeout_seconds: float, optional
        +            Deadline for one Function call. LanceDB Enterprise only.
        +        init_timeout_seconds: float, optional
        +            Deadline for Function initialization. LanceDB Enterprise only.
        +        num_workers: int, optional
        +            Worker count for an expression column; registered Function
        +            columns reject it and set the corresponding ``total_*`` options. LanceDB
        +            Enterprise only.
        +        max_job_attempts: int, optional
        +            Total automatic Function refresh attempts, including the initial job.
        +            Set to 1 to disable automatic job recovery.
        +        max_executor_processes_per_worker: int, optional
        +            Cap on executor processes per Function worker. LanceDB
        +            Enterprise only.
        +        retry_errors: bool, default False
        +            Select current failed rows on the server. Cannot be combined with
        +            ``where``. Requires Enterprise workflow version 1 or later.
        +        retry_job_id: str, optional
        +            Restrict a failed-row retry to errors recorded by this job.
        +        retry_error_type: str, optional
        +            Restrict a failed-row retry to this exception class.
        +        include_quarantined: bool, default False
        +            Explicitly release and include quarantined rows in a failed-row retry.
        +        function_version: str, optional
        +            Atomically rebind this column's Function to the specified immutable
        +            version. Requires Enterprise workflow version 1 or later.
        +        recompute: {"failed", "all", "none"}, optional
        +            Which rows to recompute during an upgrade. Requires
        +            ``function_version``; the default is ``all``. ``failed`` selects
        +            current failures, and ``none`` preserves existing values. Quarantined
        +            rows stay excluded unless explicitly included in a failed-row retry.
         
                 Returns
                 -------
        @@ -3269,22 +3899,115 @@ class Table(ABC):
                 'finished'
                 """
         
        +    def resume_refresh(self, job_id: str) -> Job[RefreshColumnJobResult]:
        +        """Resume a failed Function refresh on this table's current branch.
        +
        +        Returns the successor job. Call its ``wait()`` method for the refresh
        +        result. Requires LanceDB Enterprise.
        +        """
        +        raise NotImplementedError(
        +            "resuming a Function refresh requires LanceDB Enterprise"
        +        )
        +
        +    def retry_failed(
        +        self,
        +        column: str,
        +        *,
        +        error_type: Optional[str] = None,
        +        job_id: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        **options: Any,
        +    ) -> Job[RefreshColumnJobResult]:
        +        """Start a job for exactly the current failed rows.
        +
        +        Stable row identities survive compaction. Set ``function_version`` to
        +        upgrade and retry failures atomically. ``include_quarantined=True``
        +        explicitly releases quarantined rows before retrying them.
        +
        +        >>> job = table.retry_failed("sharpness")  # doctest: +SKIP
        +        >>> result = job.wait()  # doctest: +SKIP
        +        """
        +        return self.refresh_column_async(
        +            column,
        +            retry_errors=True,
        +            retry_error_type=error_type,
        +            retry_job_id=job_id,
        +            include_quarantined=include_quarantined,
        +            function_version=function_version,
        +            recompute="failed" if function_version is not None else None,
        +            **options,
        +        )
        +
        +    def upgrade_column(
        +        self,
        +        column: str,
        +        *,
        +        version: str,
        +        recompute: Literal["failed", "all", "none"] = "all",
        +        **options: Any,
        +    ) -> Job[RefreshColumnJobResult]:
        +        """Upgrade a Function binding while keeping its columns available.
        +
        +        ``failed`` recomputes current failures, ``all`` recomputes all live rows,
        +        and ``none`` preserves existing values. New and changed rows use the new
        +        version; ``function_provenance`` identifies each value's producing version.
        +        """
        +        return self.refresh_column_async(
        +            column, function_version=version, recompute=recompute, **options
        +        )
        +
        +    def quarantine_failed(
        +        self,
        +        column: str,
        +        *,
        +        error_type: Optional[str] = None,
        +        job_id: Optional[str] = None,
        +        after_attempts: Optional[int] = None,
        +        quarantined: bool = True,
        +    ) -> int:
        +        """Quarantine current failures, or release them with ``quarantined=False``.
        +
        +        Normal and automatic refreshes skip quarantined rows. ``after_attempts``
        +        restricts the selection to rows with at least that many failed calls.
        +        Returns the number of selected rows. LanceDB Enterprise only.
        +        """
        +        raise NotImplementedError("Function quarantine requires LanceDB Enterprise")
        +
        +    def function_provenance(
        +        self,
        +        column: str,
        +        *,
        +        limit: Optional[int] = None,
        +        version: Optional[int] = None,
        +    ) -> FunctionProvenance:
        +        """Read each returned row's producing Function version and job.
        +
        +        ``version`` selects a table snapshot. Check ``truncated`` before treating
        +        the returned records as a complete snapshot. LanceDB Enterprise only.
        +        """
        +        raise NotImplementedError("Function provenance requires LanceDB Enterprise")
        +
             @abstractmethod
             def function_errors(
                 self,
                 job_id: Optional[str] = None,
                 column: Optional[str] = None,
                 limit: Optional[int] = None,
        +        history: bool = False,
        +        page_token: Optional[str] = None,
             ) -> "FunctionErrors":
                 """
                 The per-row errors Function refreshes recorded on this table.
         
        -        A refresh running under a skip policy records each row it skipped
        -        with the input that failed and the error. This lists those records,
        -        newest job first, plus a summary for any fragment whose per-row
        -        detail was capped. LanceDB Enterprise only; reading errors
        -        needs read access to the table, since a message carries the value
        -        that failed.
        +        A refresh running under a skip policy records each row it skipped.
        +        On servers advertising workflow version 1 or later, the default lists
        +        current unresolved failures, deduplicated by row and Function column,
        +        with attempt counts and first/last failure times. ``history=True``
        +        returns retained observations, including repaired failures. Older servers
        +        keep their legacy listing behavior and reject explicit history requests.
        +        LanceDB Enterprise only; reading errors needs table read access because
        +        messages can include the input that failed.
         
                 Parameters
                 ----------
        @@ -3294,6 +4017,14 @@ class Table(ABC):
                     Only errors on this column.
                 limit: int, optional
                     At most this many records (server default 10000, cap 100000).
        +        history: bool, default False
        +            Include retained historical errors instead of current failures.
        +            Requires Enterprise workflow version 1 or later. Historical records
        +            cannot be used with the current-input ``rows()`` helper.
        +        page_token: str, optional
        +            Empty starts retained history, including repaired rows, for an exact
        +            job_id. Continue with the response's
        +            page_token until it is None, keeping all filters unchanged.
         
                 Returns
                 -------
        @@ -3301,9 +4032,31 @@ class Table(ABC):
                     ``records``, ``fragments`` and ``truncated``, the last saying
                     whether the listing stopped at its limit.
         
        -        Each record identifies its row with ``fragment_id``, ``row_offset``
        -        and the physical ``row_address`` (``(fragment_id << 32) |
        -        row_offset``). To retry the recorded rows, collect the non-null
        +        Each record identifies its row with ``fragment_id``, ``row_offset``,
        +        the physical ``row_address`` (``(fragment_id << 32) |
        +        row_offset``), and, when the table uses stable row IDs, the stable
        +        ``row_id`` read from the refresh's pinned table version. Prefer
        +        ``row_id`` for retries: compaction and rewrite can change the
        +        physical fields, while a stable row ID survives them.
        +
        +        To retry the recorded rows with stable row IDs:
        +
        +        .. code-block:: python
        +
        +            errors = table.function_errors(column="embedding")
        +            row_ids = sorted(
        +                record.row_id
        +                for record in errors.records
        +                if record.row_id is not None
        +            )
        +            if row_ids:
        +                row_id_list = ", ".join(str(row_id) for row_id in row_ids)
        +                database.execute_query(
        +                    f"REFRESH COLUMN embedding ON {table.name} "
        +                    f"WHERE _rowid IN ({row_id_list})"
        +                )
        +
        +        For a table without stable row IDs, collect the non-null physical
                 addresses before the table is compacted or rewritten and run the
                 SQL refresh:
         
        @@ -3318,7 +4071,7 @@ class Table(ABC):
                     if addresses:
                         address_list = ", ".join(str(address) for address in addresses)
                         database.execute_query(
        -                    f"REFRESH COLUMN embedding ON {table.name()} "
        +                    f"REFRESH COLUMN embedding ON {table.name} "
                             f"WHERE _rowaddr IN ({address_list})"
                         )
         
        @@ -3334,6 +4087,36 @@ class Table(ABC):
                 ...     print("listing stopped at the limit")
                 """
         
        +    @abstractmethod
        +    def column_statuses(
        +        self, column: Optional[str] = None
        +    ) -> list[FunctionColumnStatus]:
        +        """Return exact status for Function-backed output columns.
        +
        +        All statuses describe one server table version. ``column=None`` returns
        +        every Function output. This operation is available on LanceDB
        +        Enterprise tables. A table handle pinned to an exact version requests
        +        that version; a latest handle retains the normal read-freshness
        +        behavior.
        +        """
        +
        +    @abstractmethod
        +    def column_status(self, column: str) -> FunctionColumnStatus:
        +        """Return exact status for one Function-backed output column."""
        +
        +    @abstractmethod
        +    def wait_fresh(
        +        self, column: str, timeout: Optional[timedelta] = None
        +    ) -> FunctionColumnStatus:
        +        """Poll until the column has no stale or never-computed rows.
        +
        +        Rows already failed remain visible in the returned status and do not
        +        keep this method waiting. The method never submits or cancels work.
        +        Transport errors and unrecoverable status-evidence errors propagate.
        +        A typed finalization-pending response is retried; arbitrary failure
        +        responses are not.
        +        """
        +
             @abstractmethod
             def alter_columns(self, *alterations: Iterable[Dict[str, str]]):
                 """
        @@ -3469,6 +4252,12 @@ class Table(ABC):
                 out state. To return the table to a normal state use
                 `[Self::checkout_latest]`.
         
        +        For Enterprise tables, a tag must belong to this handle's current branch.
        +        To read a tag on another branch, first obtain that branch's handle with
        +        `table.branches.checkout("branch_name")`, then call `checkout(tag)` on
        +        that handle. A tag on another branch raises an error without changing
        +        the current selection.
        +
                 Parameters
                 ----------
                 version: int | str,
        @@ -3608,7 +4397,10 @@ class LanceTable(Table):
                     namespace_path = []
                 self._conn = connection
                 self._namespace_path = namespace_path
        +        self._storage_options = storage_options
        +        self._index_cache_size = index_cache_size
                 self._location = location  # Store location for use in _dataset_path
        +        self._managed_versioning = managed_versioning
                 self._namespace_client = namespace_client
                 self._pushdown_operations = pushdown_operations or set()
                 # When the connection built the namespace client natively (e.g. an
        @@ -3635,6 +4427,182 @@ class LanceTable(Table):
                     )
                 # Take queries read the pushdown set from the inner table.
                 self._table._pushdown_operations = self._pushdown_operations
        +        # These coordinates live on the Python wrapper: the native table only
        +        # reports its current branch and version, not whether it is pinned.
        +        self._branch = self._table.current_branch()
        +        self._checkout_version: Optional[int] = None
        +
        +    def _pickle_connection_state(self) -> str:
        +        """Serialize the connection, rejecting state a worker cannot recreate."""
        +        connection = self._conn
        +        namespace_client = getattr(connection, "_namespace_client", None)
        +        namespace_impl = getattr(connection, "_namespace_client_impl", None)
        +        if namespace_client is not None and namespace_impl is None:
        +            raise TypeError(
        +                f"Cannot pickle LanceTable {self.name!r} backed by a namespace "
        +                "connection whose custom namespace_client cannot be "
        +                "reconstructed. Connect through connect_namespace(impl, "
        +                "properties) or provide a picklable worker-side namespace "
        +                "connection instead."
        +            )
        +
        +        pickle_state = getattr(connection, "_pickle_state", None)
        +        if pickle_state is not None:
        +            return pickle_state()
        +
        +        session = getattr(connection, "session", None)
        +        if session is not None:
        +            raise TypeError(
        +                "Cannot pickle a LanceTable whose connection was created with a "
        +                "Session; Session objects are not serializable. Create the "
        +                "Session in each worker process instead."
        +            )
        +        return connection.serialize()
        +
        +    def _table_namespace_client(self) -> Optional[Any]:
        +        """The namespace client set on this table rather than its connection."""
        +        namespace_client = self._namespace_client
        +        if namespace_client is getattr(self._conn, "_namespace_client", None):
        +            # The connection rebuilds its own namespace client.
        +            return None
        +        if namespace_client is getattr(self._conn, "_cached_namespace_client", None):
        +            # Local manifest-mode connections cache their namespace client here.
        +            return None
        +        return namespace_client
        +
        +    def _namespace_client_for_pickle(self) -> Optional[Any]:
        +        """Keep a table-level namespace client only when pickle can carry it."""
        +        namespace_client = self._table_namespace_client()
        +        if namespace_client is None:
        +            return None
        +
        +        import pickle
        +
        +        try:
        +            pickle.dumps(namespace_client)
        +        except Exception as error:
        +            raise TypeError(
        +                f"Cannot pickle LanceTable {self.name!r}: its custom "
        +                f"namespace_client ({type(namespace_client).__name__}) is not "
        +                "serializable. Reopen the table in the worker through a "
        +                "picklable namespace connection instead."
        +            ) from error
        +        return namespace_client
        +
        +    @classmethod
        +    def _open_from_pickle_state(
        +        cls, connection: "DBConnection", state: dict[str, Any]
        +    ) -> "LanceTable":
        +        """Reopen a table from the state returned by ``__getstate__``."""
        +        async_connection = getattr(connection, "_conn", None)
        +        if async_connection is None:
        +            async_connection = connection._inner
        +
        +        # Only a table-level explicit client travels in the state. A connection
        +        # namespace client must reopen through its own provider path so caller
        +        # storage options keep their layering; passing the reconstructed client
        +        # here would turn it into an explicit table provider.
        +        namespace_client = state.get("namespace_client")
        +
        +        async_table = LOOP.run(
        +            async_connection.open_table(
        +                state["name"],
        +                namespace_path=state["namespace_path"],
        +                storage_options=state["storage_options"],
        +                index_cache_size=state["index_cache_size"],
        +                location=state["location"],
        +                namespace_client=namespace_client,
        +                managed_versioning=state["managed_versioning"],
        +            )
        +        )
        +        table = cls(
        +            connection,
        +            state["name"],
        +            namespace_path=state["namespace_path"],
        +            storage_options=state["storage_options"],
        +            index_cache_size=state["index_cache_size"],
        +            location=state["location"],
        +            namespace_client=namespace_client,
        +            managed_versioning=state["managed_versioning"],
        +            pushdown_operations=state["pushdown_operations"],
        +            route_pushdown_to_rust=state["route_pushdown_to_rust"],
        +            _async=async_table,
        +        )
        +
        +        version = state["checkout_version"]
        +        if state["branch"] is not None:
        +            table = table.branches.checkout(state["branch"], version)
        +        elif version is not None:
        +            table.checkout(version)
        +        return table
        +
        +    def __getstate__(self) -> dict[str, Any]:
        +        """Return a process-independent state for pickle-based workers."""
        +        if self._conn.uri.startswith("memory://"):
        +            # In-memory databases cannot be reopened by name in another process.
        +            # Keep the established behavior of exporting the visible table.
        +            return {"kind": "memory", "name": self.name, "data": self.to_arrow()}
        +
        +        return {
        +            "kind": "lance",
        +            "connection_state": self._pickle_connection_state(),
        +            "namespace_client": self._namespace_client_for_pickle(),
        +            **self._reopen_state(),
        +        }
        +
        +    def _reopen_state(self) -> dict[str, Any]:
        +        """Arguments for ``_open_from_pickle_state``, minus the connection."""
        +        # The native handle is authoritative: a tag checkout can move this
        +        # wrapper onto another branch, so never trust the branch captured at
        +        # construction time.
        +        self._branch = self.current_branch()
        +        return {
        +            "name": self.name,
        +            "namespace_path": list(self._namespace_path),
        +            # Only caller-supplied overrides are safe to replay. Namespace-provided
        +            # initial options may contain rotating credentials and must be fetched
        +            # again by the reopened connection's storage-options provider.
        +            "storage_options": self._storage_options,
        +            "index_cache_size": self._index_cache_size,
        +            "location": self._location,
        +            "managed_versioning": self._managed_versioning,
        +            "pushdown_operations": set(self._pushdown_operations),
        +            "route_pushdown_to_rust": self._route_pushdown_to_rust,
        +            "branch": self._branch,
        +            "checkout_version": self._checkout_version,
        +        }
        +
        +    def _private_copy(self) -> "LanceTable":
        +        """A new handle on the same table, branch and checkout, over this
        +        handle's own connection.
        +
        +        ``checkout()`` on the copy leaves this handle untouched. Unlike a
        +        pickle round trip, the connection need not be serializable (for
        +        example, one created with a ``Session``), and an in-memory table keeps
        +        its version history.
        +        """
        +        return type(self)._open_from_pickle_state(
        +            self._conn,
        +            {
        +                **self._reopen_state(),
        +                "namespace_client": self._table_namespace_client(),
        +            },
        +        )
        +
        +    def __setstate__(self, state: dict[str, Any]) -> None:
        +        """Rebuild a table from ``__getstate__`` in the current process."""
        +        if state.get("kind") == "memory":
        +            from . import connect
        +
        +            rebuilt = connect("memory://").create_table(state["name"], state["data"])
        +            self.__dict__.update(rebuilt.__dict__)
        +            return
        +
        +        from . import deserialize_conn
        +
        +        connection = deserialize_conn(state["connection_state"], for_worker=True)
        +        reopened = type(self)._open_from_pickle_state(connection, state)
        +        self.__dict__.update(reopened.__dict__)
         
             @property
             def name(self) -> str:
        @@ -3646,10 +4614,40 @@ class LanceTable(Table):
                 return self._namespace_path
         
             @classmethod
        -    async def from_inner(cls, tbl: LanceDBTable):
        +    async def from_inner(
        +        cls,
        +        tbl: LanceDBTable,
        +        *,
        +        connection: Optional["DBConnection"] = None,
        +        name: Optional[str] = None,
        +        namespace_path: Optional[List[str]] = None,
        +        location: Optional[str] = None,
        +    ):
        +        async_tbl = AsyncTable(tbl)
        +        if connection is not None:
        +            # A table created through a Python connection keeps that
        +            # connection's explicit options. Reconstructing a bare connection
        +            # from the native handle loses namespace, storage, manifest and
        +            # Session state needed by pickle.
        +            return cls(
        +                connection,
        +                name or async_tbl.name,
        +                namespace_path=namespace_path,
        +                storage_options=getattr(connection, "storage_options", None),
        +                location=location,
        +                namespace_client=getattr(connection, "_namespace_client", None),
        +                managed_versioning=getattr(connection, "_managed_versioning", None),
        +                pushdown_operations=getattr(
        +                    connection, "_namespace_client_pushdown_operations", None
        +                ),
        +                route_pushdown_to_rust=getattr(
        +                    connection, "_route_pushdown_to_rust", False
        +                ),
        +                _async=async_tbl,
        +            )
        +
                 from .db import AsyncConnection, LanceDBConnection
         
        -        async_tbl = AsyncTable(tbl)
                 inner_conn = tbl.database()
                 read_consistency_interval = await AsyncConnection(
                     inner_conn
        @@ -3755,21 +4753,42 @@ class LanceTable(Table):
                 -------
                 pa.Schema
                     A PyArrow schema object."""
        -        return LOOP.run(self._table.schema())
        +        schema_sync = getattr(self._table, "_schema_sync", None)
        +        if schema_sync is None:
        +            return LOOP.run(self._table.schema())
        +        return schema_sync()
         
             def list_versions(self) -> List[Dict[str, Any]]:
                 """List all versions of the table"""
                 return LOOP.run(self._table.list_versions())
         
        +    def delta(
        +        self,
        +        from_version: int | str,
        +        to_version: Optional[int | str] = None,
        +    ) -> "TableDelta":
        +        """Compare two versions or tags.
        +
        +        See [Table.delta][lancedb.table.Table.delta].
        +        """
        +        async_delta = LOOP.run(self._table.delta(from_version, to_version))
        +        return TableDelta(async_delta._inner)
        +
             @property
             def version(self) -> int:
                 """Get the current version of the table"""
                 return LOOP.run(self._table.version())
         
             def take_offsets(
        -        self, offsets: list[int], *, with_row_id: bool = False
        +        self,
        +        offsets: list[int],
        +        *,
        +        with_row_id: bool = False,
        +        preserve_order: bool = False,
             ) -> LanceTakeQueryBuilder:
        -        builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
        +        builder = LanceTakeQueryBuilder(
        +            self._table.take_offsets(offsets, preserve_order=preserve_order)
        +        )
                 if with_row_id:
                     builder.with_row_id()
                 return builder
        @@ -3803,13 +4822,20 @@ class LanceTable(Table):
                 self,
                 column: str,
                 row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
        +        *,
        +        buffer_size: Optional[int] = None,
             ) -> "list[Optional[BlobFile]]":
        -        return LOOP.run(self._table.fetch_blob_files(column, row_ids))
        +        return LOOP.run(
        +            self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
        +        )
         
             def open_blob_file(
        -        self, descriptor: Union[dict, pa.StructScalar, None]
        +        self,
        +        descriptor: Union[dict, pa.StructScalar, None],
        +        *,
        +        buffer_size: Optional[int] = None,
             ) -> Optional[BlobFile]:
        -        return LOOP.run(self._table.open_blob_file(descriptor))
        +        return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size))
         
             @property
             def tags(self) -> Tags:
        @@ -3863,21 +4889,36 @@ class LanceTable(Table):
                 """The branch this table handle is scoped to, or ``None`` for ``main``."""
                 return self._table.current_branch()
         
        +    def _pin_current_snapshot(self) -> "LanceTable":
        +        """Return an independent handle pinned to this table's current snapshot."""
        +
        +        async def do_pin():
        +            pinned = await self._table._checkout_current()
        +            return pinned, await pinned.version()
        +
        +        pinned, version = LOOP.run(do_pin())
        +        return self._wrap_branch_handle(pinned, version)
        +
             def _wrap_branch_handle(
                 self, async_table: "AsyncTable", version: Optional[int] = None
             ) -> "LanceTable":
        -        # version is unused locally: the pin already lives on async_table and a
        -        # local handle is not reopened via a serialized connection.
        -        return LanceTable(
        +        table = LanceTable(
                     self._conn,
                     async_table.name,
                     namespace_path=self._namespace_path,
        +            storage_options=self._storage_options,
        +            index_cache_size=self._index_cache_size,
                     namespace_client=self._namespace_client,
        +            managed_versioning=self._managed_versioning,
                     pushdown_operations=self._pushdown_operations,
                     route_pushdown_to_rust=self._route_pushdown_to_rust,
                     location=self._location,
                     _async=async_table,
                 )
        +        # The native handle knows its branch but not whether this wrapper is a
        +        # pinned branch version, so carry that coordinate explicitly.
        +        table._checkout_version = version
        +        return table
         
             def checkout(self, version: Union[int, str]):
                 """Checkout a version of the table. This is an in-place operation.
        @@ -3921,6 +4962,8 @@ class LanceTable(Table):
                 0  [1.1, 0.9]  vector
                 """
                 LOOP.run(self._table.checkout(version))
        +        self._checkout_version = self.version
        +        self._branch = self.current_branch()
         
             def checkout_latest(self):
                 """Checkout the latest version of the table. This is an in-place operation.
        @@ -3929,6 +4972,8 @@ class LanceTable(Table):
                 version of the table.
                 """
                 LOOP.run(self._table.checkout_latest())
        +        self._checkout_version = None
        +        self._branch = self.current_branch()
         
             def restore(self, version: Optional[Union[int, str]] = None):
                 """Restore a version of the table. This is an in-place operation.
        @@ -3977,6 +5022,8 @@ class LanceTable(Table):
                 if version is not None:
                     LOOP.run(self._table.checkout(version))
                 LOOP.run(self._table.restore())
        +        self._checkout_version = None
        +        self._branch = self.current_branch()
         
             def count_rows(self, filter: Optional[str] = None) -> int:
                 return LOOP.run(self._table.count_rows(filter))
        @@ -4021,7 +5068,7 @@ class LanceTable(Table):
                 ):
                     return self.to_arrow().to_pandas(**kwargs)
         
        -        if blob_mode == "bytes" and blob_v2_column_paths(self.schema):
        +        if blob_mode == "bytes" and schema_has_blob_field(self.schema):
                     return self.search().to_pandas(blob_mode=blob_mode, **kwargs)
         
                 return self.to_lance().to_pandas(blob_mode=blob_mode, **kwargs)
        @@ -4034,8 +5081,8 @@ class LanceTable(Table):
                 blob_mode: str, default "lazy"
                     ``"lazy"`` returns blob v2 descriptors that carry the row id
                     ``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
        -            ``"bytes"`` returns payload bytes and raises for legacy blob columns
        -            and blobs inside lists.
        +            ``"bytes"`` returns payload bytes for supported row-addressable blob
        +            columns and raises for blobs inside lists.
         
                 Returns
                 -------
        @@ -4098,6 +5145,7 @@ class LanceTable(Table):
                 replace: bool = ...,
                 wait_timeout: Optional[timedelta] = ...,
                 name: Optional[str] = ...,
        +        exist_ok: bool = ...,
                 train: bool = ...,
             ) -> None: ...
         
        @@ -4123,6 +5171,7 @@ class LanceTable(Table):
                 *,
                 wait_timeout: Optional[timedelta] = ...,
                 name: Optional[str] = ...,
        +        exist_ok: bool = ...,
                 train: bool = ...,
                 target_partition_size: Optional[int] = ...,
             ) -> None: ...
        @@ -4154,6 +5203,7 @@ class LanceTable(Table):
                 config: Optional[IndexConfigType] = None,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
                 train: bool = True,
                 target_partition_size: Optional[int] = None,
             ):
        @@ -4174,9 +5224,12 @@ class LanceTable(Table):
                 config : IndexConfigType, optional
                     The index configuration object. If provided, uses the new unified API.
                     Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
        -            BTree, Bitmap, LabelList, Fm, NGram, FTS.
        +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS.
                 replace : bool, default True
                     Whether to replace an existing index on this column.
        +        exist_ok : bool, default False
        +            Preserve the existing index with the requested or derived name.
        +            Takes precedence over replace and keeps its definition and build.
                 wait_timeout : timedelta, optional
                     Timeout to wait for async indexing to complete.
                 name : str, optional
        @@ -4245,8 +5298,10 @@ class LanceTable(Table):
                     # Handle accelerator through pylance
                     if accelerator is not None:
                         dataset = self.to_lance()
        -                _validate_index_accelerator(accelerator)
        -                dataset.create_index(
        +                _create_accelerated_index(
        +                    dataset,
        +                    exist_ok=exist_ok,
        +                    name=name,
                             column=column,
                             index_type=index_type,
                             metric=metric,
        @@ -4272,7 +5327,6 @@ class LanceTable(Table):
                         if acc is not None:
                             # Dispatch to pylance for GPU acceleration
                             dataset = self.to_lance()
        -                    _validate_index_accelerator(acc)
                             index_type_map = {
                                 "IvfFlat": "IVF_FLAT",
                                 "IvfSq": "IVF_SQ",
        @@ -4289,7 +5343,10 @@ class LanceTable(Table):
                             if num_bits is not None:
                                 quantization_kwargs["num_bits"] = num_bits
         
        -                    dataset.create_index(
        +                    _create_accelerated_index(
        +                        dataset,
        +                        exist_ok=exist_ok,
        +                        name=name,
                                 column=column,
                                 index_type=lance_index_type,
                                 metric=getattr(config, "distance_type", "l2"),
        @@ -4311,6 +5368,7 @@ class LanceTable(Table):
                     self._table.create_index(
                         column,
                         replace=replace,
        +                exist_ok=exist_ok,
                         config=config,
                         wait_timeout=wait_timeout,
                         name=name,
        @@ -4326,6 +5384,7 @@ class LanceTable(Table):
                 replace: Optional[bool] = None,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
                 train: bool = True,
             ) -> Job:
                 """Create an index, returning a handle to the indexing job.
        @@ -4344,6 +5403,7 @@ class LanceTable(Table):
                         self._table.create_index_async(
                             column,
                             replace=replace,
        +                    exist_ok=exist_ok,
                             config=config,
                             wait_timeout=wait_timeout,
                             name=name,
        @@ -4385,7 +5445,14 @@ class LanceTable(Table):
                 """
                 return LOOP.run(self._table.prewarm_index(name))
         
        -    def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
        +    def prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> None:
                 """
                 Prewarm data for the table.
         
        @@ -4394,7 +5461,8 @@ class LanceTable(Table):
                 Currently only supported in LanceDB Enterprise.
         
                 This call initiates prewarming and returns once the request is accepted.
        -        It is idempotent and safe to call from multiple clients concurrently.
        +        Uses SQL PREWARM and requires Flight SQL connectivity. To track the
        +        durable warming job, use ``prewarm_data_async()``.
         
                 This operation has a large upfront cost but can speed up future queries
                 that need to fetch the given columns.  Large columns such as embeddings
        @@ -4405,8 +5473,62 @@ class LanceTable(Table):
                 ----------
                 columns: list of str, optional
                     The columns to prewarm. If None, all columns are prewarmed.
        +        filter: str, optional
        +            A single SQL predicate for conservative metadata pruning.
        +        parameters: sequence, mapping, or one-row Arrow batch/table, optional
        +            Scalar values for ``$1``/``$name`` placeholders in ``filter``.
        +            Values are sent separately from SQL; requires server support.
        +        concurrency: int, optional
        +            Positive per-executor warming concurrency; omitted uses the server default.
        +
        +        Examples
        +        --------
        +        >>> table.prewarm_data(  # doctest: +SKIP
        +        ...     ["payload"], filter="quality > 0.7", concurrency=4)
                 """
        -        return LOOP.run(self._table.prewarm_data(columns))
        +        return LOOP.run(
        +            self._table.prewarm_data(
        +                columns, filter=filter, concurrency=concurrency, parameters=parameters
        +            )
        +        )
        +
        +    def explain_prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> PrewarmDataPlan:
        +        """Preview prewarm without submitting a warming job.
        +
        +        See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data]
        +        for options, permissions, snapshot semantics, and limitations.
        +        """
        +        return LOOP.run(
        +            self._table.explain_prewarm_data(
        +                columns, filter=filter, concurrency=concurrency, parameters=parameters
        +            )
        +        )
        +
        +    def prewarm_data_async(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> Job[PrewarmDataResult]:
        +        return Job(
        +            LOOP.run(
        +                self._table.prewarm_data_async(
        +                    columns,
        +                    filter=filter,
        +                    concurrency=concurrency,
        +                    parameters=parameters,
        +                )
        +            )
        +        )
         
             def wait_for_index(
                 self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
        @@ -4464,6 +5586,7 @@ class LanceTable(Table):
                 index_type: ScalarIndexType = "BTREE",
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
             ):
                 """Create a scalar index on a column.
         
        @@ -4490,6 +5613,7 @@ class LanceTable(Table):
                     self._table.create_index(
                         column,
                         replace=replace,
        +                exist_ok=exist_ok,
                         config=config,
                         wait_timeout=wait_timeout,
                         name=name,
        @@ -4527,6 +5651,7 @@ class LanceTable(Table):
                 document_granularity: DocumentGranularity = DocumentGranularity.ROW,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
             ):
                 """Create a full-text search index on a column.
         
        @@ -4588,6 +5713,7 @@ class LanceTable(Table):
                         self._table.create_index(
                             field_names,
                             replace=replace,
        +                    exist_ok=exist_ok,
                             config=config,
                             name=name,
                             wait_timeout=wait_timeout,
        @@ -4610,6 +5736,7 @@ class LanceTable(Table):
                 progress: Optional[Union[bool, Callable, Any]] = None,
                 write_parallelism: Optional[int] = None,
                 allow_external_blob_outside_bases: bool = False,
        +        retries: Optional[int] = None,
             ) -> AddResult:
                 """Add data to the table.
                 If vector columns are missing and the table
        @@ -4641,6 +5768,10 @@ class LanceTable(Table):
                 allow_external_blob_outside_bases: bool, default False
                     Allow blob URIs outside registered bases. See :meth:`Table.add`.
                     LanceDB Embedded only.
        +        retries: int, optional
        +            Override the remote retry budget for this call (0 to 255). Zero
        +            disables retries, including multipart parts. Ambiguous commits are
        +            never replayed. Ignored by LanceDB Embedded.
         
                 Returns
                 -------
        @@ -4658,6 +5789,7 @@ class LanceTable(Table):
                             progress=progress,
                             write_parallelism=write_parallelism,
                             allow_external_blob_outside_bases=allow_external_blob_outside_bases,
        +                    retries=retries,
                         )
                     )
                 finally:
        @@ -4752,6 +5884,8 @@ class LanceTable(Table):
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
                 fast_search: Optional[bool] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> LanceVectorQueryBuilder: ...
         
             @overload
        @@ -4763,6 +5897,8 @@ class LanceTable(Table):
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
                 fast_search: Optional[bool] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> LanceFtsQueryBuilder: ...
         
             @overload
        @@ -4776,6 +5912,8 @@ class LanceTable(Table):
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
                 fast_search: Optional[bool] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> LanceHybridQueryBuilder: ...
         
             @overload
        @@ -4787,6 +5925,8 @@ class LanceTable(Table):
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
                 fast_search: Optional[bool] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> LanceEmptyQueryBuilder: ...
         
             def search(
        @@ -4799,6 +5939,8 @@ class LanceTable(Table):
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
                 fast_search: Optional[bool] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> LanceQueryBuilder:
                 """Create a search query to find the nearest neighbors
                 of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
        @@ -4859,6 +6001,10 @@ class LanceTable(Table):
                     If None then the search is performed on all indexed columns.
                     For now, only one column can be searched at a time.
         
        +        operator: "AND" or "OR", optional
        +            Combine terms in a string full-text query; the default is OR.
        +            Use ``query_type="fts"`` when the table also has embeddings.
        +
                 Returns
                 -------
                 LanceQueryBuilder
        @@ -4869,8 +6015,16 @@ class LanceTable(Table):
                 """
                 if isinstance(query, FullTextQuery):
                     query_type = "fts"
        +        if (
        +            vector_column_name is None
        +            and query_type != "fts"
        +            and not (query is None and query_type != "hybrid")
        +        ):
        +            schema = self.schema
        +        else:
        +            schema = None
                 vector_column_name = infer_vector_column_name(
        -            schema=self.schema,
        +            schema=schema,
                     query_type=query_type,
                     query=query,
                     vector_column_name=vector_column_name,
        @@ -4884,6 +6038,7 @@ class LanceTable(Table):
                     ordering_field_name=ordering_field_name,
                     fts_columns=fts_columns or [],
                     fast_search=fast_search,
        +            operator=operator,
                 )
         
             @classmethod
        @@ -4907,6 +6062,8 @@ class LanceTable(Table):
                 namespace_client: Optional[Any] = None,
                 pushdown_operations: Optional[set] = None,
                 route_pushdown_to_rust: bool = False,
        +        initial_bases: Optional[List[Any]] = None,
        +        allow_external_blob_outside_bases: bool = False,
             ):
                 """
                 Create a new table.
        @@ -4960,13 +6117,29 @@ class LanceTable(Table):
                 enable_v2_manifest_paths: optional, bool, default False
                     Deprecated.  Set `storage_options` when connecting to the database and set
                     `new_table_enable_v2_manifest_paths` in the options.
        +        initial_bases: list, optional
        +            Storage bases to register in the table's manifest in the same
        +            commit that creates it. Each entry can be a
        +            [BasePath][lancedb.schema.BasePath], a dict with `path`, `name`,
        +            `is_dataset_root`, and `id` keys, or a `lance.DatasetBasePath`.
        +            Blob URIs under a registered base are stored relative to it. When
        +            supplying IDs for multiple bases, use distinct explicit non-zero
        +            IDs; [BasePath][lancedb.schema.BasePath] describes the pinned-Lance
        +            limitation.
        +        allow_external_blob_outside_bases: bool, default False
        +            Store blob URIs that do not fall under a registered base. The row
        +            keeps a reference, so the objects have to stay readable. The
        +            opt-in applies only to the initial data; a later `add()` must
        +            enable it again.
                 """
                 if namespace_path is None:
                     namespace_path = []
                 self = cls.__new__(cls)
                 self._conn = db
                 self._namespace_path = namespace_path
        +        self._index_cache_size = None
                 self._location = location
        +        self._managed_versioning = None
                 self._namespace_client = namespace_client
                 self._pushdown_operations = pushdown_operations or set()
                 self._route_pushdown_to_rust = route_pushdown_to_rust
        @@ -4994,6 +6167,7 @@ class LanceTable(Table):
                         enable_v2_manifest_paths
                     ).lower()
         
        +        self._storage_options = storage_options
                 self._table = LOOP.run(
                     self._conn._conn.create_table(
                         name,
        @@ -5008,8 +6182,12 @@ class LanceTable(Table):
                         storage_options=storage_options,
                         location=location,
                         namespace_client=namespace_client,
        +                initial_bases=initial_bases,
        +                allow_external_blob_outside_bases=allow_external_blob_outside_bases,
                     )
                 )
        +        self._branch = self._table.current_branch()
        +        self._checkout_version = None
                 return self
         
             def delete(self, where: Union[str, Expr]) -> DeleteResult:
        @@ -5113,6 +6291,55 @@ class LanceTable(Table):
         
                 return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
         
        +    def _execute_pull_query(
        +        self,
        +        query: Query,
        +        *,
        +        batch_size: Optional[int] = None,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.RecordBatchReader:
        +        """Execute a plain local scan with one Rust fetch per batch.
        +
        +        The caller has already checked that this is an embedded, non-namespace
        +        plain lazy scan. A query shape that does not map to ``AsyncQuery``
        +        keeps the existing reader path instead of guessing at its semantics.
        +        """
        +        async_query = self._table._sync_query_to_async(query)
        +        async_query._blob_row_id_prepared = query._blob_row_id_prepared
        +        if isinstance(async_query, AsyncQuery):
        +            return async_query._execute_batches_sync(
        +                max_batch_length=batch_size, timeout=timeout
        +            )
        +        return self._execute_query(query, batch_size=batch_size, timeout=timeout)
        +
        +    def _execute_arrow(
        +        self,
        +        query: Query,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        # Keep the Python namespace pushdown path, including its branch rule.
        +        if (
        +            _should_push_down_query_table(
        +                self._namespace_client, self._pushdown_operations
        +            )
        +            and not self._route_pushdown_to_rust
        +            and self.current_branch() is None
        +            and not _requires_local_namespace_execution(query)
        +        ):
        +            return self._execute_query(query, timeout=timeout).read_all()
        +
        +        async_query = self._table._sync_query_to_async(query)
        +        async_query._blob_row_id_prepared = query._blob_row_id_prepared
        +        if (
        +            self._table._inner._is_native()
        +            and self._namespace_client is None
        +            and not self._route_pushdown_to_rust
        +            and isinstance(async_query, (AsyncQuery, AsyncVectorQuery, AsyncFTSQuery))
        +        ):
        +            return async_query._execute_eager_sync(timeout=timeout)
        +        return LOOP.run(async_query._execute_eager(timeout=timeout))
        +
             def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
                 return LOOP.run(self._table._explain_plan(query, verbose))
         
        @@ -5135,9 +6362,10 @@ class LanceTable(Table):
                 new_data: DATA,
                 on_bad_vectors: OnBadVectorsType,
                 fill_value: float,
        +        retries: Optional[int] = None,
             ) -> MergeResult:
                 return LOOP.run(
        -            self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
        +            self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
                 )
         
             @property
        @@ -5199,6 +6427,21 @@ class LanceTable(Table):
                 self.checkout_latest()
                 return stats
         
        +    def compact_async(
        +        self, *, compaction_options: Optional[CompactionOptions] = None
        +    ) -> Job[CompactionResult]:
        +        return Job(
        +            LOOP.run(self._table.compact_async(compaction_options=compaction_options))
        +        )
        +
        +    def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
        +        return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds))
        +
        +    def cleanup_async(
        +        self, *, min_age_seconds: Optional[int] = None
        +    ) -> Job[CleanupResult]:
        +        return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds)))
        +
             def optimize(
                 self,
                 *,
        @@ -5329,13 +6572,30 @@ class LanceTable(Table):
                 computed: Dict[str, str] | None = None,
                 auto_refresh_enabled: bool | None = None,
                 auto_refresh_interval_seconds: int | None = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> AddColumnsResult:
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 return LOOP.run(
                     self._table.add_columns(
                         transforms,
                         computed=computed,
                         auto_refresh_enabled=auto_refresh_enabled,
                         auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                total_gpu_count=total_gpu_count,
        +                gpu_class=gpu_class,
        +                gpu_count=gpu_count,
                     )
                 )
         
        @@ -5343,9 +6603,32 @@ class LanceTable(Table):
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[Dict[str, int]] = None,
        +        planning_workers: Optional[Dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
                 gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        error_policy: Optional[Literal["fail", "skip"]] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> "RefreshColumnResult":
                 """Fill a computed column's unfilled rows and recompute those whose
                 inputs changed. See
        @@ -5353,8 +6636,31 @@ class LanceTable(Table):
                 return LOOP.run(
                     self._table.refresh_column(
                         column,
        +                where=where,
                         batch_size=batch_size,
        +                max_concurrency=max_concurrency,
        +                publication_interval_rows=publication_interval_rows,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                supervisor_resources=supervisor_resources,
        +                planning_workers=planning_workers,
                         gpu_class=gpu_class,
        +                total_gpu_count=total_gpu_count,
        +                retry_policy=retry_policy,
        +                error_policy=error_policy,
        +                max_failed_fraction=max_failed_fraction,
        +                max_failed_rows=max_failed_rows,
        +                row_timeout_seconds=row_timeout_seconds,
        +                init_timeout_seconds=init_timeout_seconds,
        +                num_workers=num_workers,
        +                max_job_attempts=max_job_attempts,
        +                max_executor_processes_per_worker=max_executor_processes_per_worker,
        +                retry_errors=retry_errors,
        +                retry_job_id=retry_job_id,
        +                retry_error_type=retry_error_type,
        +                include_quarantined=include_quarantined,
        +                function_version=function_version,
        +                recompute=recompute,
                         gpu_count=gpu_count,
                     )
                 )
        @@ -5363,9 +6669,32 @@ class LanceTable(Table):
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[Dict[str, int]] = None,
        +        planning_workers: Optional[Dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
                 gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        error_policy: Optional[Literal["fail", "skip"]] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> Job[RefreshColumnJobResult]:
                 """Fill a computed column's unfilled rows and recompute those whose
                 inputs changed, returning a handle to the refresh job. See
        @@ -5375,8 +6704,31 @@ class LanceTable(Table):
                     LOOP.run(
                         self._table.refresh_column_async(
                             column,
        +                    where=where,
                             batch_size=batch_size,
        +                    max_concurrency=max_concurrency,
        +                    publication_interval_rows=publication_interval_rows,
        +                    total_cpu_millis=total_cpu_millis,
        +                    total_memory_bytes=total_memory_bytes,
        +                    supervisor_resources=supervisor_resources,
        +                    planning_workers=planning_workers,
                             gpu_class=gpu_class,
        +                    total_gpu_count=total_gpu_count,
        +                    retry_policy=retry_policy,
        +                    error_policy=error_policy,
        +                    max_failed_fraction=max_failed_fraction,
        +                    max_failed_rows=max_failed_rows,
        +                    row_timeout_seconds=row_timeout_seconds,
        +                    init_timeout_seconds=init_timeout_seconds,
        +                    num_workers=num_workers,
        +                    max_job_attempts=max_job_attempts,
        +                    max_executor_processes_per_worker=max_executor_processes_per_worker,
        +                    retry_errors=retry_errors,
        +                    retry_job_id=retry_job_id,
        +                    retry_error_type=retry_error_type,
        +                    include_quarantined=include_quarantined,
        +                    function_version=function_version,
        +                    recompute=recompute,
                             gpu_count=gpu_count,
                         )
                     )
        @@ -5387,13 +6739,64 @@ class LanceTable(Table):
                 job_id: Optional[str] = None,
                 column: Optional[str] = None,
                 limit: Optional[int] = None,
        +        history: bool = False,
        +        page_token: Optional[str] = None,
             ) -> "FunctionErrors":
                 """The per-row errors Function refreshes recorded on this table. See
                 [`Table.function_errors`][lancedb.table.Table.function_errors]."""
                 return LOOP.run(
        -            self._table.function_errors(job_id=job_id, column=column, limit=limit)
        +            self._table.function_errors(
        +                job_id=job_id,
        +                column=column,
        +                limit=limit,
        +                history=history,
        +                page_token=page_token,
        +            )
        +        ).as_sync(self)
        +
        +    def quarantine_failed(
        +        self,
        +        column: str,
        +        *,
        +        error_type: Optional[str] = None,
        +        job_id: Optional[str] = None,
        +        after_attempts: Optional[int] = None,
        +        quarantined: bool = True,
        +    ) -> int:
        +        return LOOP.run(
        +            self._table.quarantine_failed(
        +                column,
        +                error_type=error_type,
        +                job_id=job_id,
        +                after_attempts=after_attempts,
        +                quarantined=quarantined,
        +            )
                 )
         
        +    def function_provenance(
        +        self,
        +        column: str,
        +        *,
        +        limit: Optional[int] = None,
        +        version: Optional[int] = None,
        +    ) -> FunctionProvenance:
        +        return LOOP.run(
        +            self._table.function_provenance(column, limit=limit, version=version)
        +        )
        +
        +    def column_statuses(
        +        self, column: Optional[str] = None
        +    ) -> list[FunctionColumnStatus]:
        +        return LOOP.run(self._table.column_statuses(column=column))
        +
        +    def column_status(self, column: str) -> FunctionColumnStatus:
        +        return LOOP.run(self._table.column_status(column))
        +
        +    def wait_fresh(
        +        self, column: str, timeout: Optional[timedelta] = None
        +    ) -> FunctionColumnStatus:
        +        return LOOP.run(self._table.wait_fresh(column, timeout))
        +
             def alter_columns(
                 self, *alterations: Iterable[Dict[str, str]]
             ) -> AlterColumnsResult:
        @@ -5439,8 +6842,16 @@ class LanceTable(Table):
             def update_table_overrides(self, **overrides: Any) -> dict[str, Any]:
                 """Merge Enterprise table overrides into the current table overrides.
         
        -        Only fields supplied in ``overrides`` are changed; unrelated overrides
        -        from the current read snapshot are preserved.
        +        Fetches the current overrides, recursively merges nested objects locally,
        +        then sends the complete replacement using REST PUT. Other values replace
        +        existing values; unrelated fields from the read snapshot are preserved.
        +        This read-modify-write is not atomic: concurrent edits can be overwritten,
        +        even to unrelated fields. Coordinate writers when concurrent edits must
        +        be preserved. An empty update only reads and returns the current overrides.
        +
        +        Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides
        +        object without merging. Use ``reset_table_overrides()`` to clear all
        +        overrides. Supported only on remote Enterprise tables.
         
                 Examples
                 --------
        @@ -6218,8 +7629,16 @@ class AsyncTable:
             async def update_table_overrides(self, **overrides: Any) -> dict[str, Any]:
                 """Merge Enterprise table overrides into the current table overrides.
         
        -        Only fields supplied in ``overrides`` are changed; unrelated overrides
        -        from the current read snapshot are preserved.
        +        Fetches the current overrides, recursively merges nested objects locally,
        +        then sends the complete replacement using REST PUT. Other values replace
        +        existing values; unrelated fields from the read snapshot are preserved.
        +        This read-modify-write is not atomic: concurrent edits can be overwritten,
        +        even to unrelated fields. Coordinate writers when concurrent edits must
        +        be preserved. An empty update only reads and returns the current overrides.
        +
        +        Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides
        +        object without merging. Use ``reset_table_overrides()`` to clear all
        +        overrides. Supported only on remote Enterprise tables.
         
                 Examples
                 --------
        @@ -6329,6 +7748,9 @@ class AsyncTable:
                 """
                 return _restore_blob_extensions(await self._inner.schema())
         
        +    def _schema_sync(self) -> pa.Schema:
        +        return _restore_blob_extensions(self._inner.schema_sync())
        +
             async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]:
                 """
                 Get the embedding functions for the table
        @@ -6457,7 +7879,7 @@ class AsyncTable:
         
                 if blob_mode == "lazy" and get_uri_scheme(await self.uri()) == "memory":
                     return (await self.to_arrow()).to_pandas(**kwargs)
        -        if blob_mode == "bytes" and blob_v2_column_paths(schema):
        +        if blob_mode == "bytes" and schema_has_blob_field(schema):
                     return await self.query().to_pandas(blob_mode=blob_mode, **kwargs)
                 return (await self.to_lance()).to_pandas(blob_mode=blob_mode, **kwargs)
         
        @@ -6469,8 +7891,8 @@ class AsyncTable:
                 blob_mode: str, default "lazy"
                     ``"lazy"`` returns blob v2 descriptors that carry the row id
                     ``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
        -            ``"bytes"`` returns payload bytes and raises for legacy blob columns
        -            and blobs inside lists.
        +            ``"bytes"`` returns payload bytes for supported row-addressable blob
        +            columns and raises for blobs inside lists.
         
                 Returns
                 -------
        @@ -6511,11 +7933,15 @@ class AsyncTable:
                         LabelList,
                         Fm,
                         NGram,
        +                ZoneMap,
        +                RTree,
        +                ScalarPlugin,
                         FTS,
                     ]
                 ] = None,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
                 train: bool = True,
             ):
                 """Create an index to speed up queries
        @@ -6546,6 +7972,9 @@ class AsyncTable:
                     If not set, the call returns once the build is scheduled.
                 name: str, optional
                     The name of the index. If not provided, a default name will be generated.
        +        exist_ok: bool, default False
        +            Preserve an existing index with the requested or derived name. This
        +            takes precedence over replace and keeps its definition and build.
                 train: bool, default True
                     Whether to train the index with existing data. Vector indices always train
                     with existing data.
        @@ -6587,19 +8016,23 @@ class AsyncTable:
                             LabelList,
                             Fm,
                             NGram,
        +                    ZoneMap,
        +                    RTree,
        +                    ScalarPlugin,
                             FTS,
                         ),
                     ):
                         raise TypeError(
                             "config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
        -                    " BTree, Bitmap, LabelList, Fm, NGram, or FTS, but got "
        -                    + str(type(config))
        +                    " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree,"
        +                    " ScalarPlugin, or FTS, but got " + str(type(config))
                         )
                 try:
                     await self._inner.create_index(
                         column,
                         index=config,
                         replace=replace,
        +                exist_ok=exist_ok,
                         wait_timeout=wait_timeout,
                         name=name,
                         train=train,
        @@ -6631,11 +8064,15 @@ class AsyncTable:
                         LabelList,
                         Fm,
                         NGram,
        +                ZoneMap,
        +                RTree,
        +                ScalarPlugin,
                         FTS,
                     ]
                 ] = None,
                 wait_timeout: Optional[timedelta] = None,
                 name: Optional[str] = None,
        +        exist_ok: bool = False,
                 train: bool = True,
             ) -> AsyncJob:
                 """Create an index, returning a handle to the indexing job.
        @@ -6654,6 +8091,7 @@ class AsyncTable:
                     column,
                     index=config,
                     replace=replace,
        +            exist_ok=exist_ok,
                     wait_timeout=wait_timeout,
                     name=name,
                     train=train,
        @@ -6702,7 +8140,14 @@ class AsyncTable:
                 """
                 await self._inner.prewarm_index(name)
         
        -    async def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
        +    async def prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> None:
                 """
                 Prewarm data for the table.
         
        @@ -6711,7 +8156,8 @@ class AsyncTable:
                 Currently only supported in LanceDB Enterprise.
         
                 This call initiates prewarming and returns once the request is accepted.
        -        It is idempotent and safe to call from multiple clients concurrently.
        +        Uses SQL PREWARM and requires Flight SQL connectivity. To track the
        +        durable warming job, use ``prewarm_data_async()``.
         
                 This operation has a large upfront cost but can speed up future queries
                 that need to fetch the given columns.  Large columns such as embeddings
        @@ -6722,8 +8168,74 @@ class AsyncTable:
                 ----------
                 columns: list of str, optional
                     The columns to prewarm. If None, all columns are prewarmed.
        +        filter: str, optional
        +            A single SQL predicate for conservative metadata pruning.
        +        parameters: sequence, mapping, or one-row Arrow batch/table, optional
        +            Scalar values for ``$1``/``$name`` placeholders in ``filter``.
        +            Values are sent separately from SQL; requires server support.
        +        concurrency: int, optional
        +            Positive per-executor warming concurrency; omitted uses the server default.
        +
        +        Examples
        +        --------
        +        >>> await table.prewarm_data(  # doctest: +SKIP
        +        ...     ["payload"], filter="quality > 0.7", concurrency=4)
                 """
        -        await self._inner.prewarm_data(columns)
        +        await self.prewarm_data_async(
        +            columns, filter=filter, concurrency=concurrency, parameters=parameters
        +        )
        +
        +    async def explain_prewarm_data(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> PrewarmDataPlan:
        +        """Preview prewarm without submitting a warming job.
        +
        +        See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data]
        +        for options, permissions, snapshot semantics, and limitations.
        +        """
        +        return PrewarmDataPlan.from_json(
        +            await self._inner.explain_prewarm_data(
        +                columns,
        +                filter=filter,
        +                concurrency=concurrency,
        +                parameters=to_parameter_batch(parameters),
        +            )
        +        )
        +
        +    async def prewarm_data_async(
        +        self,
        +        columns: Optional[List[str]] = None,
        +        *,
        +        filter: Optional[str] = None,
        +        concurrency: Optional[int] = None,
        +        parameters: Optional[QueryParameters] = None,
        +    ) -> AsyncJob[PrewarmDataResult]:
        +        """Submit data prewarm and return a durable handle after acceptance.
        +
        +        See [Table.prewarm_data_async][lancedb.table.Table.prewarm_data_async]
        +        for options, permissions, and compatibility. Awaiting this method does
        +        not wait for warming; use ``await job.wait()`` for completion.
        +
        +        Examples
        +        --------
        +        >>> job = await table.prewarm_data_async(  # doctest: +SKIP
        +        ...     ["video"], filter="quality > 0.7", concurrency=4)
        +        >>> await job.wait()  # doctest: +SKIP
        +        """
        +        return _typed_job(
        +            await self._inner.prewarm_data_async(
        +                columns,
        +                filter=filter,
        +                concurrency=concurrency,
        +                parameters=to_parameter_batch(parameters),
        +            ),
        +            PrewarmDataResult.from_json,
        +        )
         
             async def wait_for_index(
                 self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
        @@ -6803,6 +8315,7 @@ class AsyncTable:
                 progress: Optional[Union[bool, Callable, Any]] = None,
                 write_parallelism: Optional[int] = None,
                 allow_external_blob_outside_bases: bool = False,
        +        retries: Optional[int] = None,
             ) -> AddResult:
                 """Add more data to the [AsyncTable][lancedb.table.AsyncTable].
         
        @@ -6841,6 +8354,10 @@ class AsyncTable:
                 allow_external_blob_outside_bases: bool, default False
                     Allow blob URIs outside registered bases. See :meth:`Table.add`.
                     LanceDB Embedded only.
        +        retries: int, optional
        +            Override the remote retry budget for this call (0 to 255). Zero
        +            disables retries, including multipart parts. Ambiguous commits are
        +            never replayed. Ignored by LanceDB Embedded.
         
                 """
                 schema = await self.schema()
        @@ -6895,6 +8412,7 @@ class AsyncTable:
                         progress=progress,
                         write_parallelism=write_parallelism,
                         allow_external_blob_outside_bases=allow_external_blob_outside_bases,
        +                retries=retries,
                     )
                 except RuntimeError as e:
                     if "Cast error" in str(e):
        @@ -6979,6 +8497,8 @@ class AsyncTable:
                 query_type: QueryType = "auto",
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> AsyncQuery: ...
         
             @overload
        @@ -6989,6 +8509,8 @@ class AsyncTable:
                 query_type: Literal["auto"] = ...,
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> Union[AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]: ...
         
             @overload
        @@ -6999,6 +8521,8 @@ class AsyncTable:
                 query_type: Literal["hybrid"] = ...,
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> AsyncHybridQuery: ...
         
             @overload
        @@ -7009,6 +8533,8 @@ class AsyncTable:
                 query_type: Literal["auto"] = ...,
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> AsyncVectorQuery: ...
         
             @overload
        @@ -7019,6 +8545,8 @@ class AsyncTable:
                 query_type: Literal["fts"] = ...,
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> AsyncFTSQuery: ...
         
             @overload
        @@ -7029,6 +8557,8 @@ class AsyncTable:
                 query_type: Literal["vector"] = ...,
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> AsyncVectorQuery: ...
         
             async def search(
        @@ -7040,6 +8570,8 @@ class AsyncTable:
                 query_type: QueryType = "auto",
                 ordering_field_name: Optional[str] = None,
                 fts_columns: Optional[Union[str, List[str]]] = None,
        +        *,
        +        operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
             ) -> Union[AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]:
                 """Create a search query to find the nearest neighbors
                 of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
        @@ -7083,12 +8615,20 @@ class AsyncTable:
                     - If `query` is a string, then the query type is "vector" if the
                       table has embedding functions else the query type is "fts"
         
        +        operator: "AND" or "OR", optional
        +            Combine terms in a string full-text query; the default is OR.
        +            Use ``query_type="fts"`` when the table also has embeddings.
        +
                 Returns
                 -------
                 AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, or AsyncVectorQuery
                     A query builder object representing the query.
                 """
         
        +        if operator is not None:
        +            operator = FullTextOperator(operator)
        +            if not isinstance(query, str) or query_type not in ("auto", "fts"):
        +                raise ValueError("operator requires a string full-text query")
                 if query is None:
                     return self.query()
         
        @@ -7207,13 +8747,17 @@ class AsyncTable:
                         )
                         vector_query = await make_embedding(embedding_conf, query)
         
        +        if operator is not None and query_type != "fts":
        +            raise ValueError("operator requires a string full-text query")
                 if query_type == "vector":
                     builder = self.query().nearest_to(vector_query)
                     if vector_column_name:
                         builder = builder.column(vector_column_name)
                     return builder
                 elif query_type == "fts":
        -            return self.query().nearest_to_text(query, columns=fts_columns)
        +            return self.query().nearest_to_text(
        +                query, columns=fts_columns, operator=operator
        +            )
                 elif query_type == "hybrid":
                     builder = self.query().nearest_to(vector_query)
                     if vector_column_name:
        @@ -7244,10 +8788,32 @@ class AsyncTable:
                 | AsyncQuery
                 | AsyncTakeQuery
             ):
        -        if query.take_offsets is not None:
        -            take_query = self.take_offsets(query.take_offsets)
        -            if query.columns:
        -                take_query = take_query.select(query.columns)
        +        if query.take_offsets is not None or query.take_row_ids is not None:
        +            if query.take_offsets is not None and query.take_row_ids is not None:
        +                raise ValueError("Only one of take_offsets and take_row_ids may be set")
        +            if query.preserve_order is True and query.take_offsets is None:
        +                raise ValueError("preserve_order only supports take_offsets")
        +            if query.preserve_order is True and query.order_by:
        +                raise ValueError(
        +                    "preserve_order cannot be combined with an explicit order_by"
        +                )
        +            take_query = (
        +                self.take_row_ids(query.take_row_ids)
        +                if query.take_row_ids is not None
        +                else self.take_offsets(
        +                    query.take_offsets, preserve_order=query.preserve_order is True
        +                )
        +            )
        +            if query.columns is not None:
        +                columns = query.columns
        +                # Native requests serialize dynamic projections as (name, SQL) pairs.
        +                if (
        +                    isinstance(columns, list)
        +                    and columns
        +                    and isinstance(columns[0], tuple)
        +                ):
        +                    columns = dict(columns)
        +                take_query = take_query.select(columns)
                     if query.use_rte is not None:
                         take_query = take_query.use_rte(query.use_rte)
                     if query.with_row_id:
        @@ -7260,7 +8826,10 @@ class AsyncTable:
                 if query.offset is not None:
                     async_query = async_query.offset(query.offset)
                 if query.columns:
        -            async_query = async_query.select(query.columns)
        +            columns = query.columns
        +            if isinstance(columns, list) and columns and isinstance(columns[0], tuple):
        +                columns = dict(columns)
        +            async_query = async_query.select(columns)
                 if query.filter is not None:
                     async_query = async_query.where(query.filter)
                 if query.fast_search:
        @@ -7271,6 +8840,8 @@ class AsyncTable:
                     async_query = async_query.with_row_id()
                 if query.order_by:
                     async_query = async_query.order_by(query.order_by)
        +        if query.scan_in_order is not None:
        +            async_query = async_query.scan_in_order(query.scan_in_order)
         
                 if query.vector:
                     async_query = async_query.nearest_to(query.vector).distance_range(
        @@ -7306,7 +8877,9 @@ class AsyncTable:
         
                 if query.full_text_query:
                     async_query = async_query.nearest_to_text(
        -                query.full_text_query.query, query.full_text_query.columns
        +                query.full_text_query.query,
        +                query.full_text_query.columns,
        +                operator=query.full_text_query.operator,
                     )
         
                 return async_query
        @@ -7335,11 +8908,31 @@ class AsyncTable:
                 # used for that code path right now.
         
                 async_query = self._sync_query_to_async(query)
        +        async_query._blob_row_id_prepared = query._blob_row_id_prepared
         
                 return await async_query.to_batches(
                     max_batch_length=batch_size, timeout=timeout
                 )
         
        +    async def _execute_arrow(
        +        self,
        +        query: Query,
        +        *,
        +        timeout: Optional[timedelta] = None,
        +    ) -> pa.Table:
        +        if (
        +            _should_push_down_query_table(
        +                self._namespace_client, self._pushdown_operations
        +            )
        +            and not self._route_pushdown_to_rust
        +            and not _requires_local_namespace_execution(query)
        +        ):
        +            return (await self._execute_query(query, timeout=timeout)).read_all()
        +
        +        async_query = self._sync_query_to_async(query)
        +        async_query._blob_row_id_prepared = query._blob_row_id_prepared
        +        return await async_query._execute_eager(timeout=timeout)
        +
             async def _explain_plan(self, query: Query, verbose: Optional[bool]) -> str:
                 # This method is used by the sync table
                 async_query = self._sync_query_to_async(query)
        @@ -7365,6 +8958,7 @@ class AsyncTable:
                 new_data: DATA,
                 on_bad_vectors: OnBadVectorsType,
                 fill_value: float,
        +        retries: Optional[int] = None,
             ) -> MergeResult:
                 schema = await self.schema()
                 if on_bad_vectors is None:
        @@ -7396,6 +8990,7 @@ class AsyncTable:
                         use_rte=merge._use_rte,
                         validate_single_shard=merge._validate_single_shard,
                     ),
        +            retries=retries,
                 )
         
             async def delete(self, where: Union[str, Expr]) -> DeleteResult:
        @@ -7555,6 +9150,11 @@ class AsyncTable:
                 computed: dict[str, str] | None = None,
                 auto_refresh_enabled: bool | None = None,
                 auto_refresh_interval_seconds: int | None = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        gpu_class: Optional[str] = None,
        +        gpu_count: Optional[int] = None,
             ) -> AddColumnsResult:
                 """
                 Add new columns with defined values.
        @@ -7570,10 +9170,11 @@ class AsyncTable:
                     Alternatively, you can pass a pyarrow field or schema to add
                     new columns with NULLs.
         
        -            A mapping with one ``FunctionApplication`` value keeps its scalar
        -            or named-struct result in the named table column. A bare
        -            named-struct application expands its ordered result fields as one
        -            atomic binding; aliases come from ``rename(columns=...)``.
        +            A mapping of column names to ``FunctionApplication`` values declares
        +            all bindings in one schema commit. Each column holds its scalar
        +            or entire named-struct result. A bare named-struct application expands
        +            its ordered result fields as one atomic binding. Set field aliases
        +            with ``rename(columns=...)``.
                     Function columns are supported only in LanceDB
                     Enterprise.
         
        @@ -7621,7 +9222,12 @@ class AsyncTable:
                     not force recomputation. Applies to every declared computed output.
                     These options cannot be used with one-time transforms or ordinary
                     all-null columns.
        -
        +        total_cpu_millis: int, optional
        +            Default total CPU budget for manual and automatic Function refreshes.
        +        total_memory_bytes: int, optional
        +            Default total memory budget for these refreshes, in bytes.
        +        total_gpu_count: int, optional
        +            Default total GPU budget across the Function workers.
                 Examples
                 --------
                 >>> await table.add_columns(  # doctest: +SKIP
        @@ -7636,6 +9242,13 @@ class AsyncTable:
                     version: the new version number of the table after adding columns.
         
                 """
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 if auto_refresh_enabled is not None and type(auto_refresh_enabled) is not bool:
                     raise ValueError("auto_refresh_enabled must be a boolean")
                 if auto_refresh_interval_seconds is not None and (
        @@ -7649,34 +9262,43 @@ class AsyncTable:
                 options_supplied = (
                     auto_refresh_enabled is not None
                     or auto_refresh_interval_seconds is not None
        +            or total_cpu_millis is not None
        +            or total_memory_bytes is not None
        +            or total_gpu_count is not None
        +            or gpu_class is not None
        +            or gpu_count is not None
                 )
        -        function_application = None
        -        function_output_name = None
        +        bindings: list[tuple[FunctionApplication, str | None]] = []
                 if isinstance(transforms, FunctionApplication):
        -            function_application = transforms
        +            bindings.append((transforms, None))
                 elif isinstance(transforms, Mapping) and any(
                     isinstance(value, FunctionApplication) for value in transforms.values()
                 ):
        -            if len(transforms) != 1 or not all(
        -                isinstance(value, FunctionApplication) for value in transforms.values()
        -            ):
        -                raise ValueError(
        -                    "one add_columns call declares exactly one Function binding"
        -                )
        -            function_output_name, function_application = next(iter(transforms.items()))
        +            for name, application in transforms.items():
        +                if not isinstance(application, FunctionApplication):
        +                    raise ValueError(
        +                        "add_columns cannot mix Function applications and SQL "
        +                        "expressions"
        +                    )
        +                bindings.append((application, name))
         
        -        if function_application is not None:
        +        if bindings:
                     if computed:
                         raise ValueError(
                             "add_columns cannot mix a Function application with SQL "
                             "computed columns"
                         )
        -            function_application._ensure_declarable()
        +            for application, _ in bindings:
        +                application._ensure_declarable()
                     return await self._inner.add_function_columns(
        -                function_application.to_canonical_json(),
        -                function_output_name,
        +                [(app.to_canonical_json(), name) for app, name in bindings],
                         auto_refresh_enabled,
                         auto_refresh_interval_seconds,
        +                total_cpu_millis,
        +                total_memory_bytes,
        +                total_gpu_count,
        +                gpu_class,
        +                gpu_count,
                     )
         
                 if isinstance(transforms, pa.Field):
        @@ -7697,6 +9319,11 @@ class AsyncTable:
                         list(computed.items()),
                         auto_refresh_enabled,
                         auto_refresh_interval_seconds,
        +                total_cpu_millis,
        +                total_memory_bytes,
        +                total_gpu_count,
        +                gpu_class,
        +                gpu_count,
                     )
                 if options_supplied:
                     raise ValueError(
        @@ -7716,9 +9343,32 @@ class AsyncTable:
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[Dict[str, int]] = None,
        +        planning_workers: Optional[Dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
                 gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        error_policy: Optional[Literal["fail", "skip"]] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> RefreshColumnResult:
                 """
                 Fill the rows of a computed column that hold no value yet.
        @@ -7739,47 +9389,233 @@ class AsyncTable:
                 ----------
                 column: str
                     The name of the computed column to fill.
        +        where: str, optional
        +            SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN
        +            ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB
        +            Enterprise only; local refreshes reject this option.
                 batch_size: int, optional
                     Maximum rows per Function call on the remote server. Must be
                     greater than zero. None uses the server default. Has no effect on
                     local expression-backed columns.
        +        max_concurrency: int, optional
        +            Override the registered Function's maximum concurrent user-code
        +            calls for this logical execution. Must be between 1 and
        +            4294967295. None uses the registration default. This is not an
        +            account-wide quota. LanceDB Enterprise only; local refreshes
        +            reject this option.
        +        publication_interval_rows: int, optional
        +            Opt-in publication threshold for completed Function outputs. Must
        +            be greater than zero. None keeps whole-fragment publication. The
        +            actual publication boundary can be larger than this threshold
        +            because it also depends on completed work and Function batching.
        +            LanceDB Enterprise only; local refreshes reject this option.
        +        total_cpu_millis: int, optional
        +            Override the total CPU budget in millicores for this refresh.
        +        total_memory_bytes: int, optional
        +            Override the total memory budget in bytes for this refresh.
        +        supervisor_resources: dict[str, int], optional
        +            CPU, memory, and ephemeral-storage limits for the Function refresh
        +            supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
        +            ``ephemeral_storage_bytes``; all are required and positive.
        +            LanceDB Enterprise only; local refreshes reject it.
        +        planning_workers: dict[str, object], optional
        +            Resources and sizing for the Function refresh planning fleet.
        +            ``resources`` has the same keys as ``supervisor_resources``; the
        +            other keys are ``max_workers``, ``rows_per_worker`` and
        +            ``fragments_per_worker``. LanceDB Enterprise only; local refreshes
        +            reject it.
                 gpu_class: str, optional
                     GPU class for Function workers. Must be a lowercase name of 1-63
                     letters, digits, or hyphens, without a leading or trailing hyphen.
                     None keeps the Function's registered class or the deployment
                     default. LanceDB Enterprise only.
        -        gpu_count: int, optional
        -            Positive aggregate GPU budget for Function workers. None leaves
        -            the server's configured budget unchanged. LanceDB Enterprise
        -            only.
        +        total_gpu_count: int, optional
        +            Nonnegative total GPU budget for Function workers without changing
        +            the other resource limits. Unspecified resources inherit column defaults,
        +            then Function defaults, then deployment defaults. LanceDB Enterprise only.
        +        retry_policy: FunctionRetryPolicy, optional
        +            Override retries of failed user-code calls. Only use when repeating
        +            partial work is safe. Set max_attempts=1 to disable retries.
        +            Enterprise Functions only; local refreshes reject this option.
        +        error_policy: {"fail", "skip"}, optional
        +            Action after failure or retry exhaustion. Skip records the error
        +            and attempt count, subject to the server's failure limits.
        +            Workflow version 1 servers default to skip with a 5% failure ceiling
        +            and publish successful output before reporting a threshold failure.
        +            Older deployments retain their existing defaults.
        +        max_failed_fraction: float, optional
        +            Under a skip policy, fail the job once more than this share of
        +            rows (0 to 1) has failed. LanceDB Enterprise only.
        +        max_failed_rows: int, optional
        +            Under a skip policy, fail the job once more than this many rows
        +            have failed. LanceDB Enterprise only.
        +        row_timeout_seconds: float, optional
        +            Deadline for one Function call. LanceDB Enterprise only.
        +        init_timeout_seconds: float, optional
        +            Deadline for Function initialization. LanceDB Enterprise only.
        +        num_workers: int, optional
        +            Worker count for an expression column; registered Function
        +            columns reject it and set the corresponding ``total_*`` options. LanceDB
        +            Enterprise only.
        +        max_job_attempts: int, optional
        +            Total automatic Function refresh attempts, including the initial job.
        +            Set to 1 to disable automatic job recovery.
        +        max_executor_processes_per_worker: int, optional
        +            Cap on executor processes per Function worker. LanceDB
        +            Enterprise only.
        +        retry_errors: bool, default False
        +            Select current failed rows on the server. Cannot be combined with
        +            ``where``. Requires Enterprise workflow version 1 or later.
        +        retry_job_id: str, optional
        +            Restrict a failed-row retry to errors recorded by this job.
        +        retry_error_type: str, optional
        +            Restrict a failed-row retry to this exception class.
        +        include_quarantined: bool, default False
        +            Explicitly release and include quarantined rows in a failed-row retry.
        +        function_version: str, optional
        +            Atomically rebind this column's Function to the specified immutable
        +            version. Requires Enterprise workflow version 1 or later.
        +        recompute: {"failed", "all", "none"}, optional
        +            Which rows to recompute during an upgrade. Requires
        +            ``function_version``; the default is ``all``. ``failed`` selects
        +            current failures, and ``none`` preserves existing values. Quarantined
        +            rows stay excluded unless explicitly included in a failed-row retry.
         
                 Returns
                 -------
                 RefreshColumnResult
                     The number of rows filled and the new version of the table.
                 """
        -        return await self._inner.refresh_column(
        -            column,
        -            batch_size=batch_size,
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
                     gpu_class=gpu_class,
                     gpu_count=gpu_count,
                 )
        +        return await self._inner.refresh_column(
        +            column,
        +            where=where,
        +            batch_size=batch_size,
        +            max_concurrency=max_concurrency,
        +            publication_interval_rows=publication_interval_rows,
        +            total_cpu_millis=total_cpu_millis,
        +            total_memory_bytes=total_memory_bytes,
        +            supervisor_resources=supervisor_resources,
        +            planning_workers=planning_workers,
        +            gpu_class=gpu_class,
        +            total_gpu_count=total_gpu_count,
        +            retry_policy=None
        +            if retry_policy is None
        +            else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(),
        +            error_policy=error_policy,
        +            max_failed_fraction=max_failed_fraction,
        +            max_failed_rows=max_failed_rows,
        +            row_timeout_seconds=row_timeout_seconds,
        +            init_timeout_seconds=init_timeout_seconds,
        +            num_workers=num_workers,
        +            max_job_attempts=max_job_attempts,
        +            max_executor_processes_per_worker=max_executor_processes_per_worker,
        +            retry_errors=retry_errors,
        +            retry_job_id=retry_job_id,
        +            retry_error_type=retry_error_type,
        +            include_quarantined=include_quarantined,
        +            function_version=function_version,
        +            recompute=recompute,
        +            gpu_count=gpu_count,
        +        )
        +
        +    async def resume_refresh(self, job_id: str) -> AsyncJob[RefreshColumnJobResult]:
        +        """Resume a failed Enterprise Function refresh on this table and branch."""
        +        return _typed_job(
        +            await self._inner.resume_refresh(job_id),
        +            RefreshColumnJobResult.from_json,
        +        )
        +
        +    async def retry_failed(
        +        self,
        +        column: str,
        +        *,
        +        error_type: Optional[str] = None,
        +        job_id: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        **options: Any,
        +    ) -> AsyncJob[RefreshColumnJobResult]:
        +        """Start an exact failed-row retry; see ``Table.retry_failed``."""
        +        return await self.refresh_column_async(
        +            column,
        +            retry_errors=True,
        +            retry_error_type=error_type,
        +            retry_job_id=job_id,
        +            include_quarantined=include_quarantined,
        +            function_version=function_version,
        +            recompute="failed" if function_version is not None else None,
        +            **options,
        +        )
        +
        +    async def upgrade_column(
        +        self,
        +        column: str,
        +        *,
        +        version: str,
        +        recompute: Literal["failed", "all", "none"] = "all",
        +        **options: Any,
        +    ) -> AsyncJob[RefreshColumnJobResult]:
        +        """Upgrade the Function and choose which rows to recompute."""
        +        return await self.refresh_column_async(
        +            column, function_version=version, recompute=recompute, **options
        +        )
        +
        +    async def quarantine_failed(
        +        self,
        +        column: str,
        +        *,
        +        error_type: Optional[str] = None,
        +        job_id: Optional[str] = None,
        +        after_attempts: Optional[int] = None,
        +        quarantined: bool = True,
        +    ) -> int:
        +        """Quarantine current failures or release them for later refreshes."""
        +        return await self._inner.quarantine_function_errors(
        +            column,
        +            quarantined=quarantined,
        +            error_type=error_type,
        +            job_id=job_id,
        +            after_attempts=after_attempts,
        +        )
        +
        +    async def function_provenance(
        +        self,
        +        column: str,
        +        *,
        +        limit: Optional[int] = None,
        +        version: Optional[int] = None,
        +    ) -> FunctionProvenance:
        +        """Read per-row producing versions at a table snapshot."""
        +        return FunctionProvenance.from_json(
        +            await self._inner.function_provenance(column, limit=limit, version=version)
        +        )
         
             async def function_errors(
                 self,
                 job_id: Optional[str] = None,
                 column: Optional[str] = None,
                 limit: Optional[int] = None,
        -    ) -> "FunctionErrors":
        +        history: bool = False,
        +        page_token: Optional[str] = None,
        +    ) -> "AsyncFunctionErrors":
                 """
                 The per-row errors Function refreshes recorded on this table.
         
        -        A refresh running under a skip policy records each row it skipped
        -        with the input that failed and the error. This lists those records,
        -        newest job first, plus a summary for any fragment whose per-row
        -        detail was capped. LanceDB Enterprise only; reading errors
        -        needs read access to the table, since a message carries the value
        -        that failed.
        +        A refresh running under a skip policy records each row it skipped.
        +        On servers advertising workflow version 1 or later, the default lists
        +        current unresolved failures, deduplicated by row and Function column,
        +        with attempt counts and first/last failure times. ``history=True``
        +        returns retained observations, including repaired failures. Older servers
        +        keep their legacy listing behavior and reject explicit history requests.
        +        LanceDB Enterprise only; reading errors needs table read access because
        +        messages can include the input that failed.
         
                 Parameters
                 ----------
        @@ -7789,16 +9625,46 @@ class AsyncTable:
                     Only errors on this column.
                 limit: int, optional
                     At most this many records (server default 10000, cap 100000).
        +        history: bool, default False
        +            Include retained historical errors instead of current failures.
        +            Requires Enterprise workflow version 1 or later. Historical records
        +            cannot be used with the current-input ``rows()`` helper.
        +        page_token: str, optional
        +            Empty starts retained history, including repaired rows, for an exact
        +            job_id. Continue with the response's
        +            page_token until it is None, keeping all filters unchanged.
         
                 Returns
                 -------
        -        FunctionErrors
        +        AsyncFunctionErrors
                     ``records``, ``fragments`` and ``truncated``, the last saying
                     whether the listing stopped at its limit.
         
        -        Each record identifies its row with ``fragment_id``, ``row_offset``
        -        and the physical ``row_address`` (``(fragment_id << 32) |
        -        row_offset``). To retry the recorded rows, collect the non-null
        +        Each record identifies its row with ``fragment_id``, ``row_offset``,
        +        the physical ``row_address`` (``(fragment_id << 32) |
        +        row_offset``), and, when the table uses stable row IDs, the stable
        +        ``row_id`` read from the refresh's pinned table version. Prefer
        +        ``row_id`` for retries: compaction and rewrite can change the
        +        physical fields, while a stable row ID survives them.
        +
        +        To retry the recorded rows with stable row IDs:
        +
        +        .. code-block:: python
        +
        +            errors = await table.function_errors(column="embedding")
        +            row_ids = sorted(
        +                record.row_id
        +                for record in errors.records
        +                if record.row_id is not None
        +            )
        +            if row_ids:
        +                row_id_list = ", ".join(str(row_id) for row_id in row_ids)
        +                await database.execute_query(
        +                    f"REFRESH COLUMN embedding ON {table.name} "
        +                    f"WHERE _rowid IN ({row_id_list})"
        +                )
        +
        +        For a table without stable row IDs, collect the non-null physical
                 addresses before the table is compacted or rewritten and run the
                 SQL refresh:
         
        @@ -7813,7 +9679,7 @@ class AsyncTable:
                     if addresses:
                         address_list = ", ".join(str(address) for address in addresses)
                         await database.execute_query(
        -                    f"REFRESH COLUMN embedding ON {table.name()} "
        +                    f"REFRESH COLUMN embedding ON {table.name} "
                             f"WHERE _rowaddr IN ({address_list})"
                         )
         
        @@ -7828,17 +9694,71 @@ class AsyncTable:
                 >>> if errors.truncated:  # doctest: +SKIP
                 ...     print("listing stopped at the limit")
                 """
        -        return await self._inner.function_errors(
        -            job_id=job_id, column=column, limit=limit
        +        raw = await self._inner.function_errors(
        +            job_id=job_id,
        +            column=column,
        +            limit=limit,
        +            history=history,
        +            page_token=page_token,
                 )
        +        return AsyncFunctionErrors(raw, self, history=history or page_token is not None)
        +
        +    async def column_statuses(
        +        self, column: Optional[str] = None
        +    ) -> list[FunctionColumnStatus]:
        +        """Return exact status for Function-backed output columns.
        +
        +        All results describe one server table version. ``column=None`` returns
        +        every Function output. A handle pinned to an exact version requests
        +        that version.
        +        """
        +        return await self._inner.column_statuses(column=column)
        +
        +    async def column_status(self, column: str) -> FunctionColumnStatus:
        +        """Return exact status for one Function-backed output column."""
        +        return await self._inner.column_status(column)
        +
        +    async def wait_fresh(
        +        self, column: str, timeout: Optional[timedelta] = None
        +    ) -> FunctionColumnStatus:
        +        """Poll until no stale or never-computed rows remain.
        +
        +        Failed rows do not block completion. Server and transport errors are
        +        not retried. Only the typed finalization-pending response is retried
        +        with bounded backoff; arbitrary 500 responses surface immediately.
        +        """
        +        return await self._inner.wait_column_fresh(column, timeout)
         
             async def refresh_column_async(
                 self,
                 column: str,
                 *,
        +        where: Optional[str] = None,
                 batch_size: Optional[int] = None,
        +        max_concurrency: Optional[int] = None,
        +        publication_interval_rows: Optional[int] = None,
        +        total_cpu_millis: Optional[int] = None,
        +        total_memory_bytes: Optional[int] = None,
        +        supervisor_resources: Optional[Dict[str, int]] = None,
        +        planning_workers: Optional[Dict[str, Any]] = None,
                 gpu_class: Optional[str] = None,
                 gpu_count: Optional[int] = None,
        +        total_gpu_count: Optional[int] = None,
        +        retry_policy: Optional[FunctionRetryPolicy] = None,
        +        error_policy: Optional[Literal["fail", "skip"]] = None,
        +        max_failed_fraction: Optional[float] = None,
        +        max_failed_rows: Optional[int] = None,
        +        row_timeout_seconds: Optional[float] = None,
        +        init_timeout_seconds: Optional[float] = None,
        +        num_workers: Optional[int] = None,
        +        max_job_attempts: Optional[int] = None,
        +        max_executor_processes_per_worker: Optional[int] = None,
        +        retry_errors: bool = False,
        +        retry_job_id: Optional[str] = None,
        +        retry_error_type: Optional[str] = None,
        +        include_quarantined: bool = False,
        +        function_version: Optional[str] = None,
        +        recompute: Optional[Literal["failed", "all", "none"]] = None,
             ) -> AsyncJob[RefreshColumnJobResult]:
                 """
                 Like :meth:`refresh_column`, but returns a handle to the refresh job
        @@ -7857,20 +9777,98 @@ class AsyncTable:
                 ----------
                 column: str
                     The name of the computed column to fill.
        +        where: str, optional
        +            SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN
        +            ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB
        +            Enterprise only; local refreshes reject this option.
                 batch_size: int, optional
                     Maximum rows per Function call on the remote server. Must be
                     greater than zero. None uses the server default. Lower this for
                     slow Functions to stay within the executor's per-call deadline.
                     Has no effect on local expression-backed columns.
        +        max_concurrency: int, optional
        +            Override the registered Function's maximum concurrent user-code
        +            calls for this logical execution. Must be between 1 and
        +            4294967295. None uses the registration default. This is not an
        +            account-wide quota. LanceDB Enterprise only; local refreshes
        +            reject this option.
        +        publication_interval_rows: int, optional
        +            Opt-in publication threshold for completed Function outputs. Must
        +            be greater than zero. None keeps whole-fragment publication. The
        +            actual publication boundary can be larger than this threshold
        +            because it also depends on completed work and Function batching.
        +            LanceDB Enterprise only; local refreshes reject this option.
        +        total_cpu_millis: int, optional
        +            Override the total CPU budget in millicores for this refresh.
        +        total_memory_bytes: int, optional
        +            Override the total memory budget in bytes for this refresh.
        +        supervisor_resources: dict[str, int], optional
        +            CPU, memory, and ephemeral-storage limits for the Function refresh
        +            supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
        +            ``ephemeral_storage_bytes``; all are required and positive.
        +            LanceDB Enterprise only; local refreshes reject it.
        +        planning_workers: dict[str, object], optional
        +            Resources and sizing for the Function refresh planning fleet.
        +            ``resources`` has the same keys as ``supervisor_resources``; the
        +            other keys are ``max_workers``, ``rows_per_worker`` and
        +            ``fragments_per_worker``. LanceDB Enterprise only; local refreshes
        +            reject it.
                 gpu_class: str, optional
                     GPU class for Function workers. Must be a lowercase name of 1-63
                     letters, digits, or hyphens, without a leading or trailing hyphen.
                     None keeps the Function's registered class or the deployment
                     default. LanceDB Enterprise only.
        -        gpu_count: int, optional
        -            Positive aggregate GPU budget for Function workers. None leaves
        -            the server's configured budget unchanged. LanceDB Enterprise
        -            only.
        +        total_gpu_count: int, optional
        +            Nonnegative total GPU budget for Function workers without changing
        +            the other resource limits. Unspecified resources inherit column defaults,
        +            then Function defaults, then deployment defaults. LanceDB Enterprise only.
        +        retry_policy: FunctionRetryPolicy, optional
        +            Override retries of failed user-code calls. Only use when repeating
        +            partial work is safe. Set max_attempts=1 to disable retries.
        +            Enterprise Functions only; local refreshes reject this option.
        +        error_policy: {"fail", "skip"}, optional
        +            Action after failure or retry exhaustion. Skip records the error
        +            and attempt count, subject to the server's failure limits.
        +            Workflow version 1 servers default to skip with a 5% failure ceiling
        +            and publish successful output before reporting a threshold failure.
        +            Older deployments retain their existing defaults.
        +        max_failed_fraction: float, optional
        +            Under a skip policy, fail the job once more than this share of
        +            rows (0 to 1) has failed. LanceDB Enterprise only.
        +        max_failed_rows: int, optional
        +            Under a skip policy, fail the job once more than this many rows
        +            have failed. LanceDB Enterprise only.
        +        row_timeout_seconds: float, optional
        +            Deadline for one Function call. LanceDB Enterprise only.
        +        init_timeout_seconds: float, optional
        +            Deadline for Function initialization. LanceDB Enterprise only.
        +        num_workers: int, optional
        +            Worker count for an expression column; registered Function
        +            columns reject it and set the corresponding ``total_*`` options. LanceDB
        +            Enterprise only.
        +        max_job_attempts: int, optional
        +            Total automatic Function refresh attempts, including the initial job.
        +            Set to 1 to disable automatic job recovery.
        +        max_executor_processes_per_worker: int, optional
        +            Cap on executor processes per Function worker. LanceDB
        +            Enterprise only.
        +        retry_errors: bool, default False
        +            Select current failed rows on the server. Cannot be combined with
        +            ``where``. Requires Enterprise workflow version 1 or later.
        +        retry_job_id: str, optional
        +            Restrict a failed-row retry to errors recorded by this job.
        +        retry_error_type: str, optional
        +            Restrict a failed-row retry to this exception class.
        +        include_quarantined: bool, default False
        +            Explicitly release and include quarantined rows in a failed-row retry.
        +        function_version: str, optional
        +            Atomically rebind this column's Function to the specified immutable
        +            version. Requires Enterprise workflow version 1 or later.
        +        recompute: {"failed", "all", "none"}, optional
        +            Which rows to recompute during an upgrade. Requires
        +            ``function_version``; the default is ``all``. ``failed`` selects
        +            current failures, and ``none`` preserves existing values. Quarantined
        +            rows stay excluded unless explicitly included in a failed-row retry.
         
                 Returns
                 -------
        @@ -7893,11 +9891,43 @@ class AsyncTable:
                 >>> asyncio.run(refresh_in_background())  # doctest: +SKIP
                 'finished'
                 """
        +        _resource_options(
        +            total_cpu_millis,
        +            total_memory_bytes,
        +            total_gpu_count,
        +            gpu_class=gpu_class,
        +            gpu_count=gpu_count,
        +        )
                 return _typed_job(
                     await self._inner.refresh_column_async(
                         column,
        +                where=where,
                         batch_size=batch_size,
        +                max_concurrency=max_concurrency,
        +                publication_interval_rows=publication_interval_rows,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                supervisor_resources=supervisor_resources,
        +                planning_workers=planning_workers,
                         gpu_class=gpu_class,
        +                total_gpu_count=total_gpu_count,
        +                retry_policy=None
        +                if retry_policy is None
        +                else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(),
        +                error_policy=error_policy,
        +                max_failed_fraction=max_failed_fraction,
        +                max_failed_rows=max_failed_rows,
        +                row_timeout_seconds=row_timeout_seconds,
        +                init_timeout_seconds=init_timeout_seconds,
        +                num_workers=num_workers,
        +                max_job_attempts=max_job_attempts,
        +                max_executor_processes_per_worker=max_executor_processes_per_worker,
        +                retry_errors=retry_errors,
        +                retry_job_id=retry_job_id,
        +                retry_error_type=retry_error_type,
        +                include_quarantined=include_quarantined,
        +                function_version=function_version,
        +                recompute=recompute,
                         gpu_count=gpu_count,
                     ),
                     RefreshColumnJobResult.from_json,
        @@ -7973,6 +10003,10 @@ class AsyncTable:
                 """
                 return await self._inner.version()
         
        +    async def _checkout_current(self) -> "AsyncTable":
        +        """Return an independent handle pinned to the currently selected snapshot."""
        +        return AsyncTable(await self._inner._checkout_current())
        +
             async def list_versions(self):
                 """
                 List all versions of the table
        @@ -7988,6 +10022,20 @@ class AsyncTable:
         
                 return versions
         
        +    async def delta(
        +        self,
        +        from_version: int | str,
        +        to_version: Optional[int | str] = None,
        +    ) -> "AsyncTableDelta":
        +        """Compare two versions or tags.
        +
        +        See [Table.delta][lancedb.table.Table.delta] for endpoint, stable-row-id,
        +        and branch-tag semantics. The returned
        +        [AsyncTableDelta][lancedb.table.AsyncTableDelta] streams
        +        ``AsyncRecordBatchReader`` values.
        +        """
        +        return AsyncTableDelta(await self._inner.delta(from_version, to_version))
        +
             async def checkout(self, version: int | str):
                 """
                 Checks out a specific version of the Table
        @@ -8009,6 +10057,12 @@ class AsyncTable:
                 out state. To return the table to a normal state use
                 `[Self::checkout_latest]`.
         
        +        For Enterprise tables, a tag must belong to this handle's current branch.
        +        To read a tag on another branch, first obtain that branch's handle with
        +        `await table.branches.checkout("branch_name")`, then call
        +        `await branch_table.checkout(tag)` on that handle. A tag on another
        +        branch raises an error without changing the current selection.
        +
                 Parameters
                 ----------
                 version: int | str,
        @@ -8051,7 +10105,11 @@ class AsyncTable:
                 await self._inner.restore(version)
         
             def take_offsets(
        -        self, offsets: list[int], *, with_row_id: bool = False
        +        self,
        +        offsets: list[int],
        +        *,
        +        with_row_id: bool = False,
        +        preserve_order: bool = False,
             ) -> AsyncTakeQuery:
                 """
                 Take a list of offsets from the table.
        @@ -8063,8 +10121,12 @@ class AsyncTable:
                 Offsets are mostly useful for sampling as the set of all valid offsets is easily
                 known in advance to be [0, len(table)).
         
        -        No guarantees are made regarding the order in which results are returned.
        -        Repeated offsets produce repeated rows.
        +        By default, no guarantees are made regarding the order in which results
        +        are returned. Repeated offsets produce repeated rows. Set
        +        ``preserve_order=True`` to return found rows in input order, including
        +        repeated offsets. Missing non-negative offsets are omitted. Negative
        +        offsets are rejected and are not Python-style relative indices.
        +        ``preserve_order`` cannot be combined with an explicit ``order_by``.
         
                 Parameters
                 ----------
        @@ -8072,6 +10134,10 @@ class AsyncTable:
                     The offsets to take.
                 with_row_id: bool, default False
                     If True, include the "_rowid" column in the results.
        +        preserve_order: bool, default False
        +            If True, return found rows in input order. Rust take queries apply
        +            limit/offset after restoration; Python take builders and Query
        +            conversion do not expose pagination.
         
                 Returns
                 -------
        @@ -8080,6 +10146,8 @@ class AsyncTable:
                     offsets.
                 """
                 query = AsyncTakeQuery(self._inner.take_offsets(offsets), self)
        +        if preserve_order:
        +            query._inner.preserve_order()
                 if with_row_id:
                     query.with_row_id()
                 return query
        @@ -8090,6 +10158,9 @@ class AsyncTable:
                 """
                 Take a list of row ids from the table.
         
        +        Results follow the requested row-id order. Repeated IDs produce repeated
        +        rows; missing or deleted IDs are omitted. This also applies to remote tables.
        +
                 Row ids are not stable and are relative to the current version of the table.
                 They can change due to compaction and updates.
         
        @@ -8128,8 +10199,12 @@ class AsyncTable:
                 column: str,
                 row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
             ) -> pa.LargeBinaryArray:
        +        selection = _normalize_blob_row_ids(row_ids, column)
                 return await self._inner.fetch_blobs(
        -            column, _normalize_blob_row_ids(row_ids, column)
        +            column,
        +            selection.row_ids,
        +            version=selection.version,
        +            snapshot_identity=selection.snapshot_identity,
                 )
         
             async def fetch_blob_ranges(
        @@ -8137,32 +10212,54 @@ class AsyncTable:
                 column: str,
                 requests: Sequence[Sequence[int]],
             ) -> pa.LargeBinaryArray:
        +        """Materialize row-specific byte ranges.
        +
        +        See [Table.fetch_blob_ranges][lancedb.table.Table.fetch_blob_ranges].
        +        """
                 return await self._inner.fetch_blob_ranges(column, list(requests))
         
             async def fetch_blob_files(
                 self,
                 column: str,
                 row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
        +        *,
        +        buffer_size: Optional[int] = None,
             ) -> "list[Optional[BlobFile]]":
        +        """Open handles with configurable read-ahead.
        +
        +        See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files].
        +        """
        +        buffer_size = _validate_blob_buffer_size(buffer_size)
        +        selection = _normalize_blob_row_ids(row_ids, column)
                 handles = await self._inner.fetch_blob_files(
        -            column, _normalize_blob_row_ids(row_ids, column)
        +            column,
        +            selection.row_ids,
        +            buffer_size=buffer_size,
        +            version=selection.version,
        +            snapshot_identity=selection.snapshot_identity,
                 )
                 return _wrap_blob_files(handles)
         
             async def open_blob_file(
        -        self, descriptor: Union[dict, pa.StructScalar, None]
        +        self,
        +        descriptor: Union[dict, pa.StructScalar, None],
        +        *,
        +        buffer_size: Optional[int] = None,
             ) -> Optional[BlobFile]:
                 """Open a snapshot-bound descriptor as a seekable file.
         
                 See [Table.open_blob_file][lancedb.table.Table.open_blob_file].
                 """
        +        buffer_size = _validate_blob_buffer_size(buffer_size)
                 descriptor = _normalize_blob_descriptor(descriptor)
                 if descriptor is None:
                     return None
        -        return BlobFile(await self._inner.open_blob_file(json.dumps(descriptor)))
        +        return BlobFile(
        +            await self._inner.open_blob_file(json.dumps(descriptor), buffer_size)
        +        )
         
             async def open_blob_files(
        -        self, descriptors: Iterable
        +        self, descriptors: Iterable, *, buffer_size: Optional[int] = None
             ) -> AsyncIterator[Optional[BlobFile]]:
                 """Asynchronously iterate over files in descriptor order, preserving nulls.
         
        @@ -8177,7 +10274,7 @@ class AsyncTable:
                 ```
                 """
                 for descriptor in descriptors:
        -            yield await self.open_blob_file(descriptor)
        +            yield await self.open_blob_file(descriptor, buffer_size=buffer_size)
         
             @property
             def tags(self) -> AsyncTags:
        @@ -8210,6 +10307,38 @@ class AsyncTable:
                 """The branch this table handle is scoped to, or ``None`` for ``main``."""
                 return self._inner.current_branch()
         
        +    async def explain_cleanup(
        +        self, *, min_age_seconds: Optional[int] = None
        +    ) -> CleanupPlan:
        +        """Read-only preview; see Table.explain_cleanup."""
        +        _validate_min_age_seconds(min_age_seconds)
        +        return CleanupPlan.from_json(await self._inner.explain_cleanup(min_age_seconds))
        +
        +    async def cleanup_async(
        +        self, *, min_age_seconds: Optional[int] = None
        +    ) -> AsyncJob[CleanupResult]:
        +        """Submit cleanup. See
        +
        +        [Table.cleanup_async][lancedb.table.Table.cleanup_async].
        +        """
        +        _validate_min_age_seconds(min_age_seconds)
        +        return _typed_job(
        +            await self._inner.cleanup_async(min_age_seconds), CleanupResult.from_json
        +        )
        +
        +    async def compact_async(
        +        self, *, compaction_options: Optional[CompactionOptions] = None
        +    ) -> AsyncJob[CompactionResult]:
        +        """Submit remote compaction; await the returned job for actual results.
        +
        +        See [Table.compact_async][lancedb.table.Table.compact_async] for options,
        +        permissions, completion semantics and compatibility requirements.
        +        """
        +        return _typed_job(
        +            await self._inner.compact_async(compaction_options),
        +            CompactionResult.from_json,
        +        )
        +
             async def optimize(
                 self,
                 *,
        @@ -8228,9 +10357,13 @@ class AsyncTable:
                     are silently skipped there instead of being attempted, so this
                     call returns successfully, with zeroed pruning statistics, once
                     the compaction job has been submitted; it does not wait for that
        -            job to finish. A non-default ``compaction_options`` raises
        -            ``NotImplementedError`` before anything is submitted, since
        -            there is no way yet to forward those settings to the server.
        +            job to finish. Remote compaction supports per-job
        +            ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``,
        +            and ``batch_size``. Omitted fields inherit table tuning, then
        +            deployment/built-in defaults. Other non-default compaction settings raise
        +            ``NotImplementedError`` before submission. The server must support
        +            these SQL options; older-server errors are propagated without
        +            dropping the requested settings.
         
                 Modeled after ``VACUUM`` in PostgreSQL.
         
        @@ -8442,6 +10575,8 @@ class IndexStatistics:
                 "BITMAP",
                 "LABEL_LIST",
                 "NGRAM",
        +        "ZONEMAP",
        +        "RTREE",
             ]
             distance_type: Optional[Literal["l2", "cosine", "dot"]] = None
             num_indices: Optional[int] = None
        @@ -8538,6 +10673,26 @@ class FragmentSummaryStats:
             p99: int
         
         
        +def _validate_branch_source(
        +    from_ref: Optional[str],
        +    from_version: Optional[int],
        +    from_tag: Optional[str],
        +) -> None:
        +    if from_tag is None:
        +        return
        +    conflicts = [
        +        name
        +        for name, value in (("from_ref", from_ref), ("from_version", from_version))
        +        if value is not None
        +    ]
        +    if conflicts:
        +        raise ValueError(
        +            "from_tag cannot be combined with "
        +            + " or ".join(conflicts)
        +            + "; pass only one source"
        +        )
        +
        +
         class Tags:
             """
             Table tag manager.
        @@ -8568,7 +10723,7 @@ class Tags:
                 """
                 return LOOP.run(self._table.tags.get_version(tag))
         
        -    def create(self, tag: str, version: int) -> None:
        +    def create(self, tag: str, version: Optional[int] = None) -> None:
                 """
                 Create a tag for a given table version.
         
        @@ -8577,8 +10732,9 @@ class Tags:
                 tag: str,
                     The name of the tag to create. This name must be unique among all tag
                     names for the table.
        -        version: int,
        -            The table version to tag.
        +        version: int, optional
        +            The table version to tag. Defaults to the version visible to this
        +            handle, including a checked-out version.
                 """
                 LOOP.run(self._table.tags.create(tag, version))
         
        @@ -8625,6 +10781,8 @@ class Branches:
                 name: str,
                 from_ref: Optional[str] = None,
                 from_version: Optional[int] = None,
        +        *,
        +        from_tag: Optional[str] = None,
             ) -> "Table":
                 """Create a branch and return a handle scoped to it.
         
        @@ -8636,9 +10794,13 @@ class Branches:
                     Source branch to fork from. Defaults to ``main``.
                 from_version: int, optional
                     A specific version on ``from_ref`` to fork from. Defaults to latest.
        +        from_tag: str, optional
        +            Source tag to fork from. Cannot be combined with ``from_ref`` or
        +            ``from_version``.
                 """
        +        _validate_branch_source(from_ref, from_version, from_tag)
                 async_table = LOOP.run(
        -            self._table.branches.create(name, from_ref, from_version)
        +            self._table.branches.create(name, from_ref, from_version, from_tag=from_tag)
                 )
                 return self._wrap(async_table)
         
        @@ -8690,6 +10852,128 @@ class Branches:
                 return self._parent._wrap_branch_handle(async_table, version)
         
         
        +class TableDelta:
        +    """Streaming row changes between two table versions.
        +
        +    Created by [Table.delta][lancedb.table.Table.delta]. The endpoints are
        +    fixed when the delta is created.
        +
        +    Row-level readers require stable row ids at both endpoints. Create the
        +    table with ``storage_options={"new_table_enable_stable_row_ids": "true"}``
        +    to enable them. [list_transactions][lancedb.table.TableDelta.list_transactions]
        +    works without stable row ids.
        +
        +    A nonempty range that contains a ``Restore``, or whose transaction history
        +    is incomplete, rejects the row-level readers. Recompute the checkpoint with
        +    a full rescan and reinitialize it at the end version; transaction history
        +    remains available.
        +    """
        +
        +    def __init__(self, inner: Any):
        +        self._inner = inner
        +        self._async = AsyncTableDelta(inner)
        +
        +    @property
        +    def begin_version(self) -> int:
        +        """The version this delta starts from (exclusive)."""
        +        return self._inner.begin_version()
        +
        +    @property
        +    def end_version(self) -> int:
        +        """The version this delta ends at (inclusive)."""
        +        return self._inner.end_version()
        +
        +    def inserted_rows(self) -> pa.RecordBatchReader:
        +        """Stream rows inserted in ``(begin_version, end_version]``.
        +
        +        Each batch carries the table columns plus ``_rowid``,
        +        ``_row_created_at_version``, and ``_row_last_updated_at_version``.
        +        """
        +        return _record_batch_reader(LOOP.run(self._async.inserted_rows()))
        +
        +    def updated_rows(self) -> pa.RecordBatchReader:
        +        """Stream rows updated in ``(begin_version, end_version]``.
        +
        +        Newly inserted rows are excluded; use
        +        [upserted_rows][lancedb.table.TableDelta.upserted_rows] for both.
        +        """
        +        return _record_batch_reader(LOOP.run(self._async.updated_rows()))
        +
        +    def upserted_rows(self) -> pa.RecordBatchReader:
        +        """Stream inserted and updated rows in ``(begin_version, end_version]``."""
        +        return _record_batch_reader(LOOP.run(self._async.upserted_rows()))
        +
        +    def deleted_row_ids(self) -> pa.RecordBatchReader:
        +        """Stream the ``_rowid`` values of rows deleted in the range.
        +
        +        Each batch carries one ``_rowid`` column of type ``uint64``. Deleted
        +        rows are not reconstructed from earlier versions.
        +        """
        +        return _record_batch_reader(LOOP.run(self._async.deleted_row_ids()))
        +
        +    def list_transactions(self) -> List[Dict[str, Any]]:
        +        """List transactions committed in ``(begin_version, end_version]``.
        +
        +        Each item has ``read_version``, ``uuid``, ``operation``, ``tag``, and
        +        ``transaction_properties``. Unlike row readers, this works without
        +        stable row ids.
        +        """
        +        return LOOP.run(self._async.list_transactions())
        +
        +
        +class AsyncTableDelta:
        +    """Async streaming row changes between two table versions.
        +
        +    Created by [AsyncTable.delta][lancedb.table.AsyncTable.delta]. See
        +    [TableDelta][lancedb.table.TableDelta] for the endpoint and stable-row-id
        +    contract.
        +    """
        +
        +    def __init__(self, inner: Any):
        +        self._inner = inner
        +
        +    @property
        +    def begin_version(self) -> int:
        +        """The version this delta starts from (exclusive)."""
        +        return self._inner.begin_version()
        +
        +    @property
        +    def end_version(self) -> int:
        +        """The version this delta ends at (inclusive)."""
        +        return self._inner.end_version()
        +
        +    async def inserted_rows(self) -> AsyncRecordBatchReader:
        +        """Stream rows inserted in ``(begin_version, end_version]``."""
        +        return AsyncRecordBatchReader(await self._inner.inserted_rows())
        +
        +    async def updated_rows(self) -> AsyncRecordBatchReader:
        +        """Stream rows updated in ``(begin_version, end_version]``."""
        +        return AsyncRecordBatchReader(await self._inner.updated_rows())
        +
        +    async def upserted_rows(self) -> AsyncRecordBatchReader:
        +        """Stream inserted and updated rows in ``(begin_version, end_version]``."""
        +        return AsyncRecordBatchReader(await self._inner.upserted_rows())
        +
        +    async def deleted_row_ids(self) -> AsyncRecordBatchReader:
        +        """Stream the ``_rowid`` values of rows deleted in the range."""
        +        return AsyncRecordBatchReader(await self._inner.deleted_row_ids())
        +
        +    async def list_transactions(self) -> List[Dict[str, Any]]:
        +        """List transactions committed in ``(begin_version, end_version]``."""
        +        return await self._inner.list_transactions()
        +
        +
        +def _record_batch_reader(stream) -> pa.RecordBatchReader:
        +    def iter_sync():
        +        try:
        +            while True:
        +                yield LOOP.run(stream.__anext__())
        +        except StopAsyncIteration:
        +            return
        +
        +    return pa.RecordBatchReader.from_batches(stream.schema, iter_sync())
        +
        +
         class AsyncTags:
             """
             Async table tag manager.
        @@ -8720,7 +11004,7 @@ class AsyncTags:
                 """
                 return await self._table.tags.get_version(tag)
         
        -    async def create(self, tag: str, version: int) -> None:
        +    async def create(self, tag: str, version: Optional[int] = None) -> None:
                 """
                 Create a tag for a given table version.
         
        @@ -8729,8 +11013,9 @@ class AsyncTags:
                 tag: str,
                     The name of the tag to create. This name must be unique among all tag
                     names for the table.
        -        version: int,
        -            The table version to tag.
        +        version: int, optional
        +            The table version to tag. Defaults to the version visible to this
        +            handle, including a checked-out version.
                 """
                 await self._table.tags.create(tag, version)
         
        @@ -8774,6 +11059,8 @@ class AsyncBranches:
                 name: str,
                 from_ref: Optional[str] = None,
                 from_version: Optional[int] = None,
        +        *,
        +        from_tag: Optional[str] = None,
             ) -> "AsyncTable":
                 """Create a branch and return a handle scoped to it.
         
        @@ -8785,12 +11072,19 @@ class AsyncBranches:
                     Source branch to fork from. Defaults to ``main``.
                 from_version: int, optional
                     A specific version on ``from_ref`` to fork from. Defaults to latest.
        +        from_tag: str, optional
        +            Source tag to fork from. Cannot be combined with ``from_ref`` or
        +            ``from_version``.
                 """
        +        _validate_branch_source(from_ref, from_version, from_tag)
                 # "main" and None are two spellings of the root branch in lance; normalize
        -        # so from_ref="main" behaves identically to the default.
        +        # so from_ref="main" behaves identically to the default. This must happen
        +        # after validating from_tag conflicts so an explicit from_ref is not lost.
                 if from_ref == "main":
                     from_ref = None
        -        inner = await self._table.branches.create(name, from_ref, from_version)
        +        inner = await self._table.branches.create(
        +            name, from_ref, from_version, from_tag=from_tag
        +        )
                 return AsyncTable(inner)
         
             async def checkout(self, name: str, version: Optional[int] = None) -> "AsyncTable":
        diff --git a/python/python/lancedb/types.py b/python/python/lancedb/types.py
        index 3d7168dcf..7684398c2 100644
        --- a/python/python/lancedb/types.py
        +++ b/python/python/lancedb/types.py
        @@ -52,6 +52,7 @@ IndexType = Literal[
             "BITMAP",
             "LABEL_LIST",
             "NGRAM",
        +    "RTREE",
             "IVF_RQ",
         ]
         
        diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py
        index c37edcc6a..d8f846e24 100644
        --- a/python/python/lancedb/util.py
        +++ b/python/python/lancedb/util.py
        @@ -8,9 +8,11 @@ import importlib
         import math
         import os
         import pathlib
        +import sys
         import warnings
         from datetime import date, datetime, time, timedelta
         from decimal import Decimal
        +from enum import Enum
         from functools import singledispatch
         from typing import Tuple, Union, Optional, Any, List
         from urllib.parse import urlparse
        @@ -328,7 +330,7 @@ def _query_vector_dim(query: Optional[Any]) -> Optional[int]:
         
         
         def infer_vector_column_name(
        -    schema: pa.Schema,
        +    schema: Optional[pa.Schema],
             query_type: str,
             query: Optional[Any],  # inferred later in query builder
             vector_column_name: Optional[str],
        @@ -348,6 +350,8 @@ def infer_vector_column_name(
                 # nothing to infer.
                 return None
         
        +    if schema is None:
        +        raise ValueError("schema is required to infer a vector column")
             vector_column_name = inf_vector_column_query(schema, dim=_query_vector_dim(query))
         
             if vector_column_name is None:
        @@ -382,7 +386,8 @@ def _(value: bytes):
         
         @value_to_sql.register(int)
         def _(value: int):
        -    return str(value)
        +    # int() first: str() of an int-valued Enum member is its name, e.g. "P.HIGH".
        +    return str(int(value))
         
         
         @value_to_sql.register(float)
        @@ -394,7 +399,7 @@ def _(value: float):
                 return (
                     "CAST('Infinity' AS DOUBLE)" if value > 0 else "CAST('-Infinity' AS DOUBLE)"
                 )
        -    return str(value)
        +    return str(float(value))
         
         
         @value_to_sql.register(Decimal)
        @@ -415,6 +420,12 @@ def _(value: type(None)):
             return "NULL"
         
         
        +@value_to_sql.register(Enum)
        +def _(value: Enum):
        +    # Write the member's value, as model_to_dict does for a LanceModel field.
        +    return value_to_sql(value.value)
        +
        +
         @value_to_sql.register(datetime)
         def _(value: datetime):
             return f"'{value.isoformat()}'"
        @@ -601,15 +612,253 @@ def tbl_to_tensor(tbl: pa.Table):
             return torch.stack([to_tensor(tbl.column(i)) for i in range(tbl.num_columns)])
         
         
        +_BFLOAT16_EXTENSION_NAME = "lance.bfloat16"
        +_ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name"
        +
        +
        +def _field_metadata_value(field: pa.Field, key: str):
        +    metadata = field.metadata or {}
        +    value = metadata.get(key.encode()) or metadata.get(key)
        +    if isinstance(value, bytes):
        +        return value.decode()
        +    return value
        +
        +
        +def _field_extension_name(field: pa.Field) -> Optional[str]:
        +    extension_name = _field_metadata_value(field, _ARROW_EXTENSION_NAME_KEY)
        +    if extension_name is not None:
        +        return extension_name
        +    if isinstance(field.type, pa.ExtensionType):
        +        return field.type.extension_name
        +    return None
        +
        +
        +def _field_storage_type(field: pa.Field) -> pa.DataType:
        +    if isinstance(field.type, pa.ExtensionType):
        +        return field.type.storage_type
        +    return field.type
        +
        +
        +def _is_bfloat16_field(field: pa.Field) -> bool:
        +    if _field_extension_name(field) != _BFLOAT16_EXTENSION_NAME:
        +        return False
        +    storage_type = _field_storage_type(field)
        +    return pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
        +
        +
        +def _check_torch_nulls(array: pa.Array, column_name: str) -> None:
        +    if array.null_count:
        +        raise ValueError(
        +            f"Cannot convert column `{column_name}` to a torch tensor because it "
        +            f"contains {array.null_count} null value(s). Drop or fill nulls before "
        +            "using a torch format."
        +        )
        +
        +
        +def _bfloat16_to_tensor(array: pa.Array, torch, column_name: str):
        +    storage = array.storage if isinstance(array.type, pa.ExtensionType) else array
        +    storage_type = storage.type
        +    if not (
        +        pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
        +    ):
        +        raise ValueError(
        +            f"Column `{column_name}` is marked as {_BFLOAT16_EXTENSION_NAME!r} but "
        +            f"has storage type {storage_type}. The lance.bfloat16 extension requires "
        +            "fixed_size_binary[2] storage."
        +        )
        +    _check_torch_nulls(storage, column_name)
        +    if len(storage) == 0:
        +        return torch.empty((0,), dtype=torch.bfloat16)
        +
        +    buffer = storage.buffers()[1]
        +    if buffer is None:
        +        return torch.empty((0,), dtype=torch.bfloat16)
        +    offset = storage.offset * 2
        +    byte_length = len(storage) * 2
        +    if buffer.size < offset + byte_length:
        +        raise ValueError(
        +            f"Column `{column_name}` has a truncated bfloat16 value buffer."
        +        )
        +
        +    # Arrow stores bfloat16 as two little-endian bytes. Copy only on big-endian
        +    # hosts before viewing the same bits as torch.bfloat16.
        +    values = np.frombuffer(
        +        buffer, dtype=np.dtype(" bool:
        +    data_type = array.type
        +    if isinstance(data_type, pa.ExtensionType) or array.null_count == 0:
        +        return False
        +    return pa.types.is_integer(data_type) or pa.types.is_floating(data_type)
        +
        +
        +def _nullable_numeric_scalar_to_tensor(array: pa.Array, torch, column_name: str):
        +    try:
        +        numpy_values = array.to_numpy(zero_copy_only=False)
        +    except pa.ArrowInvalid as err:
        +        raise ValueError(
        +            f"Cannot convert nullable column `{column_name}` of type {array.type} "
        +            f"to a torch tensor: {err}"
        +        ) from err
        +    try:
        +        return torch.from_numpy(numpy_values)
        +    except (TypeError, RuntimeError) as err:
        +        raise ValueError(
        +            f"Cannot convert nullable column `{column_name}` of type {array.type} "
        +            f"to a torch tensor: {err}"
        +        ) from err
        +
        +
        +def _batch_column_tensors(batch: pa.RecordBatch, allow_scalar_nulls: bool = False):
        +    torch = attempt_import_or_raise("torch", "torch")
        +    columns = []
        +    for field, column in zip(batch.schema, batch.columns):
        +        if allow_scalar_nulls and _is_nullable_numeric_scalar(column):
        +            tensor = _nullable_numeric_scalar_to_tensor(column, torch, field.name)
        +        else:
        +            tensor = _arrow_column_to_tensor(column, field, torch, field.name)
        +        columns.append((field.name, tensor))
        +    return torch, columns
        +
        +
        +def _uniform_column_tensors(
        +    batch: pa.RecordBatch, format_name: str, allow_scalar_nulls: bool = False
        +):
        +    torch, columns = _batch_column_tensors(batch, allow_scalar_nulls=allow_scalar_nulls)
        +    if len(columns) <= 1:
        +        return torch, columns
        +
        +    first_name, first = columns[0]
        +    first_shape = tuple(first.shape[1:])
        +    for name, tensor in columns[1:]:
        +        shape = tuple(tensor.shape[1:])
        +        if shape != first_shape:
        +            raise ValueError(
        +                f"Cannot use the {format_name!r} format because column `{name}` "
        +                f"has sample shape {shape} while column `{first_name}` has sample "
        +                f'shape {first_shape}. Use with_format("torch_dict") for columns '
        +                'with different shapes, or with_format("torch") for a list of '
        +                "per-row dicts."
        +            )
        +    return torch, columns
        +
        +
         def batch_to_tensor(batch: pa.RecordBatch):
             """
             Convert a PyArrow RecordBatch to a PyTorch Tensor.
         
        -    Each column is converted to a tensor (using zero-copy via DLPack)
        -    and the columns are then stacked into a single tensor.
        +    Each column is converted to a tensor with shape ``(rows, *sample_shape)``
        +    and the columns are stacked along a new leading dimension. Scalar columns
        +    have sample shape ``()`` and fixed-size-list columns contribute each list
        +    dimension. All columns must have the same sample shape.
         
             Fails if torch is not installed.
             Fails if a column's data type is not supported by PyTorch.
        +    Fails if a column contains nulls.
         
             Parameters
             ----------
        @@ -618,43 +867,99 @@ def batch_to_tensor(batch: pa.RecordBatch):
         
             Returns
             -------
        -    torch.Tensor: The tensor containing the columns of the record batch.
        +    torch.Tensor: A tensor with shape ``(columns, rows, *sample_shape)``. A
        +        one-column batch returns an ``unsqueeze(0)`` view of that column.
             """
        -    torch = attempt_import_or_raise("torch", "torch")
        -    return torch.stack([torch.from_dlpack(col) for col in batch.columns])
        +    torch, columns = _uniform_column_tensors(batch, "torch_col")
        +    if not columns:
        +        return torch.empty((0, batch.num_rows))
        +    if len(columns) == 1:
        +        return columns[0][1].unsqueeze(0)
        +    return torch.stack([tensor for _, tensor in columns], dim=0)
         
         
         def batch_to_tensor_rows(batch: pa.RecordBatch):
             """
        -    Convert a PyArrow RecordBatch to a list of PyTorch Tensor, one per row
        +    Convert a PyArrow RecordBatch to a list of PyTorch Tensors, one per row.
         
        -    Each column is converted to a tensor (using zero-copy via DLPack)
        -    and the columns are then stacked into a single tensor.  The 2D tensor
        -    is then converted to a list of tensors, one per row
        +    Each row tensor has shape ``(columns, *sample_shape)``. All columns must
        +    have the same sample shape, so a table mixing scalar and vector columns
        +    should use ``torch_dict`` or ``torch`` instead. Dtypes are combined with
        +    ``torch.promote_types``, matching PyTorch's numeric promotion rules.
         
        -    Fails if torch or numpy is not installed.
        +    Fails if torch is not installed.
             Fails if a column's data type is not supported by PyTorch.
        +    Nulls in ordinary integer or floating scalar columns become ``NaN``.
        +    Nulls in nested fixed-size-list or tensor columns are rejected.
        +
        +    Parameters
        +    ----------
        +    batch : pa.RecordBatch
        +        The record batch to convert.
        +
        +    Returns
        +    -------
        +    list[torch.Tensor]
        +        One tensor per row, each with shape ``(columns, *sample_shape)``. A
        +        one-column scalar batch produces ``(1,)`` tensors.
             """
        -    torch = attempt_import_or_raise("torch", "torch")
        -    numpy = attempt_import_or_raise("numpy", "numpy")
        -    columns = [col.to_numpy(zero_copy_only=False) for col in batch.columns]
        -    stacked = torch.tensor(numpy.column_stack(columns))
        -    rows = list(stacked.unbind(dim=0))
        -    return rows
        +    torch, columns = _uniform_column_tensors(
        +        batch, "torch_row", allow_scalar_nulls=True
        +    )
        +    if not columns:
        +        return [torch.empty((0,)) for _ in range(batch.num_rows)]
        +
        +    dtype = columns[0][1].dtype
        +    for _, tensor in columns[1:]:
        +        dtype = torch.promote_types(dtype, tensor.dtype)
        +    tensors = [
        +        tensor if tensor.dtype == dtype else tensor.to(dtype) for _, tensor in columns
        +    ]
        +    stacked = torch.stack(tensors, dim=1)
        +    return list(stacked.unbind(dim=0))
        +
        +
        +def batch_to_tensor_columns(batch: pa.RecordBatch):
        +    """
        +    Convert a PyArrow RecordBatch to a dict of per-column PyTorch Tensors.
        +
        +    Each tensor has shape ``(rows, *sample_shape)`` and shares Arrow storage
        +    where the layout allows it. Unlike ``torch_col`` and ``torch_row``, columns
        +    may have different sample shapes. This is the transform behind
        +    ``Permutation.with_format("torch_dict")`` and can be consumed directly by
        +    a ``DataLoader`` with an identity ``collate_fn``.
        +
        +    Fails if torch is not installed.
        +    Fails if a column's data type is not supported by PyTorch.
        +    Fails if a column contains nulls.
        +
        +    Parameters
        +    ----------
        +    batch : pa.RecordBatch
        +        The record batch to convert.
        +
        +    Returns
        +    -------
        +    dict[str, torch.Tensor]
        +        A tensor per column, each with shape ``(rows, *sample_shape)``.
        +    """
        +    _, columns = _batch_column_tensors(batch)
        +    return dict(columns)
         
         
         def batch_to_tensor_dict(batch: pa.RecordBatch):
             """
             Convert a PyArrow RecordBatch to a list of per-row dicts of PyTorch Tensors.
         
        -    Each column is first converted to a 1-D tensor (zero-copy via DLPack), then
        -    sliced per row. The result is a list whose length is ``batch.num_rows`` and
        -    whose items are dicts keyed by column name. This shape composes directly
        -    with PyTorch's default ``DataLoader`` collate, which stacks the per-row
        -    dicts back into a dict of batched tensors.
        +    Each column is converted to a tensor with shape ``(rows, *sample_shape)``,
        +    then sliced per row. The result is a list whose length is
        +    ``batch.num_rows`` and whose items are dicts keyed by column name. This
        +    shape composes directly with PyTorch's default ``DataLoader`` collate,
        +    which stacks the per-row dicts back into a dict of batched tensors.
         
             Fails if torch is not installed.
             Fails if a column's data type is not supported by PyTorch.
        +    Fails if a column contains nulls.
         
             Parameters
             ----------
        @@ -665,14 +970,9 @@ def batch_to_tensor_dict(batch: pa.RecordBatch):
             -------
             list[dict[str, torch.Tensor]]
                 One per-row dict per row in the batch. Each dict maps column name to a
        -        0-D tensor view into the column.
        +        tensor view into the column.
             """
        -    torch = attempt_import_or_raise("torch", "torch")
        -    tensors = {
        -        name: torch.from_dlpack(col)
        -        for name, col in zip(batch.schema.names, batch.columns)
        -    }
        +    _, columns = _batch_column_tensors(batch)
             return [
        -        {name: tensor[i] for name, tensor in tensors.items()}
        -        for i in range(batch.num_rows)
        +        {name: tensor[i] for name, tensor in columns} for i in range(batch.num_rows)
             ]
        diff --git a/python/python/tests/test_background_loop.py b/python/python/tests/test_background_loop.py
        new file mode 100644
        index 000000000..8a3a2c247
        --- /dev/null
        +++ b/python/python/tests/test_background_loop.py
        @@ -0,0 +1,247 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import os
        +import subprocess
        +import sys
        +import textwrap
        +
        +import pytest
        +
        +
        +BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop"
        +
        +
        +def _run_in_subprocess(code: str, timeout: int = 30) -> subprocess.CompletedProcess:
        +    env = os.environ.copy()
        +    env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path)
        +    return subprocess.run(
        +        [sys.executable, "-c", textwrap.dedent(code)],
        +        check=False,
        +        capture_output=True,
        +        text=True,
        +        env=env,
        +        timeout=timeout,
        +    )
        +
        +
        +def _assert_subprocess_ok(result: subprocess.CompletedProcess) -> None:
        +    assert result.returncode == 0, result.stderr or result.stdout
        +
        +
        +def test_import_and_inspection_do_not_start_background_loop():
        +    result = _run_in_subprocess(
        +        f"""
        +        import threading
        +
        +        import lancedb
        +        from lancedb.background_loop import BackgroundEventLoop, LOOP
        +
        +        def background_threads():
        +            return [
        +                thread
        +                for thread in threading.enumerate()
        +                if thread.name == {BACKGROUND_THREAD_NAME!r}
        +            ]
        +
        +        assert LOOP.thread is None
        +        assert LOOP.loop is None
        +        assert background_threads() == []
        +
        +        # Inspecting a fresh instance is also side-effect free.
        +        loop = BackgroundEventLoop()
        +        assert loop.thread is None
        +        assert loop.loop is None
        +        assert background_threads() == []
        +        """
        +    )
        +    _assert_subprocess_ok(result)
        +
        +
        +def test_first_sync_call_starts_one_daemon_thread():
        +    result = _run_in_subprocess(
        +        f"""
        +        import threading
        +
        +        import lancedb
        +        from lancedb.background_loop import LOOP
        +
        +        def background_threads():
        +            return [
        +                thread
        +                for thread in threading.enumerate()
        +                if thread.name == {BACKGROUND_THREAD_NAME!r}
        +            ]
        +
        +        assert LOOP.thread is None
        +        assert LOOP.loop is None
        +
        +        db = lancedb.connect("memory://")
        +        assert db.table_names() == []
        +
        +        worker = LOOP.thread
        +        assert worker is not None
        +        assert worker is background_threads()[0]
        +        assert len(background_threads()) == 1
        +        assert worker.daemon
        +        assert worker.is_alive()
        +        assert LOOP.loop is not None
        +        """
        +    )
        +    _assert_subprocess_ok(result)
        +
        +
        +def test_concurrent_first_use_initializes_one_background_thread():
        +    result = _run_in_subprocess(
        +        f"""
        +        import asyncio
        +        import threading
        +
        +        from lancedb.background_loop import LOOP
        +
        +        worker_count = 8
        +        barrier = threading.Barrier(worker_count)
        +        results = []
        +        errors = []
        +        results_lock = threading.Lock()
        +
        +        def submit(index):
        +            try:
        +                barrier.wait(timeout=10)
        +                value = LOOP.run(asyncio.sleep(0.05, result=index))
        +                with results_lock:
        +                    results.append(value)
        +            except BaseException as exc:
        +                with results_lock:
        +                    errors.append(repr(exc))
        +
        +        threads = [
        +            threading.Thread(target=submit, args=(index,))
        +            for index in range(worker_count)
        +        ]
        +        for thread in threads:
        +            thread.start()
        +        for thread in threads:
        +            thread.join(timeout=20)
        +
        +        assert all(not thread.is_alive() for thread in threads)
        +        assert errors == []
        +        assert sorted(results) == list(range(worker_count))
        +
        +        background_threads = [
        +            thread
        +            for thread in threading.enumerate()
        +            if thread.name == {BACKGROUND_THREAD_NAME!r}
        +        ]
        +        assert len(background_threads) == 1
        +        assert background_threads[0].daemon
        +        """
        +    )
        +    _assert_subprocess_ok(result)
        +
        +
        +@pytest.mark.skipif(
        +    sys.platform != "linux",
        +    reason=(
        +        "fork() is unavailable on Windows and unsafe on macOS "
        +        "(Apple frameworks/TLS are not fork-safe)"
        +    ),
        +)
        +def test_forked_child_starts_background_loop_lazily():
        +    # Fork from a fresh interpreter: earlier tests in a shared pytest process
        +    # may have left native runtime state that is not part of this scenario.
        +    result = _run_in_subprocess(
        +        f"""
        +        import asyncio
        +        import multiprocessing as mp
        +        import threading
        +        import traceback
        +
        +        from lancedb.background_loop import LOOP
        +
        +        BACKGROUND_THREAD_NAME = {BACKGROUND_THREAD_NAME!r}
        +
        +        def background_threads():
        +            return [
        +                thread
        +                for thread in threading.enumerate()
        +                if thread.name == BACKGROUND_THREAD_NAME
        +            ]
        +
        +        def fork_child(queue):
        +            try:
        +                from lancedb.background_loop import LOOP
        +
        +                inherited_thread_is_none = LOOP.thread is None
        +                inherited_loop_is_none = LOOP.loop is None
        +                background_threads_before = [
        +                    thread.name for thread in background_threads()
        +                ]
        +
        +                import lancedb
        +
        +                db = lancedb.connect("memory://")
        +                tables = db.table_names()
        +
        +                worker = LOOP.thread
        +                queue.put(
        +                    dict(
        +                        error=None,
        +                        inherited_thread_is_none=inherited_thread_is_none,
        +                        inherited_loop_is_none=inherited_loop_is_none,
        +                        background_threads_before=background_threads_before,
        +                        tables=tables,
        +                        thread_alive=False if worker is None else worker.is_alive(),
        +                        thread_daemon=False if worker is None else worker.daemon,
        +                        background_thread_count=len(background_threads()),
        +                    )
        +                )
        +            except BaseException:
        +                queue.put(dict(error=traceback.format_exc()))
        +
        +        assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before"
        +        parent_thread = LOOP.thread
        +        assert parent_thread is not None
        +
        +        ctx = mp.get_context("fork")
        +        queue = ctx.Queue()
        +
        +        # Simulate forking while another thread held the initialization lock. The
        +        # child must replace the inherited lock instead of trying to acquire it.
        +        LOOP._start_lock.acquire()
        +        try:
        +            proc = ctx.Process(target=fork_child, args=(queue,))
        +            proc.start()
        +        finally:
        +            LOOP._start_lock.release()
        +
        +        proc.join(timeout=20)
        +        if proc.is_alive():
        +            proc.terminate()
        +            proc.join(timeout=5)
        +            if proc.is_alive():
        +                proc.kill()
        +                proc.join()
        +            raise AssertionError("Forked child hung starting the background loop")
        +
        +        assert proc.exitcode == 0, "child exited with code %s" % proc.exitcode
        +        payload = queue.get(timeout=5)
        +        queue.close()
        +        assert payload["error"] is None, payload["error"]
        +        assert payload["inherited_thread_is_none"] is True
        +        assert payload["inherited_loop_is_none"] is True
        +        assert payload["background_threads_before"] == []
        +        assert payload["tables"] == []
        +        assert payload["thread_alive"] is True
        +        assert payload["thread_daemon"] is True
        +        assert payload["background_thread_count"] == 1
        +
        +        # The child's reset must not disturb the parent's loop.
        +        assert LOOP.thread is parent_thread
        +        assert parent_thread.is_alive()
        +        assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after"
        +        """,
        +        # join(20) + terminate join(5) + queue get(5), plus startup and traceback.
        +        timeout=40,
        +    )
        +    _assert_subprocess_ok(result)
        diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py
        index ceb43522e..57dbc09ff 100644
        --- a/python/python/tests/test_blob.py
        +++ b/python/python/tests/test_blob.py
        @@ -1017,6 +1017,11 @@ def test_take_queries_honor_blob_mode():
                 1: b"one",
                 2: b"two",
             }
        +    ordered = table.take_offsets([1, 0], preserve_order=True).to_arrow(
        +        blob_mode="bytes"
        +    )
        +    assert ordered["id"].to_pylist() == [2, 1]
        +    assert ordered["image"].to_pylist() == [b"two", b"one"]
             assert [
                 row["image"] for row in table.take_row_ids([0]).to_list(blob_mode="bytes")
             ] == [b"one"]
        @@ -1070,8 +1075,10 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path):
             )
             table.add([{"id": 1, "image": b"one"}])
         
        -    with pytest.raises(NotImplementedError, match="stable table snapshot"):
        +    with pytest.raises(NotImplementedError, match="stable table snapshot") as exc:
                 table.to_arrow(blob_mode="bytes")
        +    assert "fetch_blobs(column, row_ids)" in str(exc.value)
        +    assert "with_row_id(True)" in str(exc.value)
             with pytest.raises(NotImplementedError, match="stable table snapshot"):
                 table.search().to_list(blob_mode="bytes")
             with pytest.raises(NotImplementedError, match="stable table snapshot"):
        @@ -1103,6 +1110,54 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path)
                 await table.query().to_batches(blob_mode="bytes")
         
         
        +def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
        +    rows = [
        +        {"id": 1, "image": b"one"},
        +        {"id": 2, "image": b""},
        +        {"id": 3, "image": None},
        +        {"id": 4, "image": b"excluded"},
        +    ]
        +    source = db.create_table("source", data=rows, schema=schema)
        +    hits = (
        +        source.search()
        +        .where("id < 4")
        +        .select(["id"])
        +        .with_row_id(True)
        +        .limit(100)
        +        .to_arrow()
        +    )
        +    payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist()
        +    subset = db.create_table("subset", schema=schema)
        +    subset.add(
        +        [
        +            {"id": image_id, "image": payload}
        +            for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True)
        +        ]
        +    )
        +    copied = subset.search().to_list(blob_mode="bytes")
        +    assert sorted(copied, key=lambda row: row["id"]) == rows[:3]
        +
        +
        +def test_copy_blob_descriptor_rows_explains_payload_materialization(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
        +    source = db.create_table("source", data=[{"id": 1, "image": b"one"}], schema=schema)
        +    hits = source.search().where("id = 1").to_arrow()
        +
        +    with pytest.raises(ValueError, match="must contain a 'data' or 'uri' child") as exc:
        +        db.create_table("copy", data=hits, schema=schema)
        +
        +    message = str(exc.value)
        +    assert "blob_mode='bytes'" in message
        +    assert "blob_mode='descriptions'" in message
        +    assert "with_row_id(True)" in message
        +    assert "fetch_blobs(column, row_ids)" in message
        +    assert "fetch_blob_files(column, row_ids)" in message
        +    assert not db.table_exists(["copy"])
        +
        +
         def test_fetch_blobs_round_trip():
             table = _blob_table(
                 "round_trip",
        @@ -1619,16 +1674,41 @@ def test_bytes_mode_rejects_blobs_inside_lists():
         
         
         def test_row_addressable_paths_exclude_list_children():
        -    from lancedb.schema import row_addressable_blob_v2_paths
        +    from lancedb.schema import (
        +        row_addressable_blob_paths,
        +        row_addressable_blob_v2_paths,
        +    )
         
             schema = pa.schema(
                 [
                     pa.field("id", pa.int64()),
        -            pa.field("info", pa.struct([lancedb.blob("blob")])),
        +            pa.field(
        +                "info",
        +                pa.struct(
        +                    [
        +                        lancedb.blob("blob"),
        +                        pa.field(
        +                            "legacy",
        +                            pa.large_binary(),
        +                            metadata={"lance-encoding:blob": "true"},
        +                        ),
        +                    ]
        +                ),
        +            ),
        +            pa.field(
        +                "legacy",
        +                pa.large_binary(),
        +                metadata={"lance-encoding:blob": "true"},
        +            ),
                     pa.field("images", pa.list_(lancedb.blob("image"))),
                 ]
             )
             assert blob_v2_column_paths(schema) == ["info.blob", "images.image"]
        +    assert row_addressable_blob_paths(schema) == [
        +        "info.blob",
        +        "info.legacy",
        +        "legacy",
        +    ]
             assert row_addressable_blob_v2_paths(schema) == ["info.blob"]
         
         
        @@ -1883,6 +1963,18 @@ def test_fetch_blob_apis_reject_missing_fragment_row_addr():
             _assert_fetch_apis_reject_missing_row_ids(table, [1 << 32, live])
         
         
        +def test_fetch_blobs_missing_row_ids_suggest_take_offsets():
        +    table = _blob_table(
        +        "position_hint",
        +        [{"id": i, "image": b"x"} for i in range(3)],
        +    )
        +    with pytest.raises(ValueError, match="take_offsets") as exc:
        +        table.fetch_blobs("image", [10])
        +    message = str(exc.value)
        +    assert "first missing row ids: [10]" in message
        +    assert "with_row_id=True" in message
        +
        +
         def test_fetch_blob_apis_reject_deleted_row_ids():
             table = _blob_table(
                 "deleted_rows",
        @@ -2141,8 +2233,11 @@ def test_fetch_blobs_from_query_result_without_row_id_raises():
             table = _blob_table("no_rowid", [{"id": 1, "image": b"x"}])
             hits = table.search().select(["id"]).to_arrow()
             assert "_rowid" not in hits.column_names
        -    with pytest.raises(ValueError, match="_rowid"):
        +    with pytest.raises(ValueError, match="take_offsets") as exc:
                 table.fetch_blobs("image", hits)
        +    message = str(exc.value)
        +    assert "with_row_id=True" in message
        +    assert "list of row ids" in message
         
         
         _HYBRID_BLOB_SCHEMA = pa.schema(
        @@ -2293,6 +2388,8 @@ async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch):
             if blob_mode != "lazy":
                 assert "_rowid" not in reader.schema.names
                 assert "_lance_row_id" not in str(reader.schema)
        +    else:
        +        assert "_rowid" in reader.schema.names
         
         
         class _KeepAllScoresReranker(Reranker):
        @@ -2307,6 +2404,77 @@ class _KeepAllScoresReranker(Reranker):
                 return combined.append_column("_relevance_score", scores)
         
         
        +class _RecordingVectorReranker(Reranker):
        +    def __init__(self):
        +        super().__init__(return_score="all")
        +        self.calls = []
        +
        +    def rerank_hybrid(self, query, vector_results, fts_results):
        +        raise AssertionError("vector queries must not call rerank_hybrid")
        +
        +    def rerank_vector(self, query, vector_results):
        +        self.calls.append((query, vector_results))
        +        return vector_results.append_column(
        +            "_relevance_score",
        +            pa.array([1.0] * len(vector_results), type=pa.float32()),
        +        )
        +
        +
        +@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"])
        +def test_vector_to_arrow_reranks_before_blob_conversion(blob_mode, monkeypatch):
        +    db = lancedb.connect("memory:///")
        +    schema = pa.schema(
        +        [
        +            pa.field("id", pa.int64()),
        +            pa.field("vector", pa.list_(pa.float32(), list_size=2)),
        +            lancedb.blob("image"),
        +        ]
        +    )
        +    table = db.create_table(f"vector_rerank_{blob_mode}", schema=schema)
        +    rows = 1100
        +    table.add(
        +        [
        +            {
        +                "id": row_id,
        +                "vector": [1.0, float(row_id % 2)],
        +                "image": f"image-{row_id}".encode(),
        +            }
        +            for row_id in range(rows)
        +        ]
        +    )
        +    fetched = []
        +    fetch_blobs = table.fetch_blobs
        +
        +    def fetch(column, row_ids):
        +        fetched.append((column, len(row_ids)))
        +        return fetch_blobs(column, row_ids)
        +
        +    monkeypatch.setattr(table, "fetch_blobs", fetch)
        +    reranker = _RecordingVectorReranker()
        +    hits = (
        +        table.search([1.0, 0.0])
        +        .limit(rows)
        +        .select(["id", "image"])
        +        .rerank(reranker, "hello")
        +        .to_arrow(blob_mode=blob_mode)
        +    )
        +
        +    assert len(reranker.calls) == 1
        +    query, source = reranker.calls[0]
        +    assert query == "hello"
        +    # The reranker sees descriptors, not already-converted payload bytes.
        +    assert not pa.types.is_large_binary(source.schema.field("image").type)
        +    assert "_relevance_score" in hits.column_names
        +    assert len(hits) == rows
        +    if blob_mode == "bytes":
        +        # The whole lazy result is materialized before one aggregate conversion.
        +        assert fetched == [("image", rows)]
        +        assert pa.types.is_large_binary(hits.schema.field("image").type)
        +    else:
        +        assert fetched == []
        +        assert not pa.types.is_large_binary(hits.schema.field("image").type)
        +
        +
         def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
             db = lancedb.connect(tmp_path)
             table = db.create_table(
        @@ -2336,7 +2504,7 @@ def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
                 .rerank(_KeepAllScoresReranker())
             )
         
        -    with pytest.raises(ValueError, match=r"\['blob'\].*legacy blob columns"):
        +    with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
                 query.to_arrow(blob_mode="bytes")
         
         
        @@ -3099,3 +3267,393 @@ async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path):
                     with file:
                         actual.append(await file.aread())
             assert actual == [None, b"alpha", b"alpha"]
        +
        +
        +def _initial_base_payloads(tmp_path):
        +    base_dir = tmp_path / "videos"
        +    base_dir.mkdir(exist_ok=True)
        +    payload = b"0123456789abcdef"
        +    clip = base_dir / "clip.mp4"
        +    clip.write_bytes(payload)
        +    return base_dir, clip, payload
        +
        +
        +@pytest.mark.parametrize("base_spec", ["lightweight", "dict", "dataset_base_path"])
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.asyncio
        +async def test_create_table_initial_bases_store_relative_blob_ranges(
        +    tmp_path, base_spec, use_async
        +):
        +    lance = None
        +    if base_spec == "dataset_base_path":
        +        lance = pytest.importorskip("lance")
        +    base_dir, clip, payload = _initial_base_payloads(tmp_path)
        +    field = lancedb.blob("video").with_metadata({"lancedb:logical_type": "mp4"})
        +    schema = pa.schema([pa.field("id", pa.int64()), field])
        +    videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
        +    batch = pa.RecordBatch.from_arrays(
        +        [pa.array([1], pa.int64()), videos], schema=schema
        +    )
        +    base_kwargs = {"path": base_dir.as_uri(), "name": "source", "id": 1}
        +    if base_spec == "lightweight":
        +        bases = [lancedb.BasePath(**base_kwargs)]
        +    elif base_spec == "dict":
        +        bases = [base_kwargs]
        +    else:
        +        bases = [lance.DatasetBasePath(**base_kwargs)]
        +
        +    if use_async:
        +        db = await lancedb.connect_async(tmp_path / "db")
        +        table = await db.create_table("videos", data=batch, initial_bases=bases)
        +        assert await table.version() == 1
        +        created_schema = await table.schema()
        +        reopened = await db.open_table("videos")
        +        hits = await reopened.query().with_row_id().to_arrow()
        +        row_id = hits["_rowid"][0].as_py()
        +        assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload[:6]]
        +        assert (
        +            await reopened.fetch_blob_ranges("video", [(row_id, 1, 3)])
        +        ).to_pylist() == [payload[1:4]]
        +    else:
        +        db = lancedb.connect(tmp_path / "db")
        +        table = db.create_table("videos", data=batch, initial_bases=bases)
        +        assert table.version == 1
        +        created_schema = table.schema
        +        # Manifest introspection needs pylance; the lightweight and dict
        +        # variants must still prove registration through the reopen and bytes.
        +        if lance is not None:
        +            registered = table.to_lance().base_paths()[1]
        +            assert registered.path == base_dir.as_uri()
        +            assert registered.is_dataset_root is False
        +        reopened = db.open_table("videos")
        +        hits = reopened.search().with_row_id(True).to_arrow()
        +        row_id = hits["_rowid"][0].as_py()
        +        assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
        +        assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
        +            payload[1:4]
        +        ]
        +    assert created_schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
        +
        +
        +def test_create_table_initial_bases_bootstrap_empty_table_with_auto_id(tmp_path):
        +    pytest.importorskip("lance")
        +    base_dir, clip, payload = _initial_base_payloads(tmp_path)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    db = lancedb.connect(tmp_path / "db")
        +
        +    table = db.create_table(
        +        "videos",
        +        schema=schema,
        +        initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source")],
        +    )
        +    assert table.version == 1
        +    registered = list(table.to_lance().base_paths().values())
        +    assert len(registered) == 1
        +    assert registered[0].id > 0
        +    assert registered[0].path == base_dir.as_uri()
        +    assert registered[0].is_dataset_root is False
        +
        +    videos = lancedb.blob_uri_array([clip.as_uri()])
        +    rows = pa.RecordBatch.from_arrays(
        +        [pa.array([1], pa.int64()), videos], schema=schema
        +    )
        +    table.add(rows)
        +    reopened = db.open_table("videos")
        +    by_id = _row_ids_by_id(reopened)
        +    assert reopened.fetch_blobs("video", [by_id[1]]).to_pylist() == [payload]
        +
        +
        +def test_create_table_initial_bases_reject_bad_input(tmp_path):
        +    base_dir, _, _ = _initial_base_payloads(tmp_path)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    db = lancedb.connect("memory:///")
        +    path = base_dir.as_uri()
        +
        +    with pytest.raises(ValueError, match="id=0"):
        +        lancedb.BasePath(path=path, id=0)
        +    with pytest.raises(ValueError, match="id=0"):
        +        db.create_table("zero", schema=schema, initial_bases=[{"path": path, "id": 0}])
        +    with pytest.raises(ValueError, match="unique"):
        +        db.create_table(
        +            "duplicates",
        +            schema=schema,
        +            initial_bases=[
        +                lancedb.BasePath(path=path, id=1),
        +                lancedb.BasePath(path=f"{path}/other", id=1),
        +            ],
        +        )
        +    with pytest.raises(ValueError, match="missing 'path'"):
        +        db.create_table("missing_path", schema=schema, initial_bases=[{"id": 1}])
        +    with pytest.raises(TypeError, match="must be a BasePath, dict, or DatasetBasePath"):
        +        db.create_table("not_a_base", schema=schema, initial_bases=[object()])
        +
        +
        +def test_create_table_allow_external_blob_outside_bases_is_atomic(tmp_path):
        +    payload = b"0123456789abcdef"
        +    clip = tmp_path / "clip.mp4"
        +    clip.write_bytes(payload)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
        +    rows = pa.RecordBatch.from_arrays(
        +        [pa.array([1], pa.int64()), videos], schema=schema
        +    )
        +    db = lancedb.connect(tmp_path / "db")
        +
        +    with pytest.raises(ValueError, match="allow_external_blob_outside_bases"):
        +        db.create_table("rejected", data=rows, schema=schema)
        +    with pytest.raises(ValueError, match="requires initial data"):
        +        db.create_table(
        +            "empty_opt_in", schema=schema, allow_external_blob_outside_bases=True
        +        )
        +
        +    table = db.create_table(
        +        "videos", data=rows, schema=schema, allow_external_blob_outside_bases=True
        +    )
        +    assert table.version == 1
        +    reopened = db.open_table("videos")
        +    hits = reopened.search().with_row_id(True).to_arrow()
        +    assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
        +    row_id = hits["_rowid"][0].as_py()
        +    assert reopened.fetch_blob_ranges("video", [(row_id, 0, 6)]).to_pylist() == [
        +        payload[:6]
        +    ]
        +
        +
        +def test_create_table_initial_bases_keep_scoped_options_on_reopen(tmp_path):
        +    pytest.importorskip("lance")
        +    payload = b"scoped-payload"
        +    dir_a = tmp_path / "base-a"
        +    dir_b = tmp_path / "base-b"
        +    dir_a.mkdir()
        +    dir_b.mkdir()
        +    clip_a = dir_a / "clip.mp4"
        +    clip_b = dir_b / "clip.mp4"
        +    clip_a.write_bytes(payload)
        +    clip_b.write_bytes(payload)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
        +    rows = pa.RecordBatch.from_arrays(
        +        [pa.array([1, 2], pa.int64()), videos], schema=schema
        +    )
        +    storage_options = {
        +        "timeout": "7s",
        +        "base_1.region": "base-one",
        +        "base_2.region": "base-two",
        +    }
        +    db = lancedb.connect(tmp_path / "db")
        +
        +    table = db.create_table(
        +        "videos",
        +        data=rows,
        +        schema=schema,
        +        initial_bases=[
        +            lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
        +            lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
        +        ],
        +        storage_options=storage_options,
        +    )
        +    assert table.version == 1
        +    assert {base.id for base in table.to_lance().base_paths().values()} == {1, 2}
        +
        +    reopened = db.open_table("videos", storage_options=storage_options)
        +    by_id = _row_ids_by_id(reopened)
        +    assert reopened.fetch_blobs("video", [by_id[1], by_id[2]]).to_pylist() == [
        +        payload,
        +        payload,
        +    ]
        +
        +
        +def test_create_table_initial_bases_through_namespace(tmp_path):
        +    pytest.importorskip("lance")
        +    base_dir, clip, payload = _initial_base_payloads(tmp_path)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
        +    rows = pa.RecordBatch.from_arrays(
        +        [pa.array([1], pa.int64()), videos], schema=schema
        +    )
        +    db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "ns")})
        +
        +    table = db.create_table(
        +        "videos",
        +        data=rows,
        +        schema=schema,
        +        initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
        +    )
        +    assert table.version == 1
        +    reopened = db.open_table("videos")
        +    hits = reopened.search().with_row_id(True).to_arrow()
        +    row_id = hits["_rowid"][0].as_py()
        +    assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
        +    assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
        +        payload[1:4]
        +    ]
        +
        +
        +def test_namespace_create_keeps_scoped_options_over_connection_defaults(tmp_path):
        +    pytest.importorskip("lance")
        +    base_dir, clip, _ = _initial_base_payloads(tmp_path)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    videos = lancedb.blob_uri_array([clip.as_uri()])
        +    rows = pa.RecordBatch.from_arrays(
        +        [pa.array([1], pa.int64()), videos], schema=schema
        +    )
        +    db = lancedb.connect_namespace(
        +        "dir",
        +        {"root": str(tmp_path / "ns")},
        +        storage_options={"timeout": "7s"},
        +    )
        +
        +    # The invalid scoped option belongs to base 1. It must survive the merge
        +    # with connection defaults instead of being replaced by them.
        +    with pytest.raises(ValueError, match="scheduler_error_mode"):
        +        db.create_table(
        +            "videos",
        +            data=rows,
        +            schema=schema,
        +            initial_bases=[
        +                lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)
        +            ],
        +            storage_options={"base_1.scheduler_error_mode": "invalid"},
        +        )
        +
        +
        +def test_namespace_reopen_applies_scoped_options_per_base(tmp_path):
        +    pytest.importorskip("lance")
        +    payload_a = b"namespace-base-a"
        +    payload_b = b"namespace-base-b"
        +    dir_a = tmp_path / "base-a"
        +    dir_b = tmp_path / "base-b"
        +    dir_a.mkdir()
        +    dir_b.mkdir()
        +    clip_a = dir_a / "clip.mp4"
        +    clip_b = dir_b / "clip.mp4"
        +    clip_a.write_bytes(payload_a)
        +    clip_b.write_bytes(payload_b)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
        +    rows = pa.RecordBatch.from_arrays(
        +        [pa.array([1, 2], pa.int64()), videos], schema=schema
        +    )
        +    db = lancedb.connect_namespace(
        +        "dir",
        +        {"root": str(tmp_path / "ns")},
        +        storage_options={"timeout": "7s"},
        +    )
        +
        +    table = db.create_table(
        +        "videos",
        +        data=rows,
        +        schema=schema,
        +        initial_bases=[
        +            lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
        +            lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
        +        ],
        +    )
        +    assert table.version == 1
        +
        +    reopened = db.open_table(
        +        "videos", storage_options={"base_1.scheduler_error_mode": "invalid"}
        +    )
        +    by_id = _row_ids_by_id(reopened)
        +    with pytest.raises(ValueError, match="scheduler_error_mode"):
        +        reopened.fetch_blobs("video", [by_id[1]])
        +    assert reopened.fetch_blobs("video", [by_id[2]]).to_pylist() == [payload_b]
        +
        +
        +@pytest.mark.asyncio
        +async def test_create_table_initial_bases_through_async_namespace(tmp_path):
        +    pytest.importorskip("lance")
        +    base_dir, clip, payload = _initial_base_payloads(tmp_path)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    videos = lancedb.blob_uri_array([clip.as_uri()])
        +    rows = pa.RecordBatch.from_arrays(
        +        [pa.array([1], pa.int64()), videos], schema=schema
        +    )
        +    db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path / "ns")})
        +
        +    table = await db.create_table(
        +        "videos",
        +        data=rows,
        +        schema=schema,
        +        initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
        +    )
        +    assert await table.version() == 1
        +    reopened = await db.open_table("videos")
        +    hits = await reopened.query().with_row_id().to_arrow()
        +    assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload]
        +
        +
        +def test_namespace_refresh_layers_caller_scoped_options(tmp_path):
        +    from lance_namespace import (
        +        DeclareTableResponse,
        +        DescribeTableResponse,
        +        LanceNamespace,
        +    )
        +    from lancedb.namespace import LanceNamespaceDBConnection
        +
        +    class RefreshingNamespace(LanceNamespace):
        +        def __init__(self, location):
        +            self.location = location
        +            self.refreshes = 0
        +
        +        def namespace_id(self):
        +            return self.location
        +
        +        def declare_table(self, request):
        +            return DeclareTableResponse(
        +                location=self.location,
        +                storage_options={
        +                    "timeout": "7s",
        +                    # Expired immediately so the next read must refresh.
        +                    "expires_at_millis": "1",
        +                },
        +            )
        +
        +        def describe_table(self, request):
        +            self.refreshes += 1
        +            return DescribeTableResponse(
        +                location=self.location,
        +                storage_options={"timeout": "8s", "namespace_vended": "fresh"},
        +            )
        +
        +    payload = b"0123456789abcdef"
        +    base_dir = tmp_path / "base"
        +    base_dir.mkdir()
        +    clip = base_dir / "clip.mp4"
        +    clip.write_bytes(payload)
        +    schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
        +    videos = lancedb.blob_uri_array([clip.as_uri()])
        +    rows = pa.RecordBatch.from_arrays(
        +        [pa.array([1], pa.int64()), videos], schema=schema
        +    )
        +    namespace = RefreshingNamespace((tmp_path / "table.lance").as_uri())
        +    db = LanceNamespaceDBConnection(namespace)
        +
        +    table = db.create_table(
        +        "videos",
        +        data=rows,
        +        schema=schema,
        +        initial_bases=[lancedb.BasePath(base_dir.as_uri(), name="base", id=1)],
        +        storage_options={"base_1.caller_scoped": "keep-me"},
        +    )
        +    initial = table.initial_storage_options()
        +    assert initial["base_1.caller_scoped"] == "keep-me"
        +    assert initial["timeout"] == "7s"
        +
        +    latest = table.latest_storage_options()
        +    assert namespace.refreshes > 0, "expired seed did not trigger a refresh"
        +    assert latest["base_1.caller_scoped"] == "keep-me"
        +    assert latest["timeout"] == "8s"
        +    assert latest["namespace_vended"] == "fresh"
        +    assert table.version == 1
        +
        +    reopened = db.open_table(
        +        "videos", storage_options={"base_1.caller_scoped": "keep-me"}
        +    )
        +    assert reopened.latest_storage_options()["base_1.caller_scoped"] == "keep-me"
        +    hits = reopened.search().with_row_id(True).to_arrow()
        +    row_id = hits["_rowid"][0].as_py()
        +    assert reopened.fetch_blobs("video", [row_id]).to_pylist() == [payload]
        +    assert reopened.fetch_blob_ranges("video", [(row_id, 4, 6)]).to_pylist() == [
        +        payload[4:10]
        +    ]
        diff --git a/python/python/tests/test_blob_array.py b/python/python/tests/test_blob_array.py
        index 7204e72e1..fa9db0cac 100644
        --- a/python/python/tests/test_blob_array.py
        +++ b/python/python/tests/test_blob_array.py
        @@ -85,3 +85,133 @@ def test_blob_array(with_pylance):
                 text=True,
             )
             assert result.returncode == 0, result.stderr
        +
        +
        +@pytest.mark.parametrize("with_pylance", [False, True])
        +def test_blob_uri_array(with_pylance):
        +    if with_pylance:
        +        pytest.importorskip("lance")
        +    # Use fresh processes so each extension class can own Arrow's registry.
        +    script = textwrap.dedent(
        +        """\
        +        import importlib.abc
        +        import pathlib
        +        import sys
        +        import tempfile
        +
        +        if sys.argv[1] == "False":
        +            class MissingLance(importlib.abc.MetaPathFinder):
        +                def find_spec(self, fullname, path, target=None):
        +                    if fullname == "lance" or fullname.startswith("lance."):
        +                        raise ModuleNotFoundError(fullname, name="lance")
        +            sys.meta_path.insert(0, MissingLance())
        +
        +        import lancedb
        +        import pyarrow as pa
        +        from lancedb import BasePath, blob_uri_array
        +        from lancedb.schema import blob
        +
        +        if sys.argv[1] == "True":
        +            from lance import DatasetBasePath
        +            from lance.blob import BlobType
        +        else:
        +            from lancedb.schema import _FallbackBlobType as BlobType
        +            DatasetBasePath = None
        +
        +        schema = pa.schema([blob("video")])
        +        array = blob_uri_array(
        +            ["s3://bucket/a.mp4", None, "b.mp4"],
        +            positions=[0, None, None],
        +            sizes=[4, None, None],
        +        )
        +        assert isinstance(array, pa.ExtensionArray)
        +        assert type(array.type) is BlobType
        +        assert array.type == schema.field("video").type
        +        assert array.storage.to_pylist() == [
        +            {"data": None, "uri": "s3://bucket/a.mp4", "position": 0, "size": 4},
        +            None,
        +            {"data": None, "uri": "b.mp4", "position": None, "size": None},
        +        ]
        +        whole = blob_uri_array(iter(["s3://bucket/a.mp4"]))
        +        assert whole.storage.to_pylist() == [
        +            {"data": None, "uri": "s3://bucket/a.mp4", "position": None, "size": None}
        +        ]
        +
        +        checks = [
        +            (lambda: blob_uri_array(["u"], positions=[0]), "provided together"),
        +            (
        +                lambda: blob_uri_array(["u"], positions=[0, 0], sizes=[1, 1]),
        +                "same length",
        +            ),
        +            (
        +                lambda: blob_uri_array(["u"], sizes=[1, 1], positions=[0, 0]),
        +                "same length",
        +            ),
        +            (
        +                lambda: blob_uri_array(["u"], positions=[0], sizes=[None]),
        +                "both position and size",
        +            ),
        +            (lambda: blob_uri_array(["u"], positions=[0], sizes=[0]), "positive"),
        +            (lambda: blob_uri_array(["u"], positions=[-1], sizes=[1]), "non-negative"),
        +            (lambda: blob_uri_array([None], positions=[0], sizes=[1]), "None but"),
        +            (lambda: blob_uri_array(["u"], positions=[0], sizes=[2**64]), "uint64"),
        +            (lambda: blob_uri_array([b"u"]), "must be a string"),
        +        ]
        +        for call, fragment in checks:
        +            try:
        +                call()
        +            except (TypeError, ValueError, OverflowError) as error:
        +                assert fragment in str(error), (fragment, error)
        +            else:
        +                raise AssertionError(f"accepted invalid input: {fragment}")
        +
        +        try:
        +            BasePath("s3://bucket", id=0)
        +        except ValueError as error:
        +            assert "id=None" in str(error)
        +        else:
        +            raise AssertionError("accepted explicit id=0")
        +
        +        # The public create route must accept the helper and register the base
        +        # in the same commit as the data, with or without pylance.
        +        root = pathlib.Path(tempfile.mkdtemp())
        +        base_dir = root / "videos"
        +        base_dir.mkdir()
        +        payload = b"0123456789abcdef"
        +        clip = base_dir / "clip.mp4"
        +        clip.write_bytes(payload)
        +        db = lancedb.connect(root / "db")
        +        field = blob("video").with_metadata({"lancedb:logical_type": "mp4"})
        +        table_schema = pa.schema([pa.field("id", pa.int64()), field])
        +        videos = blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
        +        batch = pa.RecordBatch.from_arrays(
        +            [pa.array([1], pa.int64()), videos], schema=table_schema
        +        )
        +        if DatasetBasePath is not None:
        +            bases = [DatasetBasePath(path=base_dir.as_uri(), name="source")]
        +        else:
        +            bases = [BasePath(path=base_dir.as_uri(), name="source")]
        +        table = db.create_table("videos", data=batch, initial_bases=bases)
        +        assert table.version == 1
        +        assert (
        +            table.schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
        +        )
        +        row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
        +        assert table.fetch_blobs("video", row_ids).to_pylist() == [payload[:6]]
        +        assert table.fetch_blob_ranges(
        +            "video", [(row_ids[0].as_py(), 1, 3)]
        +        ).to_pylist() == [payload[1:4]]
        +        if DatasetBasePath is not None:
        +            base_paths = table.to_lance().base_paths()
        +            assert base_paths[1].path == base_dir.as_uri()
        +            assert base_paths[1].is_dataset_root is False
        +        if sys.argv[1] == "False":
        +            assert "lance" not in sys.modules
        +        """
        +    )
        +    result = subprocess.run(
        +        [sys.executable, "-c", script, str(with_pylance)],
        +        capture_output=True,
        +        text=True,
        +    )
        +    assert result.returncode == 0, result.stderr
        diff --git a/python/python/tests/test_blob_buffering.py b/python/python/tests/test_blob_buffering.py
        new file mode 100644
        index 000000000..09fbfb862
        --- /dev/null
        +++ b/python/python/tests/test_blob_buffering.py
        @@ -0,0 +1,236 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import json
        +import threading
        +from contextlib import contextmanager
        +from urllib.parse import urlparse
        +
        +import pyarrow as pa
        +import pytest
        +
        +import lancedb
        +from test_remote_db import (
        +    BLOB_DESCRIBE_RESPONSE,
        +    blob_descriptor_take_table,
        +    mock_lancedb_connection,
        +)
        +
        +
        +@contextmanager
        +def remote_buffer_table(*, http_requests=None, truncate_first=False):
        +    payload = bytes(range(256)) * 4096
        +    requests = []
        +
        +    def handler(request):
        +        path = urlparse(request.path).path
        +        if http_requests is not None:
        +            http_requests.append(path)
        +        if path.endswith("/describe/"):
        +            body = json.dumps(BLOB_DESCRIBE_RESPONSE).encode()
        +            content_type = "application/json"
        +        elif path.endswith("/query/"):
        +            data = json.loads(
        +                request.rfile.read(int(request.headers["Content-Length"]))
        +            )
        +            assert data["columns"] == ["image"]
        +            table = blob_descriptor_take_table().slice(0, 1)
        +            images = table["image"].combine_chunks()
        +            images = pa.StructArray.from_arrays(
        +                [
        +                    images.field("kind"),
        +                    images.field("position"),
        +                    pa.array([len(payload)], pa.uint64()),
        +                    images.field("blob_id"),
        +                    images.field("blob_uri"),
        +                ],
        +                fields=list(images.type),
        +            )
        +            table = table.set_column(0, table.schema.field(0), images)
        +            sink = pa.BufferOutputStream()
        +            with pa.ipc.new_stream(sink, table.schema) as writer:
        +                writer.write_table(table)
        +            body = sink.getvalue().to_pybytes()
        +            content_type = "application/vnd.apache.arrow.stream"
        +        else:
        +            assert path == "/v1/table/test/blob/image/10/bytes"
        +            assert "version=1" in request.path
        +            start, end = map(int, request.headers["Range"][6:].split("-"))
        +            requests.append((start, end + 1))
        +            body = payload[start : end + 1]
        +            if truncate_first and len(requests) == 1:
        +                body = body[:5]
        +            request.send_response(206)
        +            request.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
        +            request.send_header("Content-Length", str(len(body)))
        +            request.end_headers()
        +            request.wfile.write(body)
        +            return
        +        request.send_response(200)
        +        request.send_header("Content-Type", content_type)
        +        request.send_header("Content-Length", str(len(body)))
        +        request.send_header("phalanx-version", "0.5.0")
        +        request.send_header("x-lancedb-version", "1")
        +        request.end_headers()
        +        request.wfile.write(body)
        +
        +    with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
        +        yield db.open_table("test"), payload, requests
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("buffer_size", [None, 0, 8, 512 * 1024])
        +async def test_remote_read_ahead_over_http(use_async, buffer_size):
        +    with remote_buffer_table() as (table, payload, requests):
        +        if use_async:
        +            files = await table._table.fetch_blob_files(
        +                "image", [10], buffer_size=buffer_size
        +            )
        +        else:
        +            files = table.fetch_blob_files("image", [10], buffer_size=buffer_size)
        +        file = files[0]
        +        assert requests == []
        +        assert file.read(2) == payload[:2]
        +        window = 512 * 1024 if buffer_size is None else max(buffer_size, 2)
        +        assert requests == [(0, window)]
        +        assert file.read(2) == payload[2:4]
        +        assert len(requests) == (2 if buffer_size == 0 else 1)
        +        file.seek(1)
        +        assert file.read(1) == payload[1:2]
        +        assert len(requests) == (3 if buffer_size == 0 else 1)
        +        before = len(requests)
        +        assert file.read_range(0, 1) == payload[:1]
        +        assert len(requests) == before + 1
        +        assert requests[-1] == (0, 1)
        +        assert file.tell() == 2
        +        file.set_buffer_size(0)
        +        assert file.read(1) == payload[2:3]
        +        assert requests[-1] == (2, 3)
        +        file.set_buffer_size(16)
        +        assert file.read(1) == payload[3:4]
        +        assert requests[-1] == (3, 19)
        +        file.seek(len(payload) - 1)
        +        assert file.read(4) == payload[-1:]
        +        assert requests[-1] == (len(payload) - 1, len(payload))
        +        before = len(requests)
        +        assert file.read(1) == b""
        +        assert len(requests) == before
        +        file.close()
        +        with pytest.raises(ValueError, match="closed"):
        +            file.set_buffer_size(0)
        +
        +
        +def test_short_prefetch_over_http_preserves_cursor():
        +    with remote_buffer_table(truncate_first=True) as (table, payload, requests):
        +        file = table.fetch_blob_files("image", [10], buffer_size=8)[0]
        +        with pytest.raises(RuntimeError, match="returned 5 bytes, expected 8"):
        +            file.read(6)
        +        assert file.tell() == 0
        +        assert file.read(3) == payload[:3]
        +        assert file.tell() == 3
        +        assert requests == [(0, 8), (0, 8)]
        +        file.close()
        +
        +
        +def test_idle_prefetch_releases_http_concurrency_slot():
        +    with remote_buffer_table() as (table, payload, requests):
        +        first, second = table.fetch_blob_files("image", [10, 10])
        +        assert first.read(1) == payload[:1]
        +        results = []
        +        errors = []
        +
        +        def read_other():
        +            try:
        +                results.append(second.read(1))
        +            except Exception as error:
        +                errors.append(error)
        +
        +        reader = threading.Thread(target=read_other, daemon=True)
        +        reader.start()
        +        reader.join(timeout=2)
        +        completed_while_first_idle = not reader.is_alive()
        +        first.close()
        +        reader.join(timeout=2)
        +        second.close()
        +        assert completed_while_first_idle, (
        +            "idle prefetch retained the HTTP request slot"
        +        )
        +        assert not errors
        +        assert results == [payload[:1]]
        +        assert requests == [(0, 512 * 1024), (0, 512 * 1024)]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_local_buffer_configuration_through_python(tmp_path, use_async):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table(
        +        "blobs", [{"image": b"0123456789"}], schema=pa.schema([lancedb.blob("image")])
        +    )
        +    row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
        +    if use_async:
        +        files = await table._table.fetch_blob_files("image", row_ids, buffer_size=0)
        +    else:
        +        files = table.fetch_blob_files("image", row_ids, buffer_size=0)
        +    file = files[0]
        +    assert file.read(2) == b"01"
        +    file.set_buffer_size(4)
        +    assert file.read(2) == b"23"
        +    file.seek(1)
        +    assert file.read(3) == b"123"
        +    assert file.read_range(8, 2) == b"89"
        +    with pytest.raises(ValueError, match="non-negative"):
        +        file.set_buffer_size(-1)
        +    with pytest.raises(TypeError):
        +        file.set_buffer_size(1.5)
        +    file.close()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_open_descriptor_files_forward_buffer_size(use_async):
        +    with remote_buffer_table() as (table, payload, requests):
        +        descriptor = {
        +            "kind": 1,
        +            "position": 0,
        +            "size": len(payload),
        +            "blob_id": 0,
        +            "blob_uri": "",
        +            "source": {
        +                "uri": "s3://bucket/test.lance",
        +                "version": 1,
        +                "committed_at_micros": 1,
        +                "column": "image",
        +                "row_reference": 10,
        +                "row_is_address": False,
        +            },
        +        }
        +        if use_async:
        +            files = [
        +                file
        +                async for file in table._table.open_blob_files(
        +                    [None, descriptor], buffer_size=8
        +                )
        +            ]
        +        else:
        +            files = list(table.open_blob_files([None, descriptor], buffer_size=8))
        +        assert files[0] is None
        +        assert files[1].read(1) == payload[:1]
        +        assert requests == [(0, 8)]
        +        files[1].close()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_invalid_buffer_size_rejects_before_http(use_async):
        +    http_requests = []
        +    with remote_buffer_table(http_requests=http_requests) as (table, _, requests):
        +        http_requests.clear()
        +        with pytest.raises(ValueError, match="non-negative"):
        +            if use_async:
        +                await table._table.fetch_blob_files("image", [10], buffer_size=-1)
        +            else:
        +                table.fetch_blob_files("image", [10], buffer_size=-1)
        +        assert requests == []
        +        assert http_requests == []
        diff --git a/python/python/tests/test_blob_query_without_pylance.py b/python/python/tests/test_blob_query_without_pylance.py
        index a5ce6db44..7c503d1ff 100644
        --- a/python/python/tests/test_blob_query_without_pylance.py
        +++ b/python/python/tests/test_blob_query_without_pylance.py
        @@ -8,12 +8,7 @@ import textwrap
         import pytest
         
         
        -@pytest.mark.parametrize("api", ["sync", "async"])
        -@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
        -def test_blob_query_without_pylance(tmp_path, api, result):
        -    if result == "pandas":
        -        pytest.importorskip("pandas")
        -    script = """\
        +_WITHOUT_LANCE = """\
         import importlib.abc
         import sys
         
        @@ -23,7 +18,15 @@ class MissingLance(importlib.abc.MetaPathFinder):
                     raise ModuleNotFoundError(fullname, name="lance")
         
         sys.meta_path.insert(0, MissingLance())
        -""" + textwrap.dedent(
        +"""
        +
        +
        +@pytest.mark.parametrize("api", ["sync", "async"])
        +@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
        +def test_blob_query_without_pylance(tmp_path, api, result):
        +    if result == "pandas":
        +        pytest.importorskip("pandas")
        +    script = _WITHOUT_LANCE + textwrap.dedent(
                 """\
                 import asyncio
                 import lancedb
        @@ -94,3 +97,187 @@ sys.meta_path.insert(0, MissingLance())
                 text=True,
             )
             assert completed.returncode == 0, completed.stderr
        +
        +
        +@pytest.mark.parametrize("api", ["sync", "async"])
        +@pytest.mark.parametrize("result", ["pandas", "batches", "arrow"])
        +def test_plain_legacy_blob_query_without_pylance(tmp_path, api, result):
        +    if result == "pandas":
        +        pytest.importorskip("pandas")
        +    script = _WITHOUT_LANCE + textwrap.dedent(
        +        """\
        +        import asyncio
        +        import lancedb
        +        import pyarrow as pa
        +        from lancedb.query import ColumnOrdering
        +
        +        schema = pa.schema(
        +            [
        +                pa.field("id", pa.int64()),
        +                pa.field("filename", pa.string()),
        +                pa.field(
        +                    "video_blob",
        +                    pa.large_binary(),
        +                    metadata={"lance-encoding:blob": "true"},
        +                ),
        +            ]
        +        )
        +        rows = [
        +            {"id": 1, "filename": "file-1.mp4", "video_blob": b"outside"},
        +            {"id": 2, "filename": "file-2.mp4", "video_blob": b""},
        +            {"id": 3, "filename": "file-3.mp4", "video_blob": None},
        +            {"id": 4, "filename": "file-4.mp4", "video_blob": b"four"},
        +        ]
        +        expected = [
        +            {"filename": "file-2.mp4", "payload": b""},
        +            {"filename": "file-3.mp4", "payload": None},
        +            {"filename": "file-4.mp4", "payload": b"four"},
        +        ]
        +
        +        def configure(query):
        +            return (
        +                query.select({"filename": "filename", "payload": "video_blob"})
        +                .where("id >= 2")
        +                .order_by(
        +                    [ColumnOrdering(column_name="id", ascending=True)]
        +                )
        +                .limit(3)
        +            )
        +
        +        async def main():
        +            storage_options = {"new_table_data_storage_version": "2.1"}
        +            if sys.argv[2] == "async":
        +                db = await lancedb.connect_async(
        +                    sys.argv[1], storage_options=storage_options
        +                )
        +                table = await db.create_table("legacy", schema=schema)
        +                await table.add(rows)
        +                table = await db.open_table("legacy")
        +                def query():
        +                    return configure(table.query())
        +                def original_query():
        +                    return table.query().select(
        +                        {"filename": "filename", "payload": "video_blob"}
        +                    ).limit(1)
        +                def empty_query():
        +                    return query().where("id < 0")
        +                def batches():
        +                    return query().to_batches(
        +                        max_batch_length=1, blob_mode="bytes"
        +                    )
        +            else:
        +                db = lancedb.connect(
        +                    sys.argv[1], storage_options=storage_options
        +                )
        +                table = db.create_table("legacy", schema=schema)
        +                table.add(rows)
        +                table = db.open_table("legacy")
        +                def query():
        +                    return configure(table.search())
        +                def original_query():
        +                    return table.search().select(
        +                        {"filename": "filename", "payload": "video_blob"}
        +                    ).limit(1)
        +                def empty_query():
        +                    return query().where("id < 0")
        +                def batches():
        +                    return query().to_batches(
        +                        batch_size=1, blob_mode="bytes"
        +                    )
        +
        +            if sys.argv[2] == "async":
        +                reused = table.query().select(
        +                    {"filename": "filename", "payload": "video_blob"}
        +                ).limit(3)
        +                byte_reader = await reused.to_batches(blob_mode="bytes")
        +                await byte_reader.read_all()
        +                lazy_reader = await reused.to_batches(blob_mode="lazy")
        +                assert "_rowid" not in lazy_reader.schema.names
        +                await lazy_reader.read_all()
        +                reused.select(["filename"])
        +                nonblob_reader = await reused.to_batches(blob_mode="lazy")
        +                assert nonblob_reader.schema.names == ["filename"]
        +                await nonblob_reader.read_all()
        +
        +            if sys.argv[3] == "pandas":
        +                frame = query().to_pandas(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    frame = await frame
        +                assert frame.to_dict("records") == expected
        +                original = original_query().to_pandas(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    original = await original
        +                assert original.to_dict("records") == [
        +                    {"filename": "file-1.mp4", "payload": b"outside"}
        +                ]
        +                direct = table.to_pandas(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    direct = await direct
        +                assert direct.to_dict("records") == rows
        +                empty = empty_query().to_pandas(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    empty = await empty
        +                assert empty.to_dict("records") == []
        +            elif sys.argv[3] == "batches":
        +                reader = batches()
        +                if sys.argv[2] == "async":
        +                    reader = await reader
        +                    rows_out = [batch async for batch in reader]
        +                else:
        +                    rows_out = list(reader)
        +                assert reader.schema.field("payload").type == pa.large_binary()
        +                assert "_rowid" not in reader.schema.names
        +                assert all(batch.num_rows == 1 for batch in rows_out)
        +                assert all(batch.schema == reader.schema for batch in rows_out)
        +                actual = [row for batch in rows_out for row in batch.to_pylist()]
        +                assert actual == expected
        +                original_reader = original_query().to_batches(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    original_reader = await original_reader
        +                    original_rows = [batch async for batch in original_reader]
        +                else:
        +                    original_rows = list(original_reader)
        +                assert [
        +                    row for batch in original_rows for row in batch.to_pylist()
        +                ] == [{"filename": "file-1.mp4", "payload": b"outside"}]
        +                empty_reader = empty_query().to_batches(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    empty_reader = await empty_reader
        +                    empty_batches = [batch async for batch in empty_reader]
        +                else:
        +                    empty_batches = list(empty_reader)
        +                assert empty_batches == []
        +                assert empty_reader.schema.field("payload").type == pa.large_binary()
        +            else:
        +                table_out = query().to_arrow(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    table_out = await table_out
        +                assert table_out.schema.field("payload").type == pa.large_binary()
        +                assert "_rowid" not in table_out.column_names
        +                assert table_out.to_pylist() == expected
        +                original = original_query().to_arrow(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    original = await original
        +                assert original.to_pylist() == [
        +                    {"filename": "file-1.mp4", "payload": b"outside"}
        +                ]
        +                direct = table.to_arrow(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    direct = await direct
        +                assert direct.to_pylist() == rows
        +                empty_table = empty_query().to_arrow(blob_mode="bytes")
        +                if sys.argv[2] == "async":
        +                    empty_table = await empty_table
        +                assert empty_table.num_rows == 0
        +                assert empty_table.schema.field("payload").type == pa.large_binary()
        +            assert "lance" not in sys.modules
        +
        +        asyncio.run(main())
        +        """
        +    )
        +    completed = subprocess.run(
        +        [sys.executable, "-c", script, str(tmp_path), api, result],
        +        capture_output=True,
        +        text=True,
        +    )
        +    assert completed.returncode == 0, completed.stderr
        diff --git a/python/python/tests/test_blob_ranges.py b/python/python/tests/test_blob_ranges.py
        new file mode 100644
        index 000000000..c65dfb8ae
        --- /dev/null
        +++ b/python/python/tests/test_blob_ranges.py
        @@ -0,0 +1,380 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +"""Exercise the public sync/async range APIs over bounded loopback HTTP."""
        +
        +import asyncio
        +import hashlib
        +import json
        +from pathlib import Path
        +import socket
        +import threading
        +
        +import lancedb._lancedb as native
        +import pyarrow as pa
        +import pytest
        +
        +from lancedb.remote.errors import HttpError, TableNotFoundError
        +from test_remote_db import mock_lancedb_connection
        +
        +MIB = 1024 * 1024
        +IDENTITY = "v1:" + "a" * 64
        +ROUTE = "/v1/table/test/fetch_blob_ranges/"
        +
        +
        +def payload(row, offset, length, version):
        +    pattern = bytes((row * 17 + i + version) % 251 for i in range(251))
        +    start = offset % 251
        +    return (pattern * ((start + length + 250) // 251))[start : start + length]
        +
        +
        +class RangeServer:
        +    def __init__(self, fault=None):
        +        self.fault = fault
        +        self.calls = []
        +        self.fetches = []
        +        self.identities = []
        +        self.stalled = threading.Event()
        +        self.release = threading.Event()
        +
        +    def __call__(self, request):
        +        request.connection.settimeout(15)
        +        size = int(request.headers.get("Content-Length", 0))
        +        assert size <= 256 * 1024
        +        body = json.loads(request.rfile.read(size) or b"{}")
        +        self.calls.append((request.command, request.path, body))
        +        if request.path in (
        +            "/v1/table/test/describe/",
        +            "/v1/table/test/branches/list/",
        +        ):
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.send_header("phalanx-version", "1.13.0-beta.0")
        +            if request.path.endswith("/describe/"):
        +                request.send_header("x-lancedb-blob-ranges", "1")
        +            request.end_headers()
        +            response = (
        +                {
        +                    "branches": {
        +                        "experiment": {
        +                            "parentBranch": None,
        +                            "parentVersion": 1,
        +                            "createAt": 1,
        +                            "manifestSize": 1,
        +                        }
        +                    }
        +                }
        +                if request.path.endswith("branches/list/")
        +                else {"version": 8, "schema": {"fields": []}}
        +            )
        +            request.wfile.write(json.dumps(response).encode())
        +            return
        +        assert (request.command, request.path) == ("POST", ROUTE)
        +        self.fetches.append(body)
        +        self.identities.append(request.headers.get("x-lancedb-query-snapshot"))
        +        assert body["column"] == "image"
        +        assert body["branch"] == "experiment"
        +        ranges = body["ranges"]
        +        assert len(ranges) <= 1024
        +        assert sum(r["length"] for r in ranges) <= 64 * MIB
        +        version = body["version"] or (7 if len(self.fetches) == 1 else 8)
        +        values = [
        +            None
        +            if r["row_id"] == 20
        +            else payload(r["row_id"], r["offset"], r["length"], version)
        +            for r in ranges
        +        ]
        +        fault = (
        +            self.fault
        +            if len(self.fetches) > 1 or str(self.fault).startswith("first-")
        +            else None
        +        )
        +        if fault in ("recreated", "gone"):
        +            request.send_response(400 if fault == "recreated" else 404)
        +            request.end_headers()
        +            request.wfile.write(
        +                b"query snapshot identity mismatch: source gone or replaced"
        +            )
        +            return
        +        if fault == "stall" and len(self.fetches) == 2:
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
        +            request.send_header("x-lancedb-version", str(version))
        +            request.send_header("x-lancedb-query-snapshot", IDENTITY)
        +            request.end_headers()
        +            request.wfile.flush()
        +            self.stalled.set()
        +            assert self.release.wait(15), "test did not release stalled response"
        +            return
        +        if fault == "structured400":
        +            request.send_response(400)
        +            request.send_header("x-lancedb-error-code", "invalid_input")
        +            request.end_headers()
        +            request.wfile.write(b'{"error":"range exceeds blob size"}')
        +            return
        +        if isinstance(fault, int):
        +            request.send_response(fault)
        +            request.end_headers()
        +            request.wfile.write(b"ordinary server failure")
        +            return
        +        if fault == "disconnect":
        +            request.connection.shutdown(socket.SHUT_RDWR)
        +            return
        +        column = "wrong" if fault == "column" else "value"
        +        data_type = pa.binary() if fault == "type" else pa.large_binary()
        +        if fault == "count":
        +            values = []
        +        elif fault == "length":
        +            values = [b""]
        +        batch = pa.table({column: pa.array(values, type=data_type)})
        +        sink = pa.BufferOutputStream()
        +        with pa.ipc.new_stream(sink, batch.schema) as writer:
        +            writer.write_table(batch, max_chunksize=257)
        +        ipc = sink.getvalue().to_pybytes()
        +        if fault == "eos":
        +            ipc = ipc[:-8]
        +        elif fault == "body":
        +            ipc = ipc[: len(ipc) // 2]
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
        +        if fault != "version":
        +            request.send_header("x-lancedb-version", str(version))
        +        if fault not in ("missing-identity", "first-missing-identity"):
        +            identity = (
        +                "broken"
        +                if fault == "first-invalid-identity"
        +                else "v1:" + "b" * 64
        +                if fault == "wrong-identity"
        +                else IDENTITY
        +            )
        +            request.send_header("x-lancedb-query-snapshot", identity)
        +        request.send_header(
        +            "Content-Length", str(len(ipc) + (10 if fault == "transport" else 0))
        +        )
        +        request.end_headers()
        +        for i in range(0, len(ipc), 8192):
        +            request.wfile.write(ipc[i : i + 8192])
        +
        +
        +async def fetch(table, requests, use_async):
        +    result = table.fetch_blob_ranges("image", requests)
        +    return await result if use_async else result
        +
        +
        +def api(db, use_async, version=None):
        +    table = db.open_table("test", branch="experiment", version=version)
        +    return table._table if use_async else table
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("version", [None, 3])
        +async def test_range_sdk_order_snapshot_and_overwrite(use_async, version):
        +    handler = RangeServer()
        +    with mock_lancedb_connection(handler) as db:
        +        table = api(db, use_async, version)
        +        requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)]
        +        requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)]
        +        result = await fetch(table, requests, use_async)
        +        assert isinstance(result, pa.LargeBinaryArray)
        +        assert result.to_pylist() == [
        +            None if row == 20 else payload(row, offset, length, version or 7)
        +            for row, offset, length in requests
        +        ]
        +        assert [b["version"] for b in handler.fetches] == [version, version or 7]
        +        result = await fetch(table, [(10, 0, 1)], use_async)
        +        assert result.to_pylist() == [payload(10, 0, 1, version or 8)]
        +        assert handler.fetches[-1]["version"] == version
        +        assert len(handler.fetches) == 3
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_range_sdk_cached_reopen_negotiates_capability(use_async):
        +    handler = RangeServer()
        +    with mock_lancedb_connection(handler) as db:
        +        for version in (7, 8):
        +            table = api(db, use_async)
        +            result = await fetch(table, [(10, 0, 1)], use_async)
        +            assert result.to_pylist() == [payload(10, 0, 1, version)]
        +        assert len(handler.fetches) == 2
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_range_sdk_large_single_and_aggregate_budget(use_async):
        +    handler = RangeServer()
        +    with mock_lancedb_connection(handler) as db:
        +        table = api(db, use_async)
        +        requests = [
        +            (10, 3, 33 * MIB),
        +            (30, 7, 33 * MIB),
        +            (40, 11, 70 * MIB),
        +            (20, 0, 2**64 - 1),
        +        ]
        +        # The loopback server advances latest after the first partition.
        +        result = await fetch(table, requests, use_async)
        +        assert len(result) == 4
        +        for i, (row, offset, length) in enumerate(requests[:3]):
        +            expected = payload(row, offset, length, 7)
        +            assert (
        +                hashlib.sha256(result[i].as_buffer()).digest()
        +                == hashlib.sha256(expected).digest()
        +            )
        +            assert len(result[i].as_buffer()) == length
        +        assert result[3].as_py() is None
        +        assert len(handler.fetches) == 3
        +        assert [b["version"] for b in handler.fetches] == [None, 7, 7]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize(
        +    "fault",
        +    [
        +        "type",
        +        "column",
        +        "count",
        +        "length",
        +        "eos",
        +        "body",
        +        "transport",
        +        "version",
        +        "disconnect",
        +        401,
        +        403,
        +        404,
        +        429,
        +        500,
        +    ],
        +)
        +async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault):
        +    handler = RangeServer(fault=fault)
        +    with mock_lancedb_connection(
        +        handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2}
        +    ) as db:
        +        table = api(db, use_async)
        +        with pytest.raises(Exception) as exc:
        +            await fetch(table, [(10, 0, 1)] * 1025, use_async)
        +        if fault == 404:
        +            assert isinstance(exc.value, TableNotFoundError)
        +            assert isinstance(exc.value.__cause__, HttpError)
        +            assert exc.value.__cause__.status_code == 404
        +        else:
        +            assert not isinstance(exc.value, ValueError)
        +        if isinstance(fault, int):
        +            assert exc.value.status_code == fault
        +        assert len(handler.fetches) == 2
        +        assert all(
        +            path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE)
        +            for _, path, _ in handler.calls
        +        )
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_range_sdk_structured_400_preserves_value_error(use_async):
        +    handler = RangeServer(fault="structured400")
        +    with mock_lancedb_connection(handler) as db:
        +        table = api(db, use_async)
        +        with pytest.raises(ValueError, match="range exceeds blob size"):
        +            await fetch(table, [(10, 0, 1)] * 1025, use_async)
        +        assert len(handler.fetches) == 2
        +
        +
        +@pytest.mark.asyncio
        +async def test_range_sdk_async_cancel_releases_only_request_permit():
        +    handler = RangeServer(fault="stall")
        +    with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
        +        table = api(db, True)
        +        pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True))
        +        try:
        +            assert await asyncio.to_thread(handler.stalled.wait, 10)
        +            pending.cancel()
        +            with pytest.raises(asyncio.CancelledError):
        +                await pending
        +            assert len(handler.fetches) == 2
        +            result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5)
        +            assert result.to_pylist() == [payload(10, 0, 1, 8)]
        +            assert len(handler.fetches) == 3
        +        finally:
        +            pending.cancel()
        +            handler.release.set()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_range_sdk_integer_validation_and_empty_zero_io(use_async):
        +    handler = RangeServer()
        +    with mock_lancedb_connection(handler) as db:
        +        table = api(db, use_async)
        +        before = len(handler.calls)
        +        assert (await fetch(table, [], use_async)).to_pylist() == []
        +        for request in [
        +            (-1, 0, 1),
        +            (2**64, 0, 1),
        +            (10, -1, 1),
        +            (10, 0, -1),
        +            (10, 0, 2**64),
        +            (10, 0.5, 1),
        +            (20, 2**64 - 1, 1),
        +            (10, 0),
        +        ]:
        +            with pytest.raises((ValueError, OverflowError, TypeError)):
        +                await fetch(table, [request], use_async)
        +        assert len(handler.calls) == before
        +
        +
        +def test_range_sdk_loaded_artifact_identity():
        +    artifact = Path(native.__file__).resolve()
        +    digest = hashlib.sha256()
        +    with artifact.open("rb") as source:
        +        for chunk in iter(lambda: source.read(1024 * 1024), b""):
        +            digest.update(chunk)
        +    print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}")
        +    assert artifact.is_file()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize(
        +    "fault", ["missing-identity", "wrong-identity", "recreated", "gone"]
        +)
        +@pytest.mark.parametrize("huge", [False, True])
        +async def test_range_sdk_original_identity_survives_every_partition(
        +    use_async, fault, huge
        +):
        +    handler = RangeServer(fault=fault)
        +    with mock_lancedb_connection(handler) as db:
        +        table = api(db, use_async)
        +        requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025
        +        error = (
        +            ValueError
        +            if fault == "recreated"
        +            else TableNotFoundError
        +            if fault == "gone"
        +            else NotImplementedError
        +        )
        +        with pytest.raises(
        +            error, match="snapshot identity" if fault != "gone" else None
        +        ):
        +            await fetch(table, requests, use_async)
        +        assert handler.identities == [None, IDENTITY]
        +        assert len(handler.fetches) == 2
        +        assert [body["version"] for body in handler.fetches] == [None, 7]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"])
        +async def test_range_sdk_bulk_requires_identity_before_payload_acceptance(
        +    use_async, fault
        +):
        +    handler = RangeServer(fault=fault)
        +    with mock_lancedb_connection(handler) as db:
        +        table = api(db, use_async)
        +        before = len(handler.calls)
        +        with pytest.raises(NotImplementedError, match="snapshot identity"):
        +            await fetch(table, [(10, 0, 1)] * 1025, use_async)
        +        assert len(handler.fetches) == 1
        +        assert len(handler.calls) == before + 1
        diff --git a/python/python/tests/test_catalog.py b/python/python/tests/test_catalog.py
        index 95b03c6e7..edac21bc1 100644
        --- a/python/python/tests/test_catalog.py
        +++ b/python/python/tests/test_catalog.py
        @@ -2,7 +2,9 @@
         # SPDX-FileCopyrightText: Copyright The LanceDB Authors
         
         from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
        +from datetime import timedelta
         import json
        +import warnings
         
         import pytest
         
        @@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
                 endpoint,
                 api_key="secret",
                 sql_host_override="invalid://localhost",
        +        storage_options={"azure_storage_account_name": "catalog-account"},
                 client_config={
                     "extra_headers": {
                         "X-LanceDB-Database": "wrong",
        @@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
             assert db.table_names() == []
             restored = lancedb.deserialize_conn(db.serialize())
             assert restored.sql_host_override == "invalid://localhost"
        +    assert restored.storage_options == {"azure_storage_account_name": "catalog-account"}
             for connection in (db, restored):
                 with pytest.raises(ValueError, match="sql_host_override must use"):
                     connection.execute_query_async("SELECT 1")
        @@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
                 )
                 assert "x-lancedb-database-prefix" not in headers
                 assert headers["x-api-key"] == "secret"
        +        assert headers["x-azure-storage-account-name"] == "catalog-account"
         
         
         @pytest.mark.asyncio
        @@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server):
                 ]
             )
             catalog = await lancedb.connect_catalog_async(
        -        endpoint, sql_host_override="invalid://localhost"
        +        endpoint,
        +        sql_host_override="invalid://localhost",
        +        storage_options={"account_name": "async-account"},
             )
             assert isinstance(catalog, lancedb.AsyncCatalog)
             db = await catalog.connect_database("analytics")
        @@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server):
                 await catalog.drop_database("full")
             await catalog.drop_database("missing", ignore_missing=True)
             assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"}
        +    for _, headers, _ in requests:
        +        headers = {key.lower(): value for key, value in headers.items()}
        +        assert headers["x-azure-storage-account-name"] == "async-account"
         
         
         @pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"])
        @@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint):
                 lancedb.connect_catalog(endpoint)
         
         
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"])
        +@pytest.mark.asyncio
        +async def test_catalog_accepts_database_connection_settings(
        +    catalog_server, asynchronous, region
        +):
        +    endpoint, requests, responses = catalog_server
        +    responses.extend([(200, {"namespaces": []}), (200, {"tables": []})])
        +    settings = {
        +        "uri": "db://analytics",
        +        "api_key": "shared-secret",
        +        "region": region,
        +        "host_override": endpoint,
        +        "sql_host_override": "invalid://localhost",
        +        "read_consistency_interval": timedelta(seconds=5),
        +        "client_config": {"extra_headers": {"x-shared-setting": "shared"}},
        +        "storage_options": {"azure_storage_account_name": "shared-account"},
        +        "session": None,
        +        "manifest_enabled": False,
        +        "namespace_client_properties": None,
        +    }
        +    if not asynchronous:
        +        settings.update(
        +            request_thread_pool=None,
        +            namespace_client_impl=None,
        +            namespace_client_pushdown_operations=None,
        +        )
        +    with pytest.warns(
        +        UserWarning, match="region is ignored by connect_catalog"
        +    ) as caught:
        +        catalog = (
        +            await lancedb.connect_catalog_async(**settings)
        +            if asynchronous
        +            else lancedb.connect_catalog(**settings)
        +        )
        +    assert len(caught) == 1
        +    assert catalog.uri == endpoint
        +    assert (
        +        [name async for name in catalog.list_databases()]
        +        if asynchronous
        +        else list(catalog.list_databases())
        +    ) == []
        +    db = (
        +        await lancedb.connect_async(**settings)
        +        if asynchronous
        +        else lancedb.connect(**settings)
        +    )
        +    assert (await db.table_names() if asynchronous else db.table_names()) == []
        +    root_headers = {key.lower(): value for key, value in requests[0][1].items()}
        +    db_headers = {key.lower(): value for key, value in requests[1][1].items()}
        +    for headers in (root_headers, db_headers):
        +        assert headers["x-api-key"] == "shared-secret"
        +        assert headers["x-shared-setting"] == "shared"
        +        assert headers["x-azure-storage-account-name"] == "shared-account"
        +    assert "x-lancedb-database" not in root_headers
        +    assert db_headers["x-lancedb-database"] == "analytics"
        +
        +
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize("host_only", [False, True])
        +@pytest.mark.asyncio
        +async def test_catalog_default_region_is_silent_and_api_key_uses_environment(
        +    catalog_server, monkeypatch, asynchronous, host_only
        +):
        +    endpoint, requests, responses = catalog_server
        +    monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret")
        +    responses.extend([(200, {}), (200, {"tables": []})])
        +    settings = {"host_override": endpoint} if host_only else {"uri": endpoint}
        +    with warnings.catch_warnings(record=True) as caught:
        +        warnings.simplefilter("always")
        +        catalog = (
        +            await lancedb.connect_catalog_async(**settings)
        +            if asynchronous
        +            else lancedb.connect_catalog(**settings)
        +        )
        +    assert caught == []
        +    assert catalog.uri == endpoint
        +    db = (
        +        await catalog.connect_database("analytics")
        +        if asynchronous
        +        else catalog.connect_database("analytics")
        +    )
        +    if not asynchronous:
        +        db = lancedb.deserialize_conn(db.serialize())
        +    assert (await db.table_names() if asynchronous else db.table_names()) == []
        +    for _, headers, _ in requests:
        +        headers = {key.lower(): value for key, value in headers.items()}
        +        assert headers["x-api-key"] == "environment-secret"
        +
        +
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.asyncio
        +async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous):
        +    endpoint, _, _ = catalog_server
        +    settings = {"uri": "https://unused.example", "host_override": endpoint}
        +    catalog = (
        +        await lancedb.connect_catalog_async(**settings)
        +        if asynchronous
        +        else lancedb.connect_catalog(**settings)
        +    )
        +    assert catalog.uri == endpoint
        +
        +
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "options, message",
        +    [
        +        ({}, "uri or host_override is required"),
        +        ({"session": object()}, "session"),
        +        ({"manifest_enabled": True}, "manifest_enabled"),
        +        ({"namespace_client_properties": {}}, "namespace_client_properties"),
        +    ],
        +)
        +@pytest.mark.asyncio
        +async def test_catalog_rejects_unsupported_connection_settings(
        +    catalog_server, asynchronous, options, message
        +):
        +    _, requests, _ = catalog_server
        +    error = NotImplementedError if options else ValueError
        +    with pytest.raises(error, match=message):
        +        if asynchronous:
        +            await lancedb.connect_catalog_async(**options)
        +        else:
        +            lancedb.connect_catalog(**options)
        +    assert requests == []
        +
        +
        +@pytest.mark.parametrize(
        +    "options, error, message",
        +    [
        +        (
        +            {"namespace_client_impl": "dir"},
        +            NotImplementedError,
        +            "namespace_client_impl",
        +        ),
        +        (
        +            {"namespace_client_pushdown_operations": []},
        +            NotImplementedError,
        +            "namespace_client_pushdown_operations",
        +        ),
        +        ({"unknown_option": True}, ValueError, "Unknown keyword arguments"),
        +    ],
        +)
        +def test_catalog_rejects_unsupported_sync_settings(options, error, message):
        +    with pytest.raises(error, match=message):
        +        lancedb.connect_catalog(**options)
        +
        +
        +def test_catalog_accepts_deprecated_sync_settings(catalog_server):
        +    endpoint, _, responses = catalog_server
        +    responses.append((200, {}))
        +    with pytest.warns(DeprecationWarning) as caught:
        +        catalog = lancedb.connect_catalog(
        +            endpoint,
        +            request_thread_pool=2,
        +            connection_timeout=5,
        +            read_timeout=10,
        +        )
        +    assert len(caught) == 3
        +    db = catalog.connect_database("analytics")
        +    assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5)
        +    assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10)
        +
        +
         @pytest.mark.parametrize("asynchronous", [False, True])
         @pytest.mark.asyncio
         @pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)])
        diff --git a/python/python/tests/test_cleanup.py b/python/python/tests/test_cleanup.py
        new file mode 100644
        index 000000000..944594b21
        --- /dev/null
        +++ b/python/python/tests/test_cleanup.py
        @@ -0,0 +1,187 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import json
        +
        +import pyarrow as pa
        +import pytest
        +
        +import lancedb
        +from lancedb.cleanup import CleanupResult
        +from test_remote_db import _create_table_handler, _mock_remote_sql_connection
        +
        +
        +@pytest.mark.parametrize("counts", [(0, 0), (2, 123), (None, None)])
        +def test_cleanup_result_preserves_measurements(counts):
        +    versions, size = counts
        +    result = CleanupResult.from_json(
        +        json.dumps(
        +            {
        +                "format_version": 1,
        +                "min_age_seconds": 0,
        +                "statistics_complete": versions is not None,
        +                "old_versions": versions,
        +                "bytes_removed": size,
        +                "future": True,
        +            }
        +        )
        +    )
        +    assert result.old_versions == versions
        +    assert result.bytes_removed == size
        +
        +
        +@pytest.mark.parametrize(
        +    "payload",
        +    [
        +        None,
        +        {},
        +        {"format_version": 2},
        +        {
        +            "format_version": 1,
        +            "min_age_seconds": 0,
        +            "statistics_complete": False,
        +            "old_versions": 1,
        +        },
        +    ],
        +)
        +def test_cleanup_result_rejects_missing_unknown_or_inconsistent_contract(payload):
        +    with pytest.raises(ValueError):
        +        CleanupResult.from_json(json.dumps(payload))
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "outcome", ["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"]
        +)
        +async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    polls = []
        +    result = {
        +        "format_version": 1,
        +        "min_age_seconds": 0,
        +        "statistics_complete": outcome != "unknown",
        +        "old_versions": None
        +        if outcome == "unknown"
        +        else 0
        +        if outcome == "no_op"
        +        else 2,
        +        "bytes_removed": None
        +        if outcome == "unknown"
        +        else 0
        +        if outcome == "no_op"
        +        else 123,
        +    }
        +
        +    class Server(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            return flight.RecordBatchStream(pa.table({"job_id": ["cleanup-job"]}))
        +
        +    def handler(request):
        +        if request.path != "/v1/jobs/describe":
        +            return _create_table_handler(request)
        +        polls.append(
        +            json.loads(request.rfile.read(int(request.headers["Content-Length"])))
        +        )
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(
        +            json.dumps(
        +                {
        +                    "job_id": "cleanup-job",
        +                    "job_type": "cleanup",
        +                    "job_state": outcome
        +                    if outcome in ("FAILED", "CANCELLED")
        +                    else "DONE",
        +                    "result": None if outcome == "missing" else result,
        +                }
        +            ).encode()
        +        )
        +
        +    server = Server()
        +    with _mock_remote_sql_connection(server, handler) as kwargs:
        +        if asynchronous:
        +            db = await lancedb.connect_async(**kwargs)
        +            table = await db.create_table("test", [{"id": 1}])
        +            job = await table.cleanup_async(min_age_seconds=0)
        +        else:
        +            db = lancedb.connect(**kwargs)
        +            table = db.create_table("test", [{"id": 1}])
        +            job = table.cleanup_async(min_age_seconds=0)
        +        assert job.id() == "cleanup-job" and not polls
        +        if outcome in ("missing", "FAILED", "CANCELLED"):
        +            with pytest.raises(
        +                Exception,
        +                match={
        +                    "missing": "did not contain a result",
        +                    "FAILED": "failed",
        +                    "CANCELLED": "cancel",
        +                }[outcome],
        +            ):
        +                if asynchronous:
        +                    await job.wait()
        +                else:
        +                    job.wait()
        +        else:
        +            stats = await job.wait() if asynchronous else job.wait()
        +            assert isinstance(stats, CleanupResult)
        +            assert stats.old_versions == result["old_versions"]
        +            reopened = (
        +                await db.open_job(job.id()) if asynchronous else db.open_job(job.id())
        +            )
        +            assert (await reopened.wait() if asynchronous else reopened.wait()) == stats
        +    assert len(server.tickets) == 1
        +    assert b"VACUUM" in server.tickets[0]
        +    assert b"min_age_seconds = 0" in server.tickets[0]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +async def test_cleanup_preview_is_read_only(asynchronous):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    payload = {
        +        "format_version": 1,
        +        "source_version": 42,
        +        "min_age_seconds": 0,
        +        "cutoff_millis": 123,
        +        "versions_to_remove": 2,
        +        "bytes_to_remove": 100,
        +    }
        +
        +    class Server(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            return flight.RecordBatchStream(
        +                pa.table({"plan_type": ["logical_plan"], "plan": [json.dumps(payload)]})
        +            )
        +
        +    def handler(request):
        +        assert not request.path.startswith("/v1/jobs"), (
        +            "preview must not submit/monitor jobs"
        +        )
        +        return _create_table_handler(request)
        +
        +    server = Server()
        +    with _mock_remote_sql_connection(server, handler) as kwargs:
        +        if asynchronous:
        +            db = await lancedb.connect_async(**kwargs)
        +            table = await db.create_table("test", [{"id": 1}])
        +            plan = await table.explain_cleanup(min_age_seconds=0)
        +        else:
        +            db = lancedb.connect(**kwargs)
        +            table = db.create_table("test", [{"id": 1}])
        +            plan = table.explain_cleanup(min_age_seconds=0)
        +        assert plan.source_version == 42
        +        assert plan.versions_to_remove == 2
        +    assert len(server.tickets) == 1
        +    assert b"EXPLAIN (FORMAT JSON) VACUUM" in server.tickets[0]
        diff --git a/python/python/tests/test_clone_creation.py b/python/python/tests/test_clone_creation.py
        new file mode 100644
        index 000000000..6c12420c5
        --- /dev/null
        +++ b/python/python/tests/test_clone_creation.py
        @@ -0,0 +1,36 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import pytest
        +
        +import lancedb
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous):
        +    source_uri = str(tmp_path / "source.lance")
        +    if asynchronous:
        +        db = await lancedb.connect_async(tmp_path)
        +        await db.create_table("source", [{"id": 1}])
        +        table = await db.clone_table("target", source_uri, exist_ok=True)
        +        assert (await table.to_arrow()).to_pylist() == [{"id": 1}]
        +        await table.add([{"id": 2}])
        +        version = await table.version()
        +        with pytest.raises(ValueError, match="already exists"):
        +            await db.clone_table("target", source_uri)
        +        kept = await db.clone_table("target", "missing.lance", exist_ok=True)
        +        assert await kept.version() == version
        +        assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}]
        +    else:
        +        db = lancedb.connect(tmp_path)
        +        db.create_table("source", [{"id": 1}])
        +        table = db.clone_table("target", source_uri, exist_ok=True)
        +        assert table.to_arrow().to_pylist() == [{"id": 1}]
        +        table.add([{"id": 2}])
        +        version = table.version
        +        with pytest.raises(ValueError, match="already exists"):
        +            db.clone_table("target", source_uri)
        +        kept = db.clone_table("target", "missing.lance", exist_ok=True)
        +        assert kept.version == version
        +        assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}]
        diff --git a/python/python/tests/test_cohere_embeddings.py b/python/python/tests/test_cohere_embeddings.py
        new file mode 100644
        index 000000000..a4bc8cc50
        --- /dev/null
        +++ b/python/python/tests/test_cohere_embeddings.py
        @@ -0,0 +1,319 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +from http.server import BaseHTTPRequestHandler, HTTPServer
        +import json
        +import os
        +import subprocess
        +import sys
        +from types import SimpleNamespace
        +
        +import lancedb
        +import pytest
        +from lancedb.embeddings import CohereEmbeddingFunction, get_registry
        +from lancedb.pydantic import LanceModel
        +from utils import start_server_thread
        +
        +
        +@pytest.fixture
        +def foundry_cohere(monkeypatch):
        +    pytest.importorskip("cohere", minversion="5.15.0")
        +    monkeypatch.setenv("NO_PROXY", "127.0.0.1")
        +    monkeypatch.setenv("no_proxy", "127.0.0.1")
        +    monkeypatch.setenv("COHERE_API_KEY", "test-hosted-key")
        +    monkeypatch.setenv("TEST_FOUNDRY_COHERE_KEY", "test-foundry-key")
        +    registry = get_registry()
        +    monkeypatch.setattr(registry, "_allowed_endpoints", set())
        +    monkeypatch.setattr(registry, "_variables", {})
        +    registry.set_var("foundry-key", os.environ["TEST_FOUNDRY_COHERE_KEY"])
        +    requests = []
        +    statuses = {}
        +
        +    class EmbedHandler(BaseHTTPRequestHandler):
        +        def do_POST(self):
        +            body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        +            requests.append((self.path, self.headers.get("Authorization"), body))
        +            status = statuses.pop(body["texts"][0], None)
        +            if status is not None:
        +                self.send_response(status)
        +                if status == 307:
        +                    self.send_header("Location", "/redirect-target/v2/embed")
        +                self.end_headers()
        +                return
        +            vectors = []
        +            for text in body["texts"]:
        +                matches = (body["input_type"], text) in {
        +                    ("search_document", "matching document"),
        +                    ("search_query", "matching query"),
        +                }
        +                if text == "wrong dimension":
        +                    vectors.append([0.0])
        +                else:
        +                    vectors.append(
        +                        ([1.0, 0.0] if matches else [0.0, 1.0]) + [0.0] * 254
        +                    )
        +            response = json.dumps(
        +                {
        +                    "id": "fixture",
        +                    "embeddings": {"float": vectors},
        +                    "texts": body["texts"],
        +                }
        +            ).encode()
        +            self.send_response(200)
        +            self.send_header("Content-Type", "application/json")
        +            self.end_headers()
        +            self.wfile.write(response)
        +
        +        def log_message(self, *args):
        +            pass
        +
        +    with HTTPServer(("127.0.0.1", 0), EmbedHandler) as server:
        +        thread = start_server_thread(server)
        +        try:
        +            options = {
        +                "name": "my-embed-v4-deployment",
        +                "base_url": f"http://127.0.0.1:{server.server_port}/providers/cohere",
        +                "output_dimension": 256,
        +                "api_key": "$var:foundry-key",
        +            }
        +            yield options, requests, statuses
        +        finally:
        +            server.shutdown()
        +            thread.join()
        +
        +
        +def test_foundry_cohere_retrieval_and_endpoint_trust(
        +    foundry_cohere, monkeypatch, tmp_path
        +):
        +    import httpx
        +
        +    options, requests, _ = foundry_cohere
        +    func = get_registry().get("cohere").create(**options)
        +    request_timeouts = []
        +    handle_request = httpx.HTTPTransport.handle_request
        +
        +    def record_request_timeout(transport, request):
        +        request_timeouts.append(request.extensions.get("timeout"))
        +        return handle_request(transport, request)
        +
        +    monkeypatch.setattr(httpx.HTTPTransport, "handle_request", record_request_timeout)
        +
        +    class Document(LanceModel):
        +        text: str = func.SourceField()
        +        vector: list[float] = func.VectorField()
        +
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("docs", schema=Document)
        +    table.add([{"text": "distractor"}, {"text": "matching document"}])
        +    reopened = lancedb.connect(tmp_path).open_table("docs")
        +    assert reopened.schema.field("vector").type.list_size == 256
        +    metadata = reopened.schema.metadata[b"embedding_functions"]
        +    assert b"test-foundry-key" not in metadata
        +    assert json.loads(metadata) == [
        +        {
        +            "name": "cohere",
        +            "model": options,
        +            "source_column": "text",
        +            "vector_column": "vector",
        +        }
        +    ]
        +    assert reopened.search("matching query").limit(1).to_list()[0]["text"] == (
        +        "matching document"
        +    )
        +    assert (
        +        request_timeouts
        +        == [{"connect": 300, "read": 300, "write": 300, "pool": 300}] * 2
        +    )
        +
        +    # A fresh interpreter has the key but must separately trust the stored URL.
        +    child = subprocess.run(
        +        [
        +            sys.executable,
        +            "-c",
        +            """
        +import os
        +import sys
        +
        +import lancedb
        +from lancedb.embeddings import UntrustedEmbeddingConfigError, get_registry
        +
        +registry = get_registry()
        +registry.set_var("foundry-key", os.environ["TEST_FOUNDRY_COHERE_KEY"])
        +db = lancedb.connect(sys.argv[1])
        +try:
        +    db.open_table("docs").search("matching query").limit(1).to_list()
        +except UntrustedEmbeddingConfigError as error:
        +    assert sys.argv[2] in str(error)
        +else:
        +    raise AssertionError("The stored endpoint needs explicit approval")
        +registry.allow_endpoint(sys.argv[2])
        +assert db.open_table("docs").search("matching query").limit(1).to_list()[0][
        +    "text"
        +] == "matching document"
        +""",
        +            str(tmp_path),
        +            options["base_url"],
        +        ],
        +        capture_output=True,
        +        text=True,
        +        timeout=30,
        +    )
        +    assert child.returncode == 0, child.stderr
        +    assert requests == [
        +        (
        +            "/providers/cohere/v2/embed",
        +            "Bearer test-foundry-key",
        +            {
        +                "model": "my-embed-v4-deployment",
        +                "texts": texts,
        +                "input_type": input_type,
        +                "output_dimension": 256,
        +                "embedding_types": ["float"],
        +            },
        +        )
        +        for input_type, texts in [
        +            ("search_document", ["distractor", "matching document"]),
        +            ("search_query", ["matching query"]),
        +            ("search_query", ["matching query"]),
        +        ]
        +    ]
        +
        +
        +def test_foundry_cohere_retries_only_failed_batch(foundry_cohere, monkeypatch):
        +    options, requests, statuses = foundry_cohere
        +    backoffs = []
        +    monkeypatch.setattr(
        +        "lancedb.embeddings.utils.time", SimpleNamespace(sleep=backoffs.append)
        +    )
        +    func = CohereEmbeddingFunction.create(**options, max_retries=1)
        +    texts = [f"document {index}" for index in range(96)] + ["matching document"]
        +    statuses["matching document"] = 429
        +    vectors = func.compute_source_embeddings_with_retry(texts)
        +    assert [body["texts"] for _, _, body in requests] == [
        +        texts[:96],
        +        texts[96:],
        +        texts[96:],
        +    ]
        +    assert len(backoffs) == 1
        +    assert [vector[:2] for vector in vectors] == [[0.0, 1.0]] * 96 + [[1.0, 0.0]]
        +
        +
        +def test_foundry_cohere_rejects_invalid_inputs_and_vectors(foundry_cohere, monkeypatch):
        +    options, requests, _ = foundry_cohere
        +    monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail)
        +    func = CohereEmbeddingFunction.create(**options)
        +    with pytest.raises(ValueError, match="unexpected dimension"):
        +        func.compute_query_embeddings_with_retry("wrong dimension")
        +    with pytest.raises(ValueError, match="requires string inputs"):
        +        func.compute_source_embeddings_with_retry([b"image"])
        +    assert len(requests) == 1
        +
        +
        +@pytest.mark.parametrize(
        +    "input_type", ["search_document", "search_query"], ids=["add", "search"]
        +)
        +def test_foundry_cohere_does_not_retry_or_follow_endpoint_redirect(
        +    foundry_cohere, monkeypatch, tmp_path, input_type
        +):
        +    from cohere.core.api_error import ApiError
        +
        +    options, requests, statuses = foundry_cohere
        +    func = CohereEmbeddingFunction.create(**options, max_retries=2)
        +
        +    class Document(LanceModel):
        +        text: str = func.SourceField()
        +        vector: list[float] = func.VectorField()
        +
        +    table = lancedb.connect(tmp_path).create_table("docs", schema=Document)
        +    table.add([{"text": "seed", "vector": [0.0] * 256}])
        +    backoffs = []
        +    monkeypatch.setattr(
        +        "lancedb.embeddings.utils.time", SimpleNamespace(sleep=backoffs.append)
        +    )
        +    statuses["redirected text"] = 307
        +
        +    if input_type == "search_document":
        +        with pytest.raises(RuntimeError, match=r"ApiError:.*status_code: 307"):
        +            table.add([{"text": "redirected text"}])
        +    else:
        +        with pytest.raises(ApiError) as error:
        +            table.search("redirected text").limit(1).to_list()
        +        assert error.value.status_code == 307
        +
        +    assert backoffs == []
        +    assert [
        +        (path, body["input_type"], body["texts"]) for path, _, body in requests
        +    ] == [("/providers/cohere/v2/embed", input_type, ["redirected text"])]
        +
        +
        +@pytest.mark.parametrize(
        +    "overrides, message",
        +    [
        +        ({"name": ""}, "deployed Cohere model"),
        +        ({"output_dimension": None}, "requires output_dimension and api_key"),
        +        ({"output_dimension": 0}, "greater than 0"),
        +        ({"api_key": None}, "requires output_dimension and api_key"),
        +        ({"api_key": "test-plaintext-key"}, "cannot be set to a hardcoded value"),
        +        ({"api_key": "$var:foundry-key:test-plaintext-key"}, "without a default"),
        +        ({"query_input_type": "classification"}, "search_query for queries"),
        +        ({"base_url": None}, "require base_url"),
        +        ({"base_url": "http://user:password@127.0.0.1"}, "without credentials"),
        +    ],
        +)
        +def test_foundry_cohere_validates_config(monkeypatch, overrides, message):
        +    registry = get_registry()
        +    monkeypatch.setattr(registry, "_variables", {"foundry-key": "test-foundry-key"})
        +    options = {
        +        "name": "embed-v-4-0",
        +        "base_url": "http://127.0.0.1/providers/cohere",
        +        "output_dimension": 256,
        +        "api_key": "$var:foundry-key",
        +    }
        +    with pytest.raises(ValueError, match=message):
        +        registry.get("cohere").create(**(options | overrides))
        +
        +
        +def test_cohere_legacy_metadata_and_v1_client(monkeypatch):
        +    requests = []
        +
        +    class LegacyClient:
        +        def __init__(self, key):
        +            assert key == "test-hosted-key"
        +
        +        def embed(self, **body):
        +            requests.append(body)
        +            return SimpleNamespace(embeddings=[[1.0, 2.0]])
        +
        +    monkeypatch.setitem(sys.modules, "cohere", SimpleNamespace(Client=LegacyClient))
        +    monkeypatch.setenv("COHERE_API_KEY", "test-hosted-key")
        +    monkeypatch.setattr(CohereEmbeddingFunction, "client", None)
        +    registry = get_registry()
        +    func = registry.get("cohere").create()
        +    assert func.ndims() == 1024
        +    assert func.safe_model_dump() == {}
        +    assert func.compute_source_embeddings(["default document"]) == [[1.0, 2.0]]
        +
        +    # This schema predates the custom endpoint parameters.
        +    stored = {
        +        "name": "cohere",
        +        "model": {"name": "embed-multilingual-v2.0", "query_input_type": "clustering"},
        +        "source_column": "text",
        +        "vector_column": "vector",
        +    }
        +    metadata = {b"embedding_functions": json.dumps([stored]).encode()}
        +    old_func = registry.parse_functions(metadata)["vector"].function
        +    assert old_func.ndims() == 768
        +    assert old_func.safe_model_dump() == stored["model"]
        +    assert old_func.compute_query_embeddings("legacy query") == [[1.0, 2.0]]
        +    assert requests == [
        +        {
        +            "texts": ["default document"],
        +            "model": "embed-multilingual-v3.0",
        +            "input_type": "search_document",
        +        },
        +        {
        +            "texts": ["legacy query"],
        +            "model": "embed-multilingual-v2.0",
        +            "input_type": "clustering",
        +        },
        +    ]
        diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py
        index 64bf928c0..5656f5203 100644
        --- a/python/python/tests/test_db.py
        +++ b/python/python/tests/test_db.py
        @@ -4,6 +4,7 @@
         
         import contextlib
         import inspect
        +import pickle
         import re
         import sys
         from datetime import timedelta
        @@ -69,6 +70,29 @@ def test_basic(tmp_path):
             assert db.open_table("test").name == db["test"].name
         
         
        +def test_lance_db_connection_pickle_roundtrip(tmp_path):
        +    interval = timedelta(seconds=2)
        +    db = lancedb.connect(tmp_path, read_consistency_interval=interval)
        +    db.create_table("pickle_conn", pa.table({"id": [1, 2]}))
        +
        +    restored = pickle.loads(pickle.dumps(db))
        +
        +    assert restored.uri == str(tmp_path)
        +    assert restored.read_consistency_interval == interval
        +    assert restored.open_table("pickle_conn").to_arrow()["id"].to_pylist() == [1, 2]
        +
        +
        +def test_lance_db_connection_pickle_preserves_zero_read_consistency(tmp_path):
        +    db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
        +    table = db.create_table("pickle_zero", pa.table({"id": [1]}))
        +
        +    restored_db, restored_table = pickle.loads(pickle.dumps((db, table)))
        +    lancedb.connect(tmp_path).open_table("pickle_zero").add(pa.table({"id": [2]}))
        +
        +    assert restored_db.read_consistency_interval == timedelta(0)
        +    assert restored_table.to_arrow()["id"].to_pylist() == [1, 2]
        +
        +
         def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeypatch):
             from lancedb.background_loop import LOOP
         
        @@ -282,9 +306,7 @@ async def test_table_listing_defaults_and_zero_limit(tmp_path):
             assert empty.page_token is None
         
         
        -def test_db_contains_stops_after_matching_table_page(
        -    tmp_db: lancedb.DBConnection, monkeypatch
        -):
        +def test_db_len_includes_all_table_pages(tmp_db: lancedb.DBConnection, monkeypatch):
             calls = []
             pages = {
                 None: SimpleNamespace(tables=["table_0", "table_1"], page_token="next"),
        @@ -297,18 +319,44 @@ def test_db_contains_stops_after_matching_table_page(
         
             monkeypatch.setattr(tmp_db, "list_tables", list_tables)
         
        -    assert "table_1" in tmp_db
        -    assert calls == [None]
        -
        -    calls.clear()
        -    assert "table_2" in tmp_db
        -    assert calls == [None, "next"]
        -
        -    calls.clear()
             assert len(tmp_db) == 3
             assert calls == [None, "next"]
         
         
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("namespace_path", [[], ["analytics", "nested"]])
        +async def test_local_table_exists_without_listing(
        +    tmp_path, monkeypatch, namespace_path
        +):
        +    db = lancedb.connect(tmp_path)
        +    for depth in range(1, len(namespace_path) + 1):
        +        db.create_namespace(namespace_path[:depth])
        +    db.create_table("events", data=[{"id": 1}], namespace_path=namespace_path)
        +    if not namespace_path:
        +        for idx in range(100):
        +            (tmp_path / f"a{idx:03}.lance").mkdir()
        +        assert "events" not in db.list_tables().tables
        +    adb = await lancedb.connect_async(tmp_path)
        +
        +    def fail_listing(*args, **kwargs):
        +        raise AssertionError("Existence checks must not list tables")
        +
        +    monkeypatch.setattr(db, "list_tables", fail_listing)
        +    monkeypatch.setattr(adb, "list_tables", fail_listing)
        +    table_id = namespace_path + ["events"]
        +    assert db.table_exists(table_id) is True
        +    assert await adb.table_exists(table_id) is True
        +    assert db.table_exists(namespace_path + ["missing"]) is False
        +    assert await adb.table_exists(namespace_path + ["missing"]) is False
        +    assert ("events" in db) is (not namespace_path)
        +    assert "missing" not in db
        +    assert table_id == namespace_path + ["events"]
        +
        +    db.drop_table("events", namespace_path=namespace_path)
        +    assert db.table_exists(table_id) is False
        +    assert await adb.table_exists(table_id) is False
        +
        +
         @pytest.mark.asyncio
         async def test_table_names_async(tmp_path):
             db = lancedb.connect(tmp_path)
        @@ -821,6 +869,35 @@ def test_open_table_sync(tmp_db: lancedb.DBConnection):
                 tmp_db.open_table("does_not_exist")
         
         
        +def test_open_table_sync_with_location(tmp_path):
        +    db = lancedb.connect(tmp_path / "db")
        +    db.create_table("test", data=[{"id": 0}])
        +    dataset_path = tmp_path / "db" / "test.lance"
        +
        +    other_db = lancedb.connect(tmp_path / "other")
        +    opened = other_db.open_table("test", location=str(dataset_path))
        +    assert opened.name == "test"
        +    assert opened.count_rows() == 1
        +
        +
        +def test_open_table_sync_lance_dataset_path_hint(tmp_path):
        +    data_dir = tmp_path / "data"
        +    lancedb.connect(data_dir).create_table("embeddings", data=[{"id": 0}])
        +    dataset_db = lancedb.connect(data_dir / "embeddings.lance")
        +
        +    with pytest.raises(ValueError) as exc_info:
        +        dataset_db.open_table("embeddings")
        +    message = str(exc_info.value)
        +    assert "Table 'embeddings' was not found" in message
        +    assert "points to a Lance dataset rather than a database directory" in message
        +    assert f"parent directory '{data_dir}'" in message
        +    assert "open table 'embeddings' instead" in message
        +
        +    with pytest.raises(ValueError) as exc_info:
        +        dataset_db.open_table("missing", location=str(tmp_path / "missing.lance"))
        +    assert "points to a Lance dataset" not in str(exc_info.value)
        +
        +
         @pytest.mark.asyncio
         async def test_open_table(tmp_path):
             from conftest import pandas_string_type
        @@ -908,7 +985,7 @@ def test_drop_table_async(tmp_db: lancedb.DBConnection):
             assert tmp_db.table_names() == ["test"]
         
             job = tmp_db.drop_table_async("test")
        -    assert job.id is None
        +    assert job.id() is None
             assert job.status() == "finished"
             assert job.wait() is None
             assert tmp_db.table_names() == []
        @@ -924,7 +1001,7 @@ async def test_drop_table_async_connection(tmp_db_async: lancedb.AsyncConnection
             await tmp_db_async.create_table("test", data=pa.table({"id": [1, 2]}))
         
             job = await tmp_db_async.drop_table_async("test")
        -    assert job.id is None
        +    assert job.id() is None
             assert await job.status() == "finished"
             assert await job.wait() is None
             assert await tmp_db_async.table_names() == []
        diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py
        index 5a2f1e290..2bceb750f 100644
        --- a/python/python/tests/test_e2e_remote_db.py
        +++ b/python/python/tests/test_e2e_remote_db.py
        @@ -10,12 +10,140 @@ import lancedb
         import numpy as np
         import pyarrow as pa
         import pytest
        -from lancedb import LanceDBConnection, udf
        +from lancedb import LanceDBConnection, function
        +from lancedb.compaction import CompactionResult
         from lancedb.index import FTS
        +from lancedb.prewarm import PrewarmDataResult
         
         # TODO: setup integ test mark and script
         
         
        +@pytest.fixture
        +def maintenance_connection_options():
        +    uri = os.environ.get("LANCEDB_URI")
        +    if not uri:
        +        pytest.skip(
        +            "Set LANCEDB_URI to a server supporting SQL maintenance job results"
        +        )
        +    assert uri.startswith("db://")
        +    return {
        +        "uri": uri,
        +        "api_key": os.environ.get("LANCEDB_API_KEY"),
        +        "region": os.environ.get("LANCEDB_REGION", "us-east-1"),
        +        "host_override": os.environ.get("LANCEDB_HOST_OVERRIDE"),
        +        "sql_host_override": os.environ.get("LANCEDB_SQL_HOST_OVERRIDE"),
        +    }
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
        +@pytest.mark.parametrize("operation", ["compact", "prewarm", "prewarm_legacy"])
        +async def test_maintenance_job_result_and_reopen_against_server(
        +    maintenance_connection_options, asynchronous, operation
        +):
        +    """Exercise real SQL receipts, workers and HTTP job results with matching versions.
        +
        +    Configure LANCEDB_URI, LANCEDB_API_KEY and the REST/Flight SQL endpoint
        +    overrides for a writable database. Workers must publish maintenance results;
        +    an unsupported server fails the contract rather than silently skipping it.
        +    """
        +    if asynchronous:
        +        connection = await lancedb.connect_async(**maintenance_connection_options)
        +    else:
        +        connection = lancedb.connect(**maintenance_connection_options)
        +
        +    async def call(method, *args, **kwargs):
        +        result = method(*args, **kwargs)
        +        return await result if asynchronous else result
        +
        +    name = f"maintenance_{uuid4().hex}"
        +    created = False
        +    expected = [{"id": i, "payload": i * 10} for i in range(16)]
        +    timeout = timedelta(minutes=5)
        +    try:
        +        table = await call(
        +            connection.create_table, name, pa.Table.from_pylist(expected[:4])
        +        )
        +        created = True
        +        for start in (4, 8, 12):
        +            await call(table.add, pa.Table.from_pylist(expected[start : start + 4]))
        +        version = await table.version() if asynchronous else table.version
        +        if operation == "compact":
        +            job = await call(
        +                table.compact_async,
        +                compaction_options={
        +                    "target_rows_per_fragment": 100,
        +                    "batch_size": 128,
        +                    "io_buffer_size": 0,
        +                },
        +            )
        +        elif operation == "prewarm_legacy":
        +            assert (
        +                await call(
        +                    table.prewarm_data,
        +                    ["payload"],
        +                    filter="id >= 8",
        +                    concurrency=2,
        +                )
        +                is None
        +            )
        +            reader = await call(
        +                connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"'
        +            )
        +            batches = await call(reader.read_all)
        +            jobs = pa.Table.from_batches(batches) if asynchronous else batches
        +            ids = [
        +                row["job_id"]
        +                for row in jobs.to_pylist()
        +                if row["job_type"] == "prewarm_page_cache"
        +            ]
        +            assert len(ids) == 1, jobs.to_pylist()
        +            job = await call(connection.open_job, ids[0])
        +        else:
        +            job = await call(
        +                table.prewarm_data_async,
        +                ["payload"],
        +                filter="id >= 8",
        +                concurrency=2,
        +            )
        +        assert job.id()
        +        progress = []
        +        result = await call(job.wait, timeout=timeout, progress=progress.append)
        +        assert any(snapshot["state"] == "finished" for snapshot in progress)
        +        await call(job.refresh)
        +        assert await call(job.status) == "finished"
        +        if operation == "compact":
        +            assert isinstance(result, CompactionResult)
        +            assert job.job_type() == "compact"
        +            assert not result.partial_commit and result.rows_failed == 0
        +            assert result.completion_percentage == 100
        +            assert 0 <= result.rows_succeeded <= len(expected)
        +            assert result.files_added is not None and result.files_removed is not None
        +        else:
        +            assert isinstance(result, PrewarmDataResult)
        +            assert job.job_type() == "prewarm_page_cache"
        +            assert result.table_version == version == job.spec()["table_version"]
        +            assert job.spec()["columns"] == ["payload"]
        +            assert job.spec()["concurrency"] == 2
        +            assert result.fragments_selected > 0
        +            assert result.executors_completed == result.executors_targeted
        +            assert result.executors_partial == 0
        +            assert result.bytes_read is None and result.ranges_completed is None
        +        reopened = await call(connection.open_job, job.id())
        +        assert await call(reopened.wait, timeout=timeout) == result
        +        query = table.query() if asynchronous else table.search()
        +        actual = await call(
        +            query.select(["id", "payload"]).limit(len(expected) + 1).to_arrow
        +        )
        +        assert sorted(actual.to_pylist(), key=lambda row: row["id"]) == expected
        +    finally:
        +        try:
        +            if created:
        +                await call(connection.drop_table, name)
        +        finally:
        +            connection.close()
        +
        +
         @pytest.mark.skipif(
             not os.environ.get("LANCEDB_URI"), reason="Set LANCEDB_URI to a JSON FTS server"
         )
        @@ -98,7 +226,7 @@ def test_function_execution_controls_through_sql_and_materialized_view():
             view_name = f"batch_probe_view_{suffix}"
             registered_version = None
         
        -    @udf(
        +    @function(
                 name=function_name,
                 input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
                 output_schema=pa.int64(),
        @@ -180,3 +308,65 @@ def test_against_local_server():
             table = conn.open_table("sift1m_ivf1024_pq16")
             df = table.search(np.random.rand(128)).to_pandas()
             assert len(df) == 10
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
        +async def test_prewarm_preview_against_server(
        +    maintenance_connection_options, asynchronous
        +):
        +    """Preview is typed, source-versioned, and creates no maintenance jobs."""
        +    from lancedb.prewarm import PrewarmDataPlan
        +
        +    connection = (
        +        await lancedb.connect_async(**maintenance_connection_options)
        +        if asynchronous
        +        else lancedb.connect(**maintenance_connection_options)
        +    )
        +
        +    async def call(method, *args, **kwargs):
        +        result = method(*args, **kwargs)
        +        return await result if asynchronous else result
        +
        +    async def jobs():
        +        reader = await call(connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"')
        +        result = await call(reader.read_all)
        +        if asynchronous:
        +            return [row for batch in result for row in batch.to_pylist()]
        +        return result.to_pylist()
        +
        +    name = f"preview_{uuid4().hex}"
        +    created = False
        +    try:
        +        table = await call(connection.create_table, name, [{"id": 1, "payload": "one"}])
        +        created = True
        +        version = await table.version() if asynchronous else table.version
        +        before = await jobs()
        +        for predicate, mode, selected in [
        +            (None, "unfiltered", 1),
        +            ("TRUE", "full_warm_fallback", 1),
        +            ("FALSE", "constant", 0),
        +            ("id > 10", "full_warm_fallback", 1),
        +        ]:
        +            preview = await call(
        +                table.explain_prewarm_data, ["payload"], filter=predicate, concurrency=2
        +            )
        +            assert isinstance(preview, PrewarmDataPlan)
        +            assert preview.table_version == version
        +            assert preview.pruning.mode == mode
        +            assert preview.pruning.input_fragments == 1
        +            assert preview.pruning.selected_fragments == selected
        +            if mode == "full_warm_fallback":
        +                assert preview.pruning.fallback_reason
        +        assert await jobs() == before
        +        assert (await table.version() if asynchronous else table.version) == version
        +        # A preview does not reserve the source snapshot for a later request.
        +        await call(table.add, [{"id": 2, "payload": "two"}])
        +        newer = await call(table.explain_prewarm_data)
        +        assert newer.table_version > version
        +        assert newer.pruning.input_fragments == 2
        +        assert await jobs() == before
        +    finally:
        +        if created:
        +            await call(connection.drop_table, name)
        +        connection.close()
        diff --git a/python/python/tests/test_eager_collector.py b/python/python/tests/test_eager_collector.py
        new file mode 100644
        index 000000000..1eaed9678
        --- /dev/null
        +++ b/python/python/tests/test_eager_collector.py
        @@ -0,0 +1,57 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +from datetime import timedelta
        +
        +import pyarrow as pa
        +import pytest
        +
        +import lancedb
        +
        +
        +@pytest.mark.asyncio
        +async def test_execute_to_reader_collects_without_default_slicing(tmp_path):
        +    db = await lancedb.connect_async(tmp_path)
        +    rows = 5000
        +    data = pa.table(
        +        {
        +            "id": pa.array(range(rows), type=pa.int64()),
        +            "text": pa.array([f"row-{i}" for i in range(rows)]),
        +        }
        +    )
        +    table = await db.create_table("test", data)
        +
        +    reader = await table._inner.query().execute_to_reader(None, None)
        +    batches = list(reader)
        +
        +    assert sum(batch.num_rows for batch in batches) == rows
        +    assert max(batch.num_rows for batch in batches) > 1024
        +
        +
        +@pytest.mark.asyncio
        +async def test_execute_to_reader_preserves_empty_schema(tmp_path):
        +    db = await lancedb.connect_async(tmp_path)
        +    data = pa.table(
        +        {
        +            "id": pa.array([1, 2], type=pa.int64()),
        +            "text": pa.array(["a", "b"]),
        +        }
        +    )
        +    table = await db.create_table("test", data)
        +
        +    query = table._inner.query()
        +    query.where("id < 0")
        +    reader = await query.execute_to_reader(None, None)
        +    result = pa.Table.from_batches(reader, schema=reader.schema)
        +
        +    assert result.num_rows == 0
        +    assert result.schema == await table.query().where("id < 0").output_schema()
        +
        +
        +@pytest.mark.asyncio
        +async def test_execute_to_reader_propagates_timeout(tmp_path):
        +    db = await lancedb.connect_async(tmp_path)
        +    table = await db.create_table("test", data=[{"id": 1}, {"id": 2}])
        +
        +    with pytest.raises(Exception, match="Query timeout"):
        +        await table._inner.query().execute_to_reader(None, timedelta(0))
        diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py
        index e9fb56c8a..6a70ddba3 100644
        --- a/python/python/tests/test_elastic_dataloader.py
        +++ b/python/python/tests/test_elastic_dataloader.py
        @@ -31,11 +31,15 @@ Parameters used throughout:
         """
         
         import dataclasses
        +import functools
         import logging
        +import multiprocessing as mp
        +import pickle
         import threading
         from unittest.mock import patch
         
         import lancedb
        +import numpy as np
         import pyarrow as pa
         import pytest
         from utils import (
        @@ -1028,6 +1032,105 @@ def test_multi_worker_elastic_det_across_worker_counts(lance_table):
                 )
         
         
        +# ── Worker start method defaults ─────────────────────────────────────────────
        +
        +
        +def _loader_start_method(loader: StreamingDataLoader) -> str:
        +    context = loader.multiprocessing_context
        +    if isinstance(context, str):
        +        return context
        +    assert context is not None
        +    return context.get_start_method()
        +
        +
        +def _platform_worker_start_method() -> str:
        +    return "forkserver" if "forkserver" in mp.get_all_start_methods() else "spawn"
        +
        +
        +def test_default_worker_start_method_prefers_forkserver():
        +    with patch.object(
        +        streaming,
        +        "get_all_start_methods",
        +        return_value=["fork", "spawn", "forkserver"],
        +    ):
        +        assert streaming._default_worker_start_method() == "forkserver"
        +
        +
        +def test_streaming_dataloader_falls_back_to_spawn_without_forkserver(lance_table):
        +    dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
        +    with patch.object(streaming, "get_all_start_methods", return_value=["spawn"]):
        +        loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1)
        +
        +    assert _loader_start_method(loader) == "spawn"
        +
        +
        +def test_streaming_dataloader_omitted_context_uses_platform_method(lance_table):
        +    dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
        +    loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1)
        +
        +    assert _loader_start_method(loader) == _platform_worker_start_method()
        +
        +
        +def test_streaming_dataloader_treats_none_context_as_omitted(lance_table):
        +    dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
        +    loader = StreamingDataLoader(
        +        dataset,
        +        batch_size=2,
        +        num_workers=1,
        +        multiprocessing_context=None,
        +    )
        +
        +    assert _loader_start_method(loader) == _platform_worker_start_method()
        +
        +
        +def test_streaming_dataloader_preserves_explicit_start_method(lance_table):
        +    dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
        +    loader = StreamingDataLoader(
        +        dataset,
        +        batch_size=2,
        +        num_workers=1,
        +        multiprocessing_context="spawn",
        +    )
        +
        +    assert _loader_start_method(loader) == "spawn"
        +
        +
        +def test_streaming_dataloader_preserves_explicit_context_object(lance_table):
        +    dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
        +    context = mp.get_context("spawn")
        +    loader = StreamingDataLoader(
        +        dataset,
        +        batch_size=2,
        +        num_workers=1,
        +        multiprocessing_context=context,
        +    )
        +
        +    assert loader.multiprocessing_context is context
        +
        +
        +def test_streaming_dataloader_zero_workers_leave_context_unset(lance_table):
        +    dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
        +    loader = StreamingDataLoader(dataset, batch_size=12, num_workers=0)
        +
        +    assert loader.multiprocessing_context is None
        +    ids = [row_id for batch in loader for row_id in batch["id"].tolist()]
        +    assert sorted(ids) == list(range(NUM_ROWS))
        +
        +
        +def test_streaming_dataloader_default_context_runs_real_worker(lance_table):
        +    dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
        +    loader = StreamingDataLoader(dataset, batch_size=12, num_workers=1)
        +    assert _loader_start_method(loader) == _platform_worker_start_method()
        +
        +    iterator = iter(loader)
        +    try:
        +        ids = [row_id for batch in iterator for row_id in batch["id"].tolist()]
        +    finally:
        +        iterator._shutdown_workers()
        +
        +    assert sorted(ids) == list(range(NUM_ROWS))
        +
        +
         # ── Resumability with num_workers ─────────────────────────────────────────────
         
         
        @@ -1079,6 +1182,74 @@ def test_streaming_dataloader_commits_only_consumed_worker_batches(tmp_path):
             assert remaining == uninterrupted == [[3, 4], [30, 40]]
         
         
        +def test_block_size_dataloader_workers_reconnect(tmp_path):
        +    """Block-mode datasets pickle with no permutation table and reopen per worker."""
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("block_workers", pa.table({"id": list(range(8))}))
        +    dataset = StreamingDataset(
        +        table,
        +        num_splits=2,
        +        shuffle=False,
        +        block_size=2,
        +    )
        +    loader = StreamingDataLoader(
        +        dataset,
        +        batch_size=2,
        +        num_workers=2,
        +        multiprocessing_context="spawn",
        +    )
        +    iterator = iter(loader)
        +    try:
        +        batches = [batch["id"].tolist() for batch in iterator]
        +    finally:
        +        iterator._shutdown_workers()
        +
        +    assert sorted(row for batch in batches for row in batch) == list(range(8))
        +
        +
        +@pytest.mark.parametrize("filter", [None, "id % 2 = 0"])
        +@pytest.mark.parametrize("reshuffle_blocks_per_epoch", [True, False])
        +def test_block_size_pickle_does_not_grow_with_block_count(
        +    tmp_path, reshuffle_blocks_per_epoch, filter
        +):
        +    """Spawned workers start serially once the pickle outgrows a pipe buffer."""
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("block_pickle", pa.table({"id": list(range(1 << 16))}))
        +
        +    def make(block_size):
        +        return StreamingDataset(
        +            table,
        +            num_splits=2,
        +            shuffle_seed=7,
        +            epoch=3,
        +            block_size=block_size,
        +            reshuffle_blocks_per_epoch=reshuffle_blocks_per_epoch,
        +            filter=filter,
        +        )
        +
        +    def pickled_state(dataset):
        +        # The fixed-size shared-memory counters only pickle while spawning a
        +        # child, and their size does not depend on the block count.
        +        state = dataset.__getstate__()
        +        for key in ("_worker_stats", "_untracked_worker_iteration", "_filled_count"):
        +            del state[key]
        +        return pickle.dumps(state)
        +
        +    few_blocks, many_blocks = make(1 << 12), make(4)
        +    few_size = len(pickled_state(few_blocks))
        +    many_size = len(pickled_state(many_blocks))
        +    assert many_size - few_size < 1024, (few_size, many_size)
        +    # A filter's per-live-row offsets must not ride along either.
        +    assert many_size < 64 * 1024, many_size
        +
        +    restored = StreamingDataset.__new__(StreamingDataset)
        +    restored.__setstate__(pickle.loads(pickled_state(many_blocks)))
        +    assert restored._block_perm == many_blocks._block_perm
        +    assert restored._block_perm != sorted(restored._block_perm)
        +    if filter is not None:
        +        np.testing.assert_array_equal(restored._live_offsets, many_blocks._live_offsets)
        +
        +
         def test_distributed_checkpoint_uses_rank_local_worker_boundary(tmp_path):
             db = lancedb.connect(tmp_path)
             table = db.create_table("rank_boundary", pa.table({"id": list(range(8))}))
        @@ -2993,6 +3164,36 @@ def _packed_dataset(table, pack_sequences, *, blocks_per_epoch, pad_id=0, **kwar
             )
         
         
        +def test_pack_sequences_checkpoint_with_block_size(tmp_path):
        +    table = _create_token_table(
        +        tmp_path,
        +        [[1], [2], [10, 11, 12, 13, 14, 15, 16, 17], [20]],
        +    )
        +    kwargs = dict(
        +        pack_sequences=5,
        +        blocks_per_epoch=4,
        +        num_splits=2,
        +        block_size=2,
        +    )
        +    reference = [
        +        block["input_ids"].tolist() for block in _packed_dataset(table, **kwargs)
        +    ]
        +
        +    dataset = _packed_dataset(table, **kwargs)
        +    iterator = iter(dataset)
        +    first_cycle = [next(iterator), next(iterator)]
        +    checkpoint = dataset.state_dict()
        +    iterator.close()
        +
        +    resumed = _packed_dataset(table, **kwargs)
        +    resumed.load_state_dict(checkpoint)
        +    remaining = [block["input_ids"].tolist() for block in resumed]
        +
        +    assert [block["input_ids"].tolist() for block in first_cycle] == reference[:2]
        +    assert checkpoint["blocks_emitted_per_split"] == [1, 1]
        +    assert remaining == reference[2:]
        +
        +
         def test_pack_sequences_emits_blocks_and_pads_final_tail(tmp_path):
             table = _create_token_table(tmp_path, [[1, 2], [3, 4], [5]])
             dataset = _packed_dataset(table, 6, blocks_per_epoch=2)
        @@ -3472,6 +3673,732 @@ def test_streaming_dataset_over_remote_table():
             assert_server_safe_row_id_requests(server)
         
         
        +class _ReorderingOffsetScanServer(MockPermutationServer):
        +    """Answers offset/limit pages as if the table's two fragments complete in a
        +    different order on each request, which remote scans are allowed to do."""
        +
        +    def _query(self, request, body):
        +        if "offset" in body and not body.get("filter"):
        +            rows = list(range(self.num_rows))
        +            half = self.num_rows // 2
        +            if body["offset"] >= half:
        +                rows = rows[half:] + rows[:half]
        +            start = body["offset"]
        +            return self._arrow(
        +                request, pa.table({"id": rows[start : start + body["k"]]})
        +            )
        +        return super()._query(request, body)
        +
        +
        +def test_two_phase_over_remote_table():
        +    """Unfiltered 2-phase reads of a remote table name each block's rows by
        +    _rowoffset: offset/limit pages have no cross-request order guarantee."""
        +    server = _ReorderingOffsetScanServer(num_rows=16)
        +
        +    with mock_remote_table(server) as table:
        +        ds = StreamingDataset(table, num_splits=2, block_size=4, shuffle=False)
        +        ids = [row["id"] for row in ds]
        +
        +    assert sorted(ids) == list(range(server.num_rows)), (
        +        "Every row of the remote table must be yielded exactly once"
        +    )
        +
        +
        +def test_two_phase_over_remote_table_filtered_and_shuffled():
        +    """2-phase's filtered live-offset precompute and take_offsets-based
        +    block reads both work against a remote table, including restoring
        +    take_offsets' unspecified order via the _rowoffset it also selects."""
        +    server = MockPermutationServer(num_rows=20)
        +    live_ids = list(range(16))  # 16 live rows -> 4 blocks, divides num_splits=2
        +
        +    with mock_remote_table(server) as table:
        +        ds = StreamingDataset(
        +            table,
        +            num_splits=2,
        +            block_size=4,
        +            shuffle=True,
        +            shuffle_seed=SHUFFLE_SEED,
        +            filter="id IN (" + ",".join(str(i) for i in live_ids) + ")",
        +            columns=["id"],
        +        )
        +        ids = [row["id"] for row in ds]
        +
        +    assert sorted(ids) == live_ids, "only live rows, each exactly once"
        +
        +
        +def test_two_phase_over_remote_table_does_not_pin_callers_handle():
        +    """_open_pinned_table() must not mutate the caller's own RemoteTable.
        +
        +    Without a connection_factory, the reopen helpers used for local/memory
        +    tables return the *same* RemoteTable object for the remote case (correct
        +    for their original cross-process pickling purpose, wrong for same-process
        +    reuse here).  Checking that object out to the block-mode pin would
        +    therefore pin -- and, since checkout_version != None marks a handle
        +    version-pinned -- effectively make read-only the caller's own live table,
        +    not an unrelated copy.
        +    """
        +    server = MockPermutationServer(num_rows=8)
        +
        +    with mock_remote_table(server) as table:
        +        assert table._checkout_version is None, "caller's table starts unpinned"
        +        ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
        +        list(ds)  # drive at least one _open_pinned_table() call
        +        assert table._checkout_version is None, (
        +            "iterating a 2-phase dataset must not pin the caller's own "
        +            "table handle to a fixed version"
        +        )
        +
        +
        +@functools.lru_cache
        +def _cached_open_table(uri, name):
        +    return lancedb.connect(uri).open_table(name)
        +
        +
        +@functools.lru_cache
        +def _cached_open_table_with_session(uri, name):
        +    return lancedb.connect(uri, session=lancedb.Session()).open_table(name)
        +
        +
        +class _ReturnsTable:
        +    def __init__(self, table):
        +        self.table = table
        +
        +    def __call__(self, name):
        +        return self.table
        +
        +
        +@pytest.mark.parametrize("connection", ["local", "session", "memory"])
        +def test_two_phase_does_not_pin_cached_factory_handle(tmp_path, connection):
        +    """A connection_factory may return a cached, caller-owned handle: pinning
        +    the dataset's snapshot must leave that handle writable, must not need a
        +    picklable connection, and must keep reading the construction snapshot
        +    after the handle's table changes."""
        +    if connection == "memory":
        +        table = lancedb.connect("memory://").create_table(
        +            "t", pa.table({"id": list(range(8))})
        +        )
        +        table.add(pa.table({"id": [100]}))
        +        table.delete("id = 100")  # the snapshot is at a version above 1
        +        factory = _ReturnsTable(table)
        +    else:
        +        lancedb.connect(tmp_path).create_table("t", pa.table({"id": list(range(8))}))
        +        open_table = (
        +            _cached_open_table_with_session
        +            if connection == "session"
        +            else _cached_open_table
        +        )
        +        factory = functools.partial(open_table, str(tmp_path))
        +        table = factory("t")
        +
        +    ds = StreamingDataset(
        +        table, block_size=4, shuffle=False, connection_factory=factory
        +    )
        +    table.delete("id = 0")
        +    table.add(pa.table({"id": [8]}))
        +
        +    assert table.count_rows() == 8
        +    assert [row["id"] for row in ds] == list(range(8))
        +
        +
        +# ---------------------------------------------------------------------------
        +# 2-phase shuffled reads (block_size)
        +# ---------------------------------------------------------------------------
        +# block_size switches StreamingDataset from 1-phase (per-row permutation) to
        +# 2-phase (block-granularity shuffle + a row-level shuffle bounded by
        +# max_shuffle_distance).  NUM_ROWS=120 with block_size=10 gives 12 blocks,
        +# which divides NUM_SPLITS=12 evenly, so most tests below reuse lance_table
        +# and those constants without the runt blocks and mid-block split boundaries
        +# covered explicitly by their own tests.
        +
        +
        +def test_two_phase_full_coverage_no_duplicates(lance_table):
        +    """Every sample ID appears exactly once across a full 2-phase epoch."""
        +    ds = StreamingDataset(
        +        lance_table,
        +        num_splits=NUM_SPLITS,
        +        shuffle_seed=SHUFFLE_SEED,
        +        block_size=10,
        +    )
        +    ids = [s["id"] for s in ds]
        +    assert len(ids) == NUM_ROWS
        +    assert sorted(ids) == list(range(NUM_ROWS)), "every row must appear exactly once"
        +
        +
        +def test_two_phase_reads_runt_block(lance_table):
        +    """A trailing partial block (block_size doesn't evenly divide the row
        +    count) is read like any other block."""
        +    ds = StreamingDataset(
        +        lance_table,
        +        num_splits=1,
        +        shuffle_seed=SHUFFLE_SEED,
        +        block_size=13,  # NUM_ROWS=120 -> 9 full blocks and a 3-row runt
        +        shuffle=False,
        +    )
        +    ids = [s["id"] for s in ds]
        +    assert ids == list(range(NUM_ROWS))
        +
        +
        +@pytest.mark.parametrize("reshuffle_blocks_per_epoch", [True, False])
        +@pytest.mark.parametrize(
        +    "block_size,num_splits,filter",
        +    [
        +        # 12 blocks over 5 splits: split boundaries fall mid-block.
        +        pytest.param(10, 5, None, id="whole_blocks_uneven_splits"),
        +        # 9 full blocks plus a 3-row runt over 7 splits: 120 // 7 = 17 rows
        +        # per split, so exactly 1 row is dropped.
        +        pytest.param(13, 7, None, id="runt_and_uneven_splits"),
        +        # 60 live rows in 9 blocks of 7 (the last a 4-row runt) over 4 splits.
        +        pytest.param(7, 4, "id % 2 = 0", id="filtered"),
        +    ],
        +)
        +def test_two_phase_drops_fewer_rows_than_splits(
        +    lance_table, block_size, num_splits, filter, reshuffle_blocks_per_epoch
        +):
        +    """Splits are cut by rows, not whole blocks, so each epoch drops fewer than
        +    num_splits rows (as 1-phase does) and every split serves the same count."""
        +    live_ids = set(range(NUM_ROWS)) if filter is None else set(range(0, NUM_ROWS, 2))
        +    rows_per_split = len(live_ids) // num_splits
        +    for epoch in range(2):
        +        ds = StreamingDataset(
        +            lance_table,
        +            num_splits=num_splits,
        +            shuffle_seed=SHUFFLE_SEED,
        +            epoch=epoch,
        +            block_size=block_size,
        +            filter=filter,
        +            reshuffle_blocks_per_epoch=reshuffle_blocks_per_epoch,
        +        )
        +        for split in range(num_splits):
        +            assert sum(b.stop - b.start for b in ds._split_blocks(split)) == (
        +                rows_per_split
        +            )
        +        ids = [s["id"] for s in ds]
        +        assert len(ids) == len(set(ids)) == rows_per_split * num_splits
        +        assert set(ids) <= live_ids
        +        assert len(live_ids) - len(ids) < num_splits
        +
        +
        +def test_two_phase_no_shuffle_preserves_order(lance_table):
        +    """shuffle=False yields rows in exact original storage order."""
        +    ds = StreamingDataset(
        +        lance_table,
        +        num_splits=1,
        +        shuffle_seed=SHUFFLE_SEED,
        +        block_size=10,
        +        shuffle=False,
        +    )
        +    ids = [s["id"] for s in ds]
        +    assert ids == list(range(NUM_ROWS)), (
        +        "shuffle=False must preserve original row order block-by-block"
        +    )
        +
        +
        +def test_two_phase_respects_max_shuffle_distance(lance_table):
        +    """No row moves farther than max_shuffle_distance from its natural
        +    (block, then row) position within its split's own block assignment.
        +
        +    White-box: reconstructs the expected natural-rank order directly from
        +    ds._block_perm (the shuffled block order), since that's the reference
        +    frame the displacement bound is defined against, not raw table order.
        +    """
        +    block_size = 10  # NUM_ROWS=120 -> 12 blocks
        +    max_shuffle_distance = 25
        +
        +    ds = StreamingDataset(
        +        lance_table,
        +        num_splits=1,
        +        shuffle_seed=SHUFFLE_SEED,
        +        block_size=block_size,
        +        max_shuffle_distance=max_shuffle_distance,
        +    )
        +    ids = [s["id"] for s in ds]
        +
        +    natural_order = [
        +        row_id
        +        for bp in ds._block_perm
        +        for row_id in range(bp * block_size, (bp + 1) * block_size)
        +    ]
        +    assert sorted(ids) == list(range(NUM_ROWS))
        +    assert sorted(natural_order) == list(range(NUM_ROWS))
        +
        +    natural_rank = {row_id: rank for rank, row_id in enumerate(natural_order)}
        +    for output_pos, row_id in enumerate(ids):
        +        displacement = abs(output_pos - natural_rank[row_id])
        +        assert displacement < max_shuffle_distance, (
        +            f"row {row_id} displaced {displacement} positions from its natural "
        +            f"rank, exceeding max_shuffle_distance={max_shuffle_distance}"
        +        )
        +
        +
        +@pytest.mark.parametrize(
        +    "kwargs,expected_window,expected_distance",
        +    [
        +        pytest.param({}, 8, 80, id="defaults"),
        +        pytest.param({"window_blocks": 2}, 2, 20, id="window_override"),
        +        pytest.param({"max_shuffle_distance": 15}, 8, 15, id="distance_override"),
        +    ],
        +)
        +def test_two_phase_window_defaults(
        +    lance_table, kwargs, expected_window, expected_distance
        +):
        +    ds = StreamingDataset(
        +        lance_table, num_splits=1, shuffle_seed=SHUFFLE_SEED, block_size=10, **kwargs
        +    )
        +    assert ds._window_blocks == expected_window
        +    assert ds._max_shuffle_distance == expected_distance
        +
        +
        +def test_two_phase_filter_counts_live_rows(tmp_path):
        +    """block_size counts only rows passing filter; dead rows never appear."""
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table(
        +        "t",
        +        pa.table(
        +            {
        +                "id": list(range(NUM_ROWS)),
        +                "category": ["train"] * 60 + ["val"] * 60,
        +            }
        +        ),
        +    )
        +    ds = StreamingDataset(
        +        table,
        +        num_splits=1,
        +        shuffle_seed=SHUFFLE_SEED,
        +        block_size=10,  # 60 live (train) rows -> 6 blocks exactly, no runt
        +        filter="category = 'train'",
        +    )
        +    ids = [s["id"] for s in ds]
        +    assert all(i < 60 for i in ids), "only live (train) rows should appear"
        +    assert sorted(ids) == list(range(60))
        +
        +
        +def test_two_phase_resume_checkpoint_round_trip(lance_table):
        +    """state_dict/load_state_dict resumes a 2-phase dataset without gaps or
        +    repeats, the same guarantee test_doc_example_checkpoint verifies for
        +    1-phase."""
        +    steps_before_checkpoint = 5
        +    block_size = 10  # NUM_ROWS=120 -> 12 blocks, divides NUM_SPLITS=12 evenly
        +
        +    ds = StreamingDataset(
        +        lance_table,
        +        num_splits=NUM_SPLITS,
        +        shuffle_seed=SHUFFLE_SEED,
        +        block_size=block_size,
        +    )
        +    it = iter(ds)
        +    consumed = [next(it)["id"] for _ in range(steps_before_checkpoint * NUM_SPLITS)]
        +    checkpoint = ds.state_dict()
        +    remaining_original = [s["id"] for s in it]
        +
        +    ds_resumed = StreamingDataset(
        +        lance_table,
        +        num_splits=NUM_SPLITS,
        +        shuffle_seed=SHUFFLE_SEED,
        +        block_size=block_size,
        +    )
        +    ds_resumed.load_state_dict(checkpoint)
        +    remaining_resumed = [s["id"] for s in ds_resumed]
        +
        +    assert remaining_original == remaining_resumed, (
        +        "Resumed 2-phase dataset must continue from exactly the same position"
        +    )
        +    assert sorted(consumed + remaining_original) == list(range(NUM_ROWS)), (
        +        "Consumed + remaining must cover every row exactly once"
        +    )
        +
        +
        +@pytest.mark.parametrize(
        +    "saved,resumed,mismatched_key",
        +    [
        +        pytest.param(
        +            {"block_size": 10}, {"block_size": 5}, "block_size", id="block_size"
        +        ),
        +        pytest.param(
        +            {"block_size": 10}, {}, "block_size", id="two_phase_into_one_phase"
        +        ),
        +        pytest.param(
        +            {}, {"block_size": 10}, "block_size", id="one_phase_into_two_phase"
        +        ),
        +        pytest.param(
        +            {"block_size": 10},
        +            {"block_size": 10, "max_shuffle_distance": 15},
        +            "max_shuffle_distance",
        +            id="max_shuffle_distance",
        +        ),
        +        pytest.param(
        +            {"block_size": 10},
        +            {"block_size": 10, "reshuffle_blocks_per_epoch": False},
        +            "reshuffle_blocks_per_epoch",
        +            id="reshuffle_blocks_per_epoch",
        +        ),
        +        pytest.param(
        +            {"block_size": 10},
        +            {"block_size": 10, "shuffle": False},
        +            "shuffle",
        +            id="shuffle",
        +        ),
        +    ],
        +)
        +def test_two_phase_checkpoint_rejects_different_read_order(
        +    lance_table, saved, resumed, mismatched_key
        +):
        +    """Saved positions index one 2-phase read order; resuming them under
        +    another would replay consumed rows and skip unread ones. The error names
        +    the setting to change."""
        +
        +    def make(options):
        +        return StreamingDataset(
        +            lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED, **options
        +        )
        +
        +    source = make(saved)
        +    it = iter(source)
        +    for _ in range(2 * NUM_SPLITS):
        +        next(it)
        +    checkpoint = source.state_dict()
        +
        +    with pytest.raises(ValueError, match=f"^{mismatched_key} mismatch: checkpoint"):
        +        make(resumed).load_state_dict(checkpoint)
        +    with pytest.raises(ValueError, match=f"^{mismatched_key} mismatch across"):
        +        StreamingDataset.merge_state_dicts([checkpoint, make(resumed).state_dict()])
        +
        +
        +def test_two_phase_failed_reader_build_closes_built_readers(lance_table, monkeypatch):
        +    """A resume position past a split's end fails while building readers; the
        +    readers built before it must still release their prefetch executors."""
        +    ds = StreamingDataset(
        +        lance_table, num_splits=2, shuffle_seed=SHUFFLE_SEED, block_size=10
        +    )
        +    checkpoint = ds.state_dict()
        +    checkpoint["positions_consumed_per_split"] = [0, NUM_ROWS]
        +    ds.load_state_dict(checkpoint)
        +
        +    closed = []
        +    close = streaming._TwoPhaseSplitReader.close
        +
        +    def counting_close(reader):
        +        closed.append(reader)
        +        close(reader)
        +
        +    monkeypatch.setattr(streaming._TwoPhaseSplitReader, "close", counting_close)
        +    with pytest.raises(ValueError, match="out of range"):
        +        list(ds)
        +    assert len(closed) == 1
        +
        +
        +def test_two_phase_pinned_version_survives_concurrent_write(tmp_path):
        +    """The block plan is pinned to the table version at construction; a
        +    write between construction and iteration must not change what an
        +    in-progress epoch reads."""
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("t", pa.table({"id": list(range(8))}))
        +
        +    ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
        +    table.delete("id = 0")  # mutate after construction, before iteration
        +
        +    ids = [s["id"] for s in ds]
        +    assert ids == list(range(8)), (
        +        "must read the version pinned at construction, not the live, since-mutated one"
        +    )
        +
        +
        +def test_two_phase_pinned_memory_table_survives_concurrent_write():
        +    """Same guarantee as the on-disk test above, but for a memory:// table.
        +
        +    A memory table's "pickle state" is its row data (to_arrow()), not just
        +    reopen coordinates, so it must be captured once at construction -- not
        +    recomputed from the live table on every _open_pinned_table() call --
        +    or a write made after construction would leak into every later read.
        +    """
        +    db = lancedb.connect("memory://")
        +    table = db.create_table("t", pa.table({"id": list(range(8))}))
        +
        +    ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
        +    table.delete("id = 0")
        +    table.add(pa.table({"id": [8]}))
        +
        +    ids = [s["id"] for s in ds]
        +    assert ids == list(range(8)), (
        +        "must read the snapshot captured at construction, not the live, "
        +        "since-mutated one"
        +    )
        +
        +
        +def test_two_phase_memory_table_already_at_a_later_version():
        +    """Constructing over a memory table already past version 1 must not
        +    fail: the pin is the snapshot's data, not a version number to replay
        +    against a freshly rebuilt (always version-1) in-memory table."""
        +    db = lancedb.connect("memory://")
        +    table = db.create_table("t", pa.table({"id": list(range(4))}))
        +    table.add(pa.table({"id": [4, 5, 6, 7]}))  # now at version 2, 8 live rows
        +
        +    ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
        +    ids = [s["id"] for s in ds]
        +    assert sorted(ids) == list(range(8))
        +
        +
        +def test_two_phase_reader_plan_arrays_are_int32(lance_table):
        +    """_plan_block_pos/_plan_local_offset are retained for the reader's
        +    whole lifetime, one entry per row in the entire split (the open
        +    whole-split-memory review thread) -- so their dtype is a real, constant
        +    memory-footprint decision, not an implementation detail. Pinned here at
        +    int32 (half of int64) so a future change can't silently regress it."""
        +    ds = StreamingDataset(
        +        lance_table, num_splits=1, shuffle_seed=SHUFFLE_SEED, block_size=10
        +    )
        +    reader = ds._make_two_phase_reader(0, ds._open_pinned_table(), None)
        +    assert reader._plan_block_pos.dtype == np.int32
        +    assert reader._plan_local_offset.dtype == np.int32
        +    # Values must still be correct, not just narrower -- e.g. a block index
        +    # silently wrapping around int32 would be a far worse regression than
        +    # the memory this dtype choice saves.
        +    assert reader._plan_block_pos.max() < len(ds._split_blocks(0))
        +    assert reader._plan_local_offset.max() < 10  # block_size
        +
        +
        +class _LookupCountingDict(dict):
        +    def __init__(self, *args):
        +        super().__init__(*args)
        +        self.lookups = 0
        +
        +    def __getitem__(self, key):
        +        self.lookups += 1
        +        return super().__getitem__(key)
        +
        +    def get(self, key, default=None):
        +        self.lookups += 1
        +        return super().get(key, default)
        +
        +
        +@pytest.mark.parametrize(
        +    "skip,swap_calls",
        +    [
        +        pytest.param(0, False, id="fresh"),
        +        pytest.param(1500, False, id="resumed"),
        +        # io_queue_depth lets calls take the reader's lock out of order.
        +        pytest.param(0, True, id="out_of_order"),
        +    ],
        +)
        +def test_two_phase_reader_sequential_read_is_linear_in_blocks(skip, swap_calls):
        +    """A sequential read must fetch each block once and keep per-call
        +    bookkeeping bounded by the resident window, not by how many blocks the
        +    split has already passed -- otherwise prefetch cost grows quadratically
        +    with split size."""
        +    num_blocks, block_size, batch = 400, 8, 8
        +    block_ids = list(range(1000, 1000 + num_blocks))
        +    reads = []
        +
        +    def read_block(block_id):
        +        reads.append(block_id)
        +        # Two record batches per block, as a multi-batch scan returns.
        +        half = block_size // 2
        +        return pa.concat_tables(
        +            pa.table({"block": [block_id] * half, "row": range(lo, lo + half)})
        +            for lo in (0, half)
        +        )
        +
        +    reader = streaming._TwoPhaseSplitReader(
        +        block_ids=block_ids,
        +        block_live_counts=[block_size] * num_blocks,
        +        shuffle=True,
        +        max_shuffle_distance=4 * block_size,
        +        seed=SHUFFLE_SEED,
        +        read_block_fn=read_block,
        +        columns=None,
        +        skip=skip,
        +        prefetch_depth=2,
        +    )
        +    try:
        +        # Later positions overwrite earlier ones, leaving each block's last.
        +        expected_last_pos = {
        +            bp: pos for pos, bp in enumerate(reader._plan_block_pos.tolist())
        +        }
        +        assert reader._block_last_pos == expected_last_pos
        +
        +        reader._block_last_pos = _LookupCountingDict(reader._block_last_pos)
        +        starts = list(range(0, reader.num_rows, batch))
        +        if swap_calls:
        +            starts[0::2], starts[1::2] = starts[1::2], starts[0::2]
        +        outputs = {}
        +        for start in starts:
        +            out = reader.__getitems__(range(start, min(start + batch, reader.num_rows)))
        +            outputs[start] = list(
        +                zip(out.column("block").to_pylist(), out.column("row").to_pylist())
        +            )
        +            assert all(
        +                t.column("block").num_chunks == 1 for t in reader._loaded.values()
        +            )
        +        rows = [row for start in sorted(outputs) for row in outputs[start]]
        +        num_calls = len(starts)
        +    finally:
        +        reader.close()
        +
        +    expected_rows = [
        +        (block_ids[bp], off)
        +        for bp, off in zip(
        +            reader._plan_block_pos.tolist(), reader._plan_local_offset.tolist()
        +        )
        +    ]
        +    assert rows == expected_rows
        +    if skip == 0:
        +        assert sorted(rows) == [
        +            (bid, off) for bid in block_ids for off in range(block_size)
        +        ]
        +    needed_blocks = {block_ids[bp] for bp in expected_last_pos}
        +    assert sorted(reads) == sorted(needed_blocks)
        +    # Rescanning every already-passed block on each prefetch top-up grows
        +    # quadratically (~29k lookups fresh here); a bounded walk stays linear
        +    # (~2k).
        +    assert reader._block_last_pos.lookups < 10 * (num_calls + num_blocks)
        +
        +
        +def test_two_phase_auto_blocks_per_epoch_reads_only_sampled_blocks(
        +    tmp_path, monkeypatch
        +):
        +    """blocks_per_epoch='auto' must sample whole blocks: a scattered row
        +    sample touches nearly every block and so reads the whole token column."""
        +    table = _create_token_table(tmp_path, [[1, 2, 3]] * 1000)
        +    reads = []
        +    read_block = StreamingDataset._read_block
        +
        +    def counting_read_block(self, pinned_table, block, columns):
        +        reads.append(block)
        +        return read_block(self, pinned_table, block, columns)
        +
        +    monkeypatch.setattr(StreamingDataset, "_read_block", counting_read_block)
        +    with pytest.warns(UserWarning, match="approximate token-count sample"):
        +        dataset = _packed_dataset(
        +            table, 4, blocks_per_epoch="auto", num_splits=2, block_size=10
        +        )
        +
        +    # 1% of each 500-row split rounds up to a single 10-row block per split.
        +    assert len(reads) == 2
        +    assert reads[0] in dataset._split_blocks(0)
        +    assert reads[1] in dataset._split_blocks(1)
        +    # Every document is 3 tokens plus EOS, so the sample is exact: 4000 / 4.
        +    assert dataset.state_dict()["blocks_per_epoch"] == 1000
        +
        +
        +def test_two_phase_rejects_rte_write_spec_table(tmp_path):
        +    """An RTE write spec means some acknowledged writes live only in the
        +    MemWAL, invisible to a version-pinned read; block_size must refuse the
        +    table at construction rather than silently reading stale base-table
        +    values (mirroring the row-id rejection 1-phase already applies)."""
        +    from lancedb import RTEWriteSpec
        +
        +    db = lancedb.connect(tmp_path)
        +    schema = pa.schema(
        +        [
        +            pa.field("id", pa.int64(), nullable=False),
        +            pa.field("value", pa.int64(), nullable=False),
        +        ]
        +    )
        +    table = db.create_table(
        +        "t",
        +        pa.Table.from_pydict({"id": list(range(8)), "value": [0] * 8}, schema=schema),
        +    )
        +    table.set_unenforced_primary_key("id")
        +    table.enable_rte(RTEWriteSpec.bucket("id", 1))
        +    table.merge_insert(
        +        "id"
        +    ).when_matched_update_all().when_not_matched_insert_all().execute(
        +        pa.Table.from_pydict({"id": list(range(8)), "value": [99] * 8}, schema=schema)
        +    )
        +
        +    with pytest.raises(ValueError, match="RTE write spec"):
        +        StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
        +
        +
        +def test_two_phase_rejects_fingerprinted_checkpoint(lance_table):
        +    """A checkpoint tied to a split_strategy permutation cannot resume block mode."""
        +    source = StreamingDataset(
        +        lance_table,
        +        split_strategy=lambda b: b.bootstrap_sample(
        +            2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED
        +        ),
        +        num_splits=NUM_SPLITS,
        +    )
        +    checkpoint = source.state_dict()
        +    assert "perm_fingerprint" in checkpoint
        +
        +    target = StreamingDataset(
        +        lance_table,
        +        num_splits=NUM_SPLITS,
        +        shuffle_seed=checkpoint["shuffle_seed"],
        +        block_size=10,
        +    )
        +    with pytest.raises(ValueError, match="no permutation table"):
        +        target.load_state_dict(checkpoint)
        +
        +
        +def test_two_phase_reshuffle_blocks_per_epoch_toggle(lance_table):
        +    """reshuffle_blocks_per_epoch=False keeps each split's blocks fixed
        +    across epochs; the default (True) reassigns them every epoch."""
        +    block_size = 10  # NUM_ROWS=120 -> 12 blocks
        +
        +    def block_perm_for(epoch, reshuffle):
        +        ds = StreamingDataset(
        +            lance_table,
        +            num_splits=1,
        +            shuffle_seed=SHUFFLE_SEED,
        +            block_size=block_size,
        +            epoch=epoch,
        +            reshuffle_blocks_per_epoch=reshuffle,
        +        )
        +        return list(ds._block_perm)
        +
        +    assert block_perm_for(0, False) == block_perm_for(1, False), (
        +        "blocks must stay pinned to the same split across epochs when disabled"
        +    )
        +    assert block_perm_for(0, True) != block_perm_for(1, True), (
        +        "blocks should be reassigned across epochs by default"
        +    )
        +
        +
        +def test_two_phase_too_few_blocks_for_num_splits_raises(tmp_path):
        +    """Fewer blocks than num_splits would leave some splits with no data."""
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("t", pa.table({"id": list(range(20))}))  # 2 blocks
        +    with pytest.raises(ValueError):
        +        StreamingDataset(table, num_splits=4, shuffle_seed=SHUFFLE_SEED, block_size=10)
        +
        +
        +@pytest.mark.parametrize(
        +    "extra_kwargs",
        +    [
        +        pytest.param(
        +            {"block_size": 10, "shuffle_clump_size": 5},
        +            id="shuffle_clump_size_with_block_size",
        +        ),
        +        pytest.param(
        +            {
        +                "block_size": 10,
        +                "split_strategy": lambda b: b.split_sequential(fixed=NUM_SPLITS),
        +            },
        +            id="split_strategy_with_block_size",
        +        ),
        +        pytest.param({"block_size": 1}, id="block_size_too_small"),
        +        pytest.param({"window_blocks": 2}, id="window_blocks_without_block_size"),
        +        pytest.param(
        +            {"max_shuffle_distance": 5}, id="max_shuffle_distance_without_block_size"
        +        ),
        +        pytest.param(
        +            {"reshuffle_blocks_per_epoch": True},
        +            id="reshuffle_blocks_per_epoch_without_block_size",
        +        ),
        +    ],
        +)
        +def test_two_phase_constructor_validation_raises(lance_table, extra_kwargs):
        +    """Invalid 2-phase parameter combinations raise ValueError at construction."""
        +    with pytest.raises(ValueError):
        +        StreamingDataset(
        +            lance_table,
        +            num_splits=NUM_SPLITS,
        +            shuffle_seed=SHUFFLE_SEED,
        +            **extra_kwargs,
        +        )
        +
        +
         # ---------------------------------------------------------------------------
         # split_strategy escape hatch
         # ---------------------------------------------------------------------------
        diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py
        index 78cd76ad2..488fd3cd9 100644
        --- a/python/python/tests/test_embeddings.py
        +++ b/python/python/tests/test_embeddings.py
        @@ -1107,6 +1107,47 @@ def test_openai_bad_request_partial_batch_recovery():
             assert embeddings[1] is None
         
         
        +@pytest.fixture
        +def mock_openai_client(monkeypatch):
        +    client = MagicMock()
        +    client.embeddings.create.return_value.data = []
        +    monkeypatch.setattr(
        +        "lancedb.embeddings.openai.attempt_import_or_raise", MagicMock()
        +    )
        +    monkeypatch.setattr(get_registry().get("openai"), "_openai_client", client)
        +    return client
        +
        +
        +@pytest.mark.parametrize(
        +    ("texts", "expected"),
        +    [([], []), ([None, ""], [None, None])],
        +    ids=["empty-batch", "all-inputs-filtered"],
        +)
        +def test_openai_skips_batches_without_valid_text(mock_openai_client, texts, expected):
        +    model = get_registry().get("openai").create()
        +
        +    assert model.compute_source_embeddings(texts) == expected
        +    mock_openai_client.embeddings.create.assert_not_called()
        +
        +
        +def test_openai_add_all_invalid_texts_as_null_vectors(mock_openai_client, tmp_path):
        +    model = get_registry().get("openai").create(name="text-embedding-3-small", dim=2)
        +
        +    class TextModel(LanceModel):
        +        text: Optional[str] = model.SourceField()
        +        vector: Optional[Vector(model.ndims())] = model.VectorField()
        +
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("words", schema=TextModel)
        +    table.add([{"text": None}, {"text": ""}], on_bad_vectors="null")
        +
        +    assert table.to_arrow().to_pylist() == [
        +        {"text": None, "vector": None},
        +        {"text": "", "vector": None},
        +    ]
        +    mock_openai_client.embeddings.create.assert_not_called()
        +
        +
         def test_ollama_embeddings_pickle():
             """OllamaEmbeddings must pickle even after the cached client is created."""
             registry = get_registry()
        diff --git a/python/python/tests/test_embeddings_bedrock.py b/python/python/tests/test_embeddings_bedrock.py
        new file mode 100644
        index 000000000..9340c3f58
        --- /dev/null
        +++ b/python/python/tests/test_embeddings_bedrock.py
        @@ -0,0 +1,330 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import base64
        +import io
        +import json
        +
        +import boto3
        +from botocore.response import StreamingBody
        +from botocore.stub import ANY, Stubber
        +from PIL import Image, UnidentifiedImageError
        +from pydantic import ValidationError
        +import pytest
        +
        +import lancedb
        +from lancedb.embeddings import get_registry
        +from lancedb.pydantic import LanceModel, Vector
        +
        +
        +TITAN_IMAGE = "amazon.titan-embed-image-v1"
        +COHERE_IMAGE = "cohere.embed-v4:0"
        +
        +
        +@pytest.fixture
        +def bedrock_runtime(monkeypatch):
        +    runtime = boto3.Session(
        +        aws_access_key_id="stub-access-key",
        +        aws_secret_access_key="stub-secret-key",
        +        region_name="us-east-1",
        +    ).client("bedrock-runtime")
        +    monkeypatch.setattr(boto3.Session, "client", lambda *args, **kwargs: runtime)
        +    return runtime
        +
        +
        +def stub_embedding(stub, model_id, response):
        +    data = json.dumps(response).encode("utf-8")
        +    stub.add_response(
        +        "invoke_model",
        +        {
        +            "body": StreamingBody(io.BytesIO(data), len(data)),
        +            "contentType": "application/json",
        +        },
        +        {
        +            "modelId": model_id,
        +            "body": ANY,
        +            "contentType": "application/json",
        +            "accept": "application/json",
        +        },
        +    )
        +
        +
        +def encode_image(image, image_format):
        +    with io.BytesIO() as buffer:
        +        image.save(buffer, format=image_format)
        +        return buffer.getvalue()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "model_id, dimensions", [(TITAN_IMAGE, 1024), (COHERE_IMAGE, 1536)]
        +)
        +@pytest.mark.parametrize("source_type", [bytes, str], ids=["bytes", "paths"])
        +async def test_bedrock_image_search(
        +    tmp_path, bedrock_runtime, mocker, model_id, dimensions, source_type
        +):
        +    db_path = tmp_path / "database"
        +    db = lancedb.connect(db_path)
        +    kwargs = {"name": model_id} if model_id != TITAN_IMAGE else {}
        +    model = (
        +        get_registry()
        +        .get("bedrock-image")
        +        .create(region="eu-west-1", max_retries=0, **kwargs)
        +    )
        +    assert model.ndims() == dimensions
        +
        +    class Photo(LanceModel):
        +        label: str
        +        image: source_type = model.SourceField()
        +        vector: Vector(dimensions) = model.VectorField()
        +
        +    red_image = Image.new("RGB", (64, 64), "red")
        +    red_png = encode_image(red_image, "PNG")
        +    blue_image = Image.new("RGB", (64, 64), "blue")
        +    blue_jpeg = encode_image(blue_image, "JPEG")
        +    images = {"red": red_png, "blue": blue_jpeg}
        +    cohere_only_images = {}
        +    if model_id == COHERE_IMAGE:
        +        cohere_only_images = {
        +            "webp": encode_image(blue_image, "WEBP"),
        +            "gif": encode_image(blue_image, "GIF"),
        +        }
        +        images.update(cohere_only_images)
        +    sources = images.copy()
        +    if source_type is str:
        +        # The contents, not the file suffix, determine the request MIME type.
        +        for label, encoded_image in images.items():
        +            path = tmp_path / f"{label}.image"
        +            path.write_bytes(encoded_image)
        +            sources[label] = str(path)
        +
        +    red = [1.0, 0.0] + [0.0] * (dimensions - 2)
        +    blue = [0.0, 1.0] + [0.0] * (dimensions - 2)
        +    other = [0.0, 0.0, 1.0] + [0.0] * (dimensions - 3)
        +    invoke = mocker.spy(bedrock_runtime, "invoke_model")
        +    session = mocker.spy(boto3, "Session")
        +    with Stubber(bedrock_runtime) as stub:
        +        for vector in (red, blue, *([other] * len(cohere_only_images)), blue, red, red):
        +            if model_id == TITAN_IMAGE:
        +                stub_embedding(stub, model_id, {"embedding": vector})
        +            else:
        +                stub_embedding(stub, model_id, {"embeddings": {"float": [vector]}})
        +
        +        table = db.create_table("photos", schema=Photo)
        +        table.add(
        +            [{"label": label, "image": image} for label, image in sources.items()]
        +        )
        +        table = db.open_table("photos")
        +        restored = table.embedding_functions["vector"].function
        +        assert (restored.name, restored.region, restored.max_retries) == (
        +            model_id,
        +            "eu-west-1",
        +            0,
        +        )
        +        assert table.schema.field("vector").type.list_size == dimensions
        +        assert table.search("blue").limit(1).to_list()[0]["label"] == "blue"
        +        assert table.search(red_image).limit(1).to_list()[0]["label"] == "red"
        +
        +        async_db = await lancedb.connect_async(db_path)
        +        async_table = await async_db.open_table("photos")
        +        query = await async_table.search(red_image, query_type="vector")
        +        assert (await query.limit(1).to_list())[0]["label"] == "red"
        +        stub.assert_no_pending_responses()
        +
        +    assert session.call_args_list
        +    assert all(not call.args and not call.kwargs for call in session.call_args_list)
        +    red_base64 = base64.b64encode(red_png).decode("ascii")
        +    blue_base64 = base64.b64encode(blue_jpeg).decode("ascii")
        +    if model_id == TITAN_IMAGE:
        +        red_query = {"inputImage": red_base64}
        +        expected = [
        +            {"inputImage": red_base64},
        +            {"inputImage": blue_base64},
        +            {"inputText": "blue"},
        +            red_query,
        +            red_query,
        +        ]
        +    else:
        +        red_uri = f"data:image/png;base64,{red_base64}"
        +        blue_uri = f"data:image/jpeg;base64,{blue_base64}"
        +        red_query = {"images": [red_uri], "input_type": "search_query"}
        +        additional_documents = [
        +            {
        +                "images": [
        +                    f"data:image/{image_format};base64,"
        +                    f"{base64.b64encode(image).decode('ascii')}"
        +                ],
        +                "input_type": "search_document",
        +            }
        +            for image_format, image in cohere_only_images.items()
        +        ]
        +        expected = [
        +            {"images": [red_uri], "input_type": "search_document"},
        +            {"images": [blue_uri], "input_type": "search_document"},
        +            *additional_documents,
        +            {"texts": ["blue"], "input_type": "search_query"},
        +            red_query,
        +            red_query,
        +        ]
        +        expected = [{**payload, "embedding_types": ["float"]} for payload in expected]
        +    assert [
        +        json.loads(call.kwargs["body"]) for call in invoke.call_args_list
        +    ] == expected
        +
        +
        +def test_bedrock_image_retry_does_not_replay_successful_rows(
        +    tmp_path, bedrock_runtime, mocker
        +):
        +    sleep = mocker.patch("lancedb.embeddings.utils.time.sleep")
        +    model = get_registry().get("bedrock-image").create(max_retries=1)
        +
        +    class Photo(LanceModel):
        +        image: bytes | None = model.SourceField()
        +        vector: Vector(model.ndims()) | None = model.VectorField()
        +
        +    table = lancedb.connect(tmp_path).create_table("photos", schema=Photo)
        +    red_png = encode_image(Image.new("RGB", (64, 64), "red"), "PNG")
        +    blue_png = encode_image(Image.new("RGB", (64, 64), "blue"), "PNG")
        +    red = [1.0] + [0.0] * 1023
        +    blue = [0.0, 1.0] + [0.0] * 1022
        +    invoke = mocker.spy(bedrock_runtime, "invoke_model")
        +    with Stubber(bedrock_runtime) as stub:
        +        stub_embedding(stub, TITAN_IMAGE, {"embedding": red})
        +        stub.add_client_error(
        +            "invoke_model",
        +            service_error_code="ThrottlingException",
        +            http_status_code=429,
        +        )
        +        stub_embedding(stub, TITAN_IMAGE, {"embedding": blue})
        +        table.add(
        +            [{"image": red_png}, {"image": None}, {"image": blue_png}],
        +            on_bad_vectors="null",
        +        )
        +        stub.assert_no_pending_responses()
        +
        +    sleep.assert_called_once()
        +    assert [
        +        base64.b64decode(json.loads(call.kwargs["body"])["inputImage"])
        +        for call in invoke.call_args_list
        +    ] == [red_png, blue_png, blue_png]
        +    assert table.to_arrow()["vector"].to_pylist() == [red, None, blue]
        +
        +
        +def test_bedrock_image_local_error_does_not_retry(tmp_path, mocker):
        +    sleep = mocker.patch("lancedb.embeddings.utils.time.sleep")
        +    session = mocker.patch.object(boto3, "Session")
        +    model = get_registry().get("bedrock-image").create(max_retries=1)
        +
        +    class Photo(LanceModel):
        +        image: bytes = model.SourceField()
        +        vector: Vector(model.ndims()) = model.VectorField()
        +
        +    table = lancedb.connect(tmp_path).create_table("photos", schema=Photo)
        +    with pytest.raises(RuntimeError, match="UnidentifiedImageError"):
        +        table.add([{"image": b"invalid image bytes"}])
        +    assert table.count_rows() == 0
        +
        +    with pytest.raises(UnidentifiedImageError):
        +        model.compute_source_embeddings_with_retry(b"invalid image bytes")
        +    gif = encode_image(Image.new("RGB", (64, 64)), "GIF")
        +    with pytest.raises(ValueError, match="accepts PNG and JPEG images"):
        +        model.compute_source_embeddings_with_retry(gif)
        +    with pytest.raises(TypeError, match="text or a Pillow image"):
        +        model.compute_query_embeddings_with_retry(b"invalid query")
        +    sleep.assert_not_called()
        +    session.assert_not_called()
        +
        +
        +@pytest.mark.parametrize(
        +    "field, value",
        +    [
        +        ("profile_name", "other-profile"),
        +        ("assumed_role", "arn:aws:iam::123456789012:role/OtherRole"),
        +        ("role_session_name", "other-session"),
        +    ],
        +)
        +def test_bedrock_image_rejects_credential_settings(tmp_path, mocker, field, value):
        +    registry = get_registry()
        +    image_provider = registry.get("bedrock-image")
        +    session = mocker.patch.object(boto3, "Session")
        +    with pytest.raises(ValidationError, match=field):
        +        image_provider.create(**{field: value})
        +
        +    model = image_provider.create()
        +
        +    class Photo(LanceModel):
        +        image: bytes = model.SourceField()
        +        vector: Vector(model.ndims()) = model.VectorField()
        +
        +    schema = Photo.to_arrow_schema()
        +    metadata = schema.metadata
        +    key = b"embedding_functions"
        +    entries = json.loads(metadata[key])
        +    entries[0]["model"][field] = value
        +    metadata[key] = json.dumps(entries).encode()
        +    schema = schema.with_metadata(metadata)
        +    lancedb.connect(tmp_path).create_table("photos", schema=schema)
        +    reopened = lancedb.connect(tmp_path).open_table("photos")
        +    with pytest.raises(ValidationError, match=field):
        +        reopened.search("sunset", query_type="vector").limit(1).to_list()
        +    session.assert_not_called()
        +
        +
        +def test_bedrock_text_restores_credential_settings(tmp_path, mocker):
        +    registry = get_registry()
        +    model = registry.get("bedrock-text").create(
        +        profile_name="text-profile",
        +        assumed_role="arn:aws:iam::123456789012:role/TextRole",
        +        role_session_name="text-session",
        +    )
        +
        +    class TextRow(LanceModel):
        +        text: str = model.SourceField()
        +        vector: Vector(model.ndims()) = model.VectorField()
        +
        +    db = lancedb.connect(tmp_path)
        +    db.create_table("texts", schema=TextRow)
        +    restored = registry.parse_functions(db.open_table("texts").schema.metadata)[
        +        "vector"
        +    ].function
        +    session = mocker.patch.object(boto3, "Session")
        +    client = session.return_value.client
        +    sts = mocker.Mock()
        +    runtime = mocker.Mock()
        +    client.side_effect = [sts, runtime]
        +    sts.assume_role.return_value = {
        +        "Credentials": {
        +            "AccessKeyId": "stub-key",
        +            "SecretAccessKey": "stub-secret",
        +            "SessionToken": "stub-token",
        +        }
        +    }
        +
        +    assert restored.client is runtime
        +    session.assert_called_once_with(
        +        region_name=model.region, profile_name="text-profile"
        +    )
        +    sts.assume_role.assert_called_once_with(
        +        RoleArn="arn:aws:iam::123456789012:role/TextRole",
        +        RoleSessionName="text-session",
        +    )
        +    assert client.call_args.kwargs["aws_session_token"] == "stub-token"
        +
        +
        +def test_bedrock_text_cohere_v3(bedrock_runtime, mocker):
        +    model_id = "cohere.embed-multilingual-v3"
        +    model = get_registry().get("bedrock-text").create(name=model_id, max_retries=0)
        +    vector = [1.0] * 1024
        +    invoke = mocker.spy(bedrock_runtime, "invoke_model")
        +    with Stubber(bedrock_runtime) as stub:
        +        stub_embedding(stub, model_id, {"embeddings": [vector]})
        +        stub_embedding(stub, model_id, {"embeddings": [vector]})
        +        assert model.ndims() == 1024
        +        assert model.compute_source_embeddings(["document"]) == [vector]
        +        assert model.compute_query_embeddings("query") == [vector]
        +        stub.assert_no_pending_responses()
        +
        +    assert [json.loads(call.kwargs["body"]) for call in invoke.call_args_list] == [
        +        {"texts": ["document"], "input_type": "search_document"},
        +        {"texts": ["query"], "input_type": "search_query"},
        +    ]
        diff --git a/python/python/tests/test_embeddings_trust.py b/python/python/tests/test_embeddings_trust.py
        index 5eaed15a6..fe582677a 100644
        --- a/python/python/tests/test_embeddings_trust.py
        +++ b/python/python/tests/test_embeddings_trust.py
        @@ -233,15 +233,27 @@ OCI_REGION_ENDPOINT = (
                 ("ollama", {"host": ATTACKER_URL}),
                 ("ollama", {"ollama_client_kwargs": {"proxy": ATTACKER_URL}}),
                 ("watsonx", {"url": ATTACKER_URL}),
        +        (
        +            "cohere",
        +            {
        +                "name": "embed-v-4-0",
        +                "base_url": ATTACKER_URL,
        +                "output_dimension": 256,
        +                "api_key": "$var:cohere-test-key",
        +            },
        +        ),
             ],
         )
        -def test_restored_custom_endpoint_requires_allowlist(name, model):
        +def test_restored_custom_endpoint_requires_allowlist(name, model, monkeypatch):
        +    registry = get_registry()
        +    monkeypatch.setitem(registry._variables, "cohere-test-key", "test-cohere-key")
        +
             func = restore(name, model)
             with pytest.raises(UntrustedEmbeddingConfigError, match="attacker.example"):
                 func.compute_query_embeddings("hello")
         
        -    get_registry().allow_endpoint(ATTACKER_URL)
        -    assert isinstance(restore(name, model), get_registry().get(name))
        +    registry.allow_endpoint(ATTACKER_URL)
        +    assert isinstance(restore(name, model), registry.get(name))
         
         
         def test_default_endpoints_need_no_allowlist():
        diff --git a/python/python/tests/test_errors.py b/python/python/tests/test_errors.py
        index 8721a2bb7..12a193074 100644
        --- a/python/python/tests/test_errors.py
        +++ b/python/python/tests/test_errors.py
        @@ -10,10 +10,12 @@ from lance_namespace.errors import TableNotFoundError as NamespaceTableNotFoundE
         from lancedb.db import DBConnection
         from lancedb.remote.errors import (
             AlreadyExistsError,
        +    ConflictError,
             FunctionNotFoundError,
             HttpError,
             LanceDBClientError,
             NamespaceNotFoundError,
        +    ResponseInterruptedError,
             RetryError,
             SecretNotFoundError,
             TableNotFoundError,
        @@ -72,6 +74,31 @@ def test_pickle_http_transport_error():
             assert restored.request_id == "req-789"
         
         
        +def test_pickle_response_interrupted_error():
        +    err = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7, True)
        +    restored = pickle.loads(pickle.dumps(err))
        +    assert type(restored) is ResponseInterruptedError
        +    assert str(restored) == "interrupted"
        +    assert restored.request_id == "req-1"
        +    assert (restored.batches, restored.rows, restored.table_version) == (2, 2048, 7)
        +    assert restored.is_transport_error is True
        +    assert restored.status_code is None
        +
        +
        +@pytest.mark.parametrize("error_code", [None, "conflict", "future_conflict_code"])
        +def test_http_conflict_error_preserves_reason_and_metadata(error_code):
        +    reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files"
        +    original = HttpError(reason, "req-conflict", 409, error_code)
        +    for error in [original, pickle.loads(pickle.dumps(original))]:
        +        assert type(error) is ConflictError
        +        assert isinstance(error, HttpError)
        +        assert str(error) == reason
        +        assert error.request_id == "req-conflict"
        +        assert error.status_code == 409
        +        assert error.error_code == error_code
        +        assert error.is_transport_error is False
        +
        +
         @pytest.mark.parametrize(
             "error_code,resource_kind,status_code,expected_type",
             [
        @@ -251,6 +278,9 @@ def test_sql_errors_use_only_server_codes(code, category, type_name):
                 (400, "schema_mismatch", "SchemaMismatchError"),
                 (404, "table_not_found", "TableNotFoundError"),
                 (404, "reference_not_found", "ReferenceNotFoundError"),
        +        (409, None, "ConflictError"),
        +        (409, "conflict", "ConflictError"),
        +        (500, "conflict", "HttpError"),
                 (500, "column_not_found", "HttpError"),
                 (503, "table_not_found", "HttpError"),
             ],
        diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py
        index cc4485133..d5b86977a 100644
        --- a/python/python/tests/test_first_class_function_slice1.py
        +++ b/python/python/tests/test_first_class_function_slice1.py
        @@ -2,17 +2,19 @@
         # SPDX-FileCopyrightText: Copyright The LanceDB Authors
         
         import json
        +import warnings
         from collections import UserDict
         from pathlib import Path
         from types import MappingProxyType
         
         import pytest
         
        -from lancedb import col
        +from lancedb import col, lit
         import lancedb.functions as functions
         from lancedb.functions import (
             FunctionApplication,
             FunctionBinding,
        +    FunctionImage,
             FunctionVersion,
             PythonRuntimeSpec,
             SecretBinding,
        @@ -20,6 +22,7 @@ from lancedb.functions import (
             SecretReference,
         )
         from lancedb.table import AsyncTable
        +from lancedb.resources import _resource_options
         
         
         FIXTURES = (
        @@ -34,7 +37,7 @@ FIXTURES = (
         
         
         def fixture(name: str) -> str:
        -    return (FIXTURES / name).read_text()
        +    return (FIXTURES / name).read_text(encoding="utf-8")
         
         
         def job_result(name: str) -> dict:
        @@ -58,6 +61,7 @@ def assert_no_secret_values(value):
         
         
         def test_public_function_values_are_in_api_reference():
        +    assert "LiteralInputBinding" in functions.__all__
             docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md"
             rendered = docs.read_text()
             for name in functions.__all__:
        @@ -148,6 +152,91 @@ def test_function_version_identity_is_immutable_and_exact():
                     FunctionVersion(**{**value, "version": invalid})
         
         
        +@pytest.mark.parametrize("gpu", [False, True])
        +def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu):
        +    value = job_result("remote_function_job.json")["image"]
        +    value["descriptor"]["future_metadata"] = "x" * 100_000
        +    if gpu:
        +        value["descriptor"]["requires"]["capabilities"] = [
        +            {
        +                "type": "lance.cuda",
        +                "version": 1,
        +                "device_count": 1,
        +                "cuda_toolkit": "12.4",
        +            }
        +        ]
        +    image = FunctionImage(**value)
        +    with warnings.catch_warnings():
        +        warnings.simplefilter("error", DeprecationWarning)
        +        details = image.describe()
        +        rendered = repr(image)
        +        assert "manifest_digest=" in str(image)
        +        encoded = json.loads(image.to_canonical_json())
        +    assert details == {
        +        "manifest_digest": value["manifest_digest"],
        +        "python_version": "3.12.14",
        +        "requires_gpu": gpu,
        +        "cuda_toolkit": "12.4" if gpu else None,
        +        "platforms": None,
        +        "base_image": None,
        +        "size_bytes": None,
        +    }
        +    assert len(rendered) < 350
        +    assert f"requires_gpu={gpu}" in rendered
        +    assert "future_metadata" not in rendered
        +    assert encoded == value
        +
        +
        +@pytest.mark.parametrize(
        +    "descriptor",
        +    [
        +        {},
        +        {"format_version": 2, "requires": {"capabilities": []}},
        +        {"format_version": 1, "requires": {"capabilities": [None]}},
        +        {"python": {"version": {"future": "x" * 100_000}}},
        +    ],
        +)
        +def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor):
        +    image = FunctionImage(
        +        manifest_digest="sha256:example", descriptor=descriptor, source=True
        +    )
        +    assert image.describe()["requires_gpu"] is None
        +    assert image.describe()["python_version"] is None
        +    assert len(repr(image)) < 350
        +
        +
        +@pytest.mark.parametrize(
        +    "case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"]
        +)
        +def test_runtime_digests_match_server_golden_values(case):
        +    runtime = PythonRuntimeSpec.from_json(json.dumps(case["runtime"]))
        +    assert runtime.digest == case["digest"]
        +    assert (
        +        PythonRuntimeSpec.from_json(runtime.to_canonical_json()).digest
        +        == runtime.digest
        +    )
        +
        +
        +def test_unknown_runtime_digest_fails_closed():
        +    runtime = PythonRuntimeSpec.from_json('{"kind":"python_v3","future":"value"}')
        +    with pytest.raises(ValueError, match="cannot digest unknown runtime kind"):
        +        runtime.digest
        +
        +
        +@pytest.mark.parametrize("runtime_digest", [None, "sha256:runtime-inputs"])
        +def test_function_version_preserves_runtime_digest(runtime_digest):
        +    value = job_result("remote_function_job.json")
        +    legacy = FunctionVersion.from_json(json.dumps(value))
        +    assert legacy.runtime_digest is None
        +    assert "runtime_digest" not in json.loads(legacy.to_canonical_json())
        +    value["runtime_digest"] = runtime_digest
        +    version = FunctionVersion.from_json(json.dumps(value))
        +    assert version.runtime_digest == runtime_digest
        +    assert FunctionVersion.from_json(version.to_canonical_json()) == version
        +    with pytest.raises((TypeError, ValueError)):
        +        version.runtime_digest = "sha256:changed"
        +
        +
         @pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"])
         def test_function_version_preserves_source_digest(source_digest):
             value = job_result("remote_function_job.json")
        @@ -180,6 +269,28 @@ def test_function_version_exposes_registered_gpu_class():
             assert json.loads(version.to_canonical_json())["gpu_class"] == "a10g"
         
         
        +def test_function_version_preserves_execution_controls():
        +    value = job_result("remote_function_job.json")
        +    value.update(
        +        batch_size=12,
        +        max_concurrency=4,
        +        row_timeout_seconds=8.0,
        +        result_stability="input_and_context",
        +    )
        +    version = FunctionVersion.from_json(json.dumps(value))
        +    encoded = json.loads(version.to_canonical_json())
        +
        +    assert encoded == value
        +    assert type(encoded["batch_size"]) is int
        +    assert type(encoded["max_concurrency"]) is int
        +    assert type(encoded["row_timeout_seconds"]) is float
        +    assert type(encoded["result_stability"]) is str
        +
        +    for invalid in [True, 1.5, 0, -1, 2**32]:
        +        with pytest.raises(ValueError, match="max_concurrency"):
        +            FunctionVersion(**{**value, "max_concurrency": invalid})
        +
        +
         def test_function_version_binds_named_columns_as_one_immutable_application():
             version = FunctionVersion.from_json(
                 json.dumps(job_result("remote_function_job.json"))
        @@ -232,6 +343,67 @@ def test_function_version_binding_validates_names_and_direct_columns():
                 version(text=col("text").lower())
         
         
        +@pytest.mark.parametrize("constant", [16, 8, True, "prompt", None, 2**64 - 1])
        +def test_function_version_binds_direct_literals_without_changing_identity(constant):
        +    value = job_result("remote_function_job.json")
        +    value["signature"]["inputs"].append(
        +        {
        +            "name": "option",
        +            "arrow_type": "bool"
        +            if type(constant) is bool
        +            else "utf8"
        +            if isinstance(constant, str)
        +            else "uint64"
        +            if constant == 2**64 - 1
        +            else "int64",
        +            "nullable": True,
        +        }
        +    )
        +    version = FunctionVersion.from_json(json.dumps(value))
        +    expression = lit(constant)
        +    application = version(text=col("body"), option=expression)
        +    encoded = json.loads(application.to_canonical_json())
        +    assert encoded["inputs"] == [
        +        {"parameter": "text", "kind": "column", "value": {"path": "body"}},
        +        {"parameter": "option", "kind": "literal", "value": constant},
        +    ]
        +    assert application.function.version == version.version
        +    assert application.function.object_id == version.object_id
        +    assert application.function.manifest_digest == version.image.manifest_digest
        +    assert FunctionApplication.from_json(application.to_canonical_json()) == application
        +    if constant is None:
        +        assert expression.to_sql() == "NULL"
        +    if type(constant) is int:
        +        assert expression.to_sql() == str(constant)
        +
        +
        +def test_function_literals_reject_expressions_and_unsupported_values():
        +    version = FunctionVersion.from_json(
        +        json.dumps(job_result("remote_function_job.json"))
        +    )
        +    with pytest.raises(TypeError, match="direct col"):
        +        version(text=lit(16) + lit(8))
        +    with pytest.raises(ValueError, match="floating-point Function literals"):
        +        version(text=lit(1.5))
        +    with pytest.raises(TypeError, match="unsupported Function literal type"):
        +        version(text=lit(b"data"))
        +
        +
        +def test_function_literal_binding_preserves_null_and_rejects_duplicate_parameters():
        +    value = json.loads((FIXTURES / "remote_function_binding.json").read_text())
        +    value["inputs"] = value["inputs"][:1]
        +    value["literal_inputs"] = [{"parameter": "body", "value": None}]
        +    binding = FunctionBinding.from_json(json.dumps(value))
        +    assert binding.literal_inputs[0].value is None
        +    assert json.loads(binding.to_canonical_json())["literal_inputs"] == [
        +        {"parameter": "body", "value": None}
        +    ]
        +    assert FunctionBinding.from_json(binding.to_canonical_json()) == binding
        +    value["literal_inputs"][0]["parameter"] = "title"
        +    with pytest.raises(ValueError, match="input parameters must be unique"):
        +        FunctionBinding.from_json(json.dumps(value))
        +
        +
         def test_function_version_keeps_named_struct_outputs_in_one_application():
             value = job_result("remote_function_job.json")
             value["name"] = "text_features"
        @@ -285,10 +457,15 @@ def test_unknown_fields_and_discriminators_are_forward_decodable():
         
             version = FunctionVersion.from_json(json.dumps(value))
             assert version.image.descriptor["future_interface"] == {"kind": "wasm"}
        -    assert json.loads(version.to_canonical_json())["image"]["descriptor"][
        -        "future_interface"
        -    ] == {"kind": "wasm"}
             assert version.signature.output.kind == "future_output_shape"
        +    assert not hasattr(version, "future_version_metadata")
        +
        +    canonical = json.loads(version.to_canonical_json())
        +    expected = json.loads(fixture("remote_function_version.canonical.json"))
        +    expected["image"]["descriptor"]["future_interface"] = {"kind": "wasm"}
        +    expected["signature"]["output"]["kind"] = "future_output_shape"
        +    assert canonical == expected
        +    assert "future_version_metadata" not in canonical
         
         
         def test_function_application_uses_rename_columns_only():
        @@ -434,17 +611,23 @@ class _FunctionDeclarationInner:
         
             async def add_function_columns(
                 self,
        -        application_json,
        -        output_name,
        +        bindings,
                 auto_refresh_enabled,
                 auto_refresh_interval_seconds,
        +        total_cpu_millis,
        +        total_memory_bytes,
        +        total_gpu_count,
        +        gpu_class=None,
        +        gpu_count=None,
             ):
                 self.calls.append(
                     (
        -                json.loads(application_json),
        -                output_name,
        +                [(json.loads(app), name) for app, name in bindings],
                         auto_refresh_enabled,
                         auto_refresh_interval_seconds,
        +                total_cpu_millis,
        +                total_memory_bytes,
        +                total_gpu_count,
                     )
                 )
                 return "declared"
        @@ -469,29 +652,45 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
                 mapping_type({"features": application._copy(update={"columns": {}})})
             )
             assert result == "declared"
        -    assert inner.calls[-1][1] == "features"
        -    assert inner.calls[-1][2:] == (None, None)
        +    [(_, name)], *options = inner.calls[-1]
        +    assert name == "features"
        +    assert options == [None, None, None, None, None]
         
             bare = application._copy(update={"columns": {}}).rename(
                 columns={"normalized_text": "search_text"}
             )
             result = await table.add_columns(
        -        bare, auto_refresh_enabled=False, auto_refresh_interval_seconds=300
        +        bare,
        +        auto_refresh_enabled=False,
        +        auto_refresh_interval_seconds=300,
        +        total_cpu_millis=8000,
        +        total_gpu_count=0,
             )
             assert result == "declared"
        -    assert inner.calls[-1][1] is None
        -    assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"}
        -    assert inner.calls[-1][2:] == (False, 300)
        +    [(payload, name)], *options = inner.calls[-1]
        +    assert name is None
        +    assert payload["columns"] == {"normalized_text": "search_text"}
        +    assert options == [False, 300, 8000, None, 0]
         
         
         @pytest.mark.asyncio
        -async def test_add_columns_rejects_multiple_bindings_and_unknown_newer_application():
        +async def test_add_columns_routes_multiple_bindings_in_one_call():
        +    inner = _FunctionDeclarationInner()
        +    table = AsyncTable(inner)
        +    application = known_application()._copy(update={"columns": {}})
        +    assert await table.add_columns({"a": application, "b": application}) == "declared"
        +    assert len(inner.calls) == 1
        +    assert [name for _, name in inner.calls[0][0]] == ["a", "b"]
        +
        +
        +@pytest.mark.asyncio
        +async def test_add_columns_rejects_mixed_bindings_and_unknown_newer_application():
             inner = _FunctionDeclarationInner()
             table = AsyncTable(inner)
             application = known_application()
         
        -    with pytest.raises(ValueError, match="exactly one Function binding"):
        -        await table.add_columns({"a": application, "b": application})
        +    with pytest.raises(ValueError, match="cannot mix Function applications"):
        +        await table.add_columns({"a": application, "b": "1+1"})
         
             future = json.loads(fixture("remote_function_application.json"))
             application = FunctionApplication(**future)
        @@ -537,3 +736,20 @@ def test_rename_requires_named_struct_and_keeps_partial_mapping_immutable():
             renamed = application.rename(columns={"normalized_text": "search_text"})
             assert dict(application.columns) == {}
             assert dict(renamed.columns) == {"normalized_text": "search_text"}
        +
        +
        +@pytest.mark.parametrize("gpu_count", [0, -1, True, 1.5, 2**32])
        +def test_gpu_worker_count_rejects_invalid_values(gpu_count):
        +    with pytest.raises(ValueError, match="gpu_count"):
        +        _resource_options(None, None, None, gpu_count=gpu_count)
        +
        +
        +def test_gpu_worker_settings_are_separate_from_execution_totals():
        +    assert _resource_options(8000, None, 8, gpu_class="any", gpu_count=2) == {
        +        "total_cpu_millis": 8000,
        +        "total_gpu_count": 8,
        +        "gpu_class": "any",
        +        "gpu_count": 2,
        +    }
        +    with pytest.raises(ValueError, match="cannot fit"):
        +        _resource_options(None, None, 1, gpu_count=2)
        diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py
        index bb2e6f755..751b24cb3 100644
        --- a/python/python/tests/test_first_class_function_slice2.py
        +++ b/python/python/tests/test_first_class_function_slice2.py
        @@ -9,7 +9,7 @@ import functools
         import importlib.util
         import inspect
         import types
        -from datetime import date
        +from datetime import date, datetime, timedelta
         import http.server
         import json
         import os
        @@ -18,25 +18,33 @@ import subprocess
         import sys
         import typing
         import urllib.parse
        -from typing import Optional
        +import warnings
        +from decimal import Decimal
        +from typing import Annotated, Optional
         
         import pyarrow as pa
         import pytest
         
         import lancedb
         from lancedb import BlobReader
        +from lancedb.db import AsyncConnection, DBConnection, LanceDBConnection
         from lancedb.functions import (
        +    FunctionRegistrationRequest,
        +    FunctionSignature,
        +    FunctionVersion,
             HuggingFaceModel,
        +    PythonEnvironmentBuild,
             PythonRuntimeSpec,
             SecretBinding,
             SecretReference,
        -    UdfDefinition,
        +    FunctionDefinition,
             _canonical_arrow_type,
             _exact_arrow_type,
             _GRAMMAR_PRIMITIVES,
        -    udf,
        +    function,
         )
         from lancedb.secrets import EnvVarSecret
        +from lancedb.remote.db import RemoteDBConnection
         from utils import start_server_thread
         
         THRESHOLD = 20
        @@ -59,7 +67,7 @@ FUNCTION_VERSION = json.loads(
         )["version"]
         
         
        -@udf(
        +@function(
             pip=["numpy>=2"],
             env={"MODE": "test"},
             python_version="3.12",
        @@ -68,7 +76,7 @@ def normalize_score(value: float) -> float:
             return value / 100.0
         
         
        -@udf(
        +@function(
             pip=["openai==3.7.0"],
             env={"MODE": "test"},
             python_version="3.12",
        @@ -77,8 +85,65 @@ def analyze_caption(caption: str) -> str:
             return caption.strip()
         
         
        -def test_scalar_udf_matches_shared_registration_golden_and_remains_callable():
        -    assert isinstance(normalize_score, UdfDefinition)
        +def _function_version_with_resolved_environment():
        +    version = json.loads(
        +        (FIXTURES / "remote_function_version.canonical.json").read_text()
        +    )
        +    version["runtime"] = json.loads(
        +        normalize_score.registration_request.runtime.to_canonical_json()
        +    )
        +    version["resolved_environment"] = {
        +        "packages": [
        +            {
        +                "name": "torch",
        +                "version": "2.9.0+cu130",
        +                "source": "https://packages.example/simple",
        +            },
        +            {"name": "transformers", "version": "4.57.1"},
        +        ],
        +        "provenance": {
        +            "configured_index_urls": ["https://packages.example/simple"],
        +            "configured_find_links": ["https://downloads.example/wheels"],
        +            "resolved_indexes": ["https://packages.example/simple"],
        +            "cuda_toolkit": "12.8",
        +            "torch_version": "torch==2.9.0+cu130",
        +        },
        +        "warnings": [
        +            "transformers resolved to transformers==4.57.1 but is not pinned "
        +            "exactly; add transformers==4.57.1 to pin it."
        +        ],
        +    }
        +    return version
        +
        +
        +def _function_version_with_resolved_environments():
        +    version = json.loads(
        +        (FIXTURES / "remote_function_version.canonical.json").read_text()
        +    )
        +    version["runtime"] = json.loads(
        +        normalize_score.registration_request.runtime.to_canonical_json()
        +    )
        +    version["resolved_environments"] = {
        +        "linux/amd64": {
        +            "packages": [
        +                {
        +                    "name": "torch",
        +                    "version": "2.9.0+cu130",
        +                    "source": "https://packages.example/simple",
        +                }
        +            ],
        +            "warnings": ["amd64 environment warning"],
        +        },
        +        "linux/arm64": {
        +            "packages": [],
        +            "warnings": ["arm64 environment warning"],
        +        },
        +    }
        +    return version
        +
        +
        +def test_scalar_function_matches_shared_registration_golden_and_remains_callable():
        +    assert isinstance(normalize_score, FunctionDefinition)
             assert normalize_score(25.0) == 0.25
             assert (
                 normalize_score.registration_request.to_canonical_json()
        @@ -93,13 +158,125 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable():
             }
         
         
        -def test_udf_declares_pinned_hugging_face_models():
        +def test_refresh_lock_is_a_registration_option_not_part_of_identity():
        +    default = normalize_score.registration_request
        +    old_json = default.to_canonical_json()
        +    assert "refresh_lock" not in json.loads(old_json)
        +
        +    refreshed = default.with_refresh_lock(True)
        +    payload = json.loads(refreshed.to_canonical_json())
        +    assert payload["refresh_lock"] is True
        +    assert (
        +        FunctionRegistrationRequest.from_json(
        +            refreshed.to_canonical_json()
        +        ).refresh_lock
        +        is True
        +    )
        +    assert refreshed.artifact.digest == default.artifact.digest
        +    assert refreshed.runtime.digest == default.runtime.digest
        +    assert default.with_refresh_lock(False).to_canonical_json() == old_json
        +    with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
        +        default.with_refresh_lock(1)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("exist_ok", [False, True])
        +async def test_async_create_function_forwards_refresh_lock(exist_ok):
        +    calls = []
        +
        +    class Inner:
        +        async def create_function_async(
        +            self, request_json, namespace_path=None, *, exist_ok=False
        +        ):
        +            calls.append((json.loads(request_json), namespace_path, exist_ok))
        +            return object()
        +
        +    connection = object.__new__(AsyncConnection)
        +    connection._inner = Inner()
        +    await connection.create_function_async(normalize_score)
        +    await connection.create_function_async(
        +        normalize_score, refresh_lock=True, exist_ok=exist_ok, namespace_path=["team"]
        +    )
        +    with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
        +        await connection.create_function_async(normalize_score, refresh_lock=1)
        +
        +    assert len(calls) == 2
        +    assert "refresh_lock" not in calls[0][0]
        +    assert calls[0][1:] == (None, False)
        +    assert calls[1][0]["refresh_lock"] is True
        +    assert calls[1][1:] == (["team"], exist_ok)
        +
        +
        +@pytest.mark.parametrize("exist_ok", [False, True])
        +def test_sync_create_function_paths_forward_refresh_lock(exist_ok):
        +    calls = []
        +
        +    class AsyncInner:
        +        async def create_function_async(
        +            self,
        +            definition,
        +            *,
        +            secrets=None,
        +            exist_ok=False,
        +            namespace_path=None,
        +            refresh_lock=False,
        +        ):
        +            calls.append(("wrapped", refresh_lock, namespace_path, exist_ok))
        +            return object()
        +
        +    for connection_type in (LanceDBConnection, RemoteDBConnection):
        +        connection = object.__new__(connection_type)
        +        connection._conn = AsyncInner()
        +        connection.create_function_async(
        +            normalize_score,
        +            refresh_lock=True,
        +            exist_ok=exist_ok,
        +            namespace_path=["team"],
        +        )
        +
        +    class BlockingConnection:
        +        def create_function_async(
        +            self,
        +            definition,
        +            *,
        +            secrets=None,
        +            exist_ok=False,
        +            namespace_path=None,
        +            refresh_lock=False,
        +        ):
        +            calls.append(("blocking", refresh_lock, namespace_path, exist_ok))
        +
        +            class ImmediateJob:
        +                def wait(self):
        +                    return "version"
        +
        +            return ImmediateJob()
        +
        +    blocking = BlockingConnection()
        +    assert (
        +        DBConnection.create_function(
        +            blocking,
        +            normalize_score,
        +            refresh_lock=True,
        +            exist_ok=exist_ok,
        +            namespace_path=["team"],
        +        )
        +        == "version"
        +    )
        +    assert calls == [
        +        ("wrapped", True, ["team"], exist_ok),
        +        ("wrapped", True, ["team"], exist_ok),
        +        ("blocking", True, ["team"], exist_ok),
        +    ]
        +
        +
        +def test_function_declares_pinned_hugging_face_models():
             model = HuggingFaceModel(
                 repo="sentence-transformers/all-MiniLM-L6-v2",
                 revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
             )
         
        -    @udf(pip=["sentence-transformers==3.3.1"], models=[model])
        +    @function(pip=["sentence-transformers==3.3.1"], models=[model])
             def embed_text(value: str) -> list[float]:
                 return [1.0]
         
        @@ -114,23 +291,24 @@ def test_udf_declares_pinned_hugging_face_models():
             assert "models" not in undeclared
         
             with pytest.raises(ValueError, match="once"):
        -        udf(name="duplicate_model", models=[model, model])(lambda value: value)
        +        function(name="duplicate_model", models=[model, model])(lambda value: value)
             with pytest.raises(ValueError, match="40-character"):
                 HuggingFaceModel(repo="owner/model", revision="main")
             with pytest.raises(ValueError, match="reserve"):
        -        udf(
        +        function(
                     name="reserved_model_env",
                     models=[model],
                     env={"HF_HOME": "/tmp/model"},
                 )(lambda value: value)
         
         
        -def test_udf_execution_controls_match_shared_registration_golden():
        -    controlled = udf(
        +def test_function_execution_controls_match_shared_registration_golden():
        +    controlled = function(
                 pip=["numpy>=2"],
                 env={"MODE": "test"},
                 python_version="3.12",
                 batch_size=2,
        +        max_concurrency=4,
                 row_timeout_seconds=0.75,
             )(normalize_score.__wrapped__)
             assert (
        @@ -141,8 +319,8 @@ def test_udf_execution_controls_match_shared_registration_golden():
             )
         
         
        -def test_udf_execution_controls_apply_to_vectorized_functions():
        -    @udf(
        +def test_function_execution_controls_apply_to_vectorized_functions():
        +    @function(
                 input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
                 output_schema=pa.int64(),
                 batch_size=3,
        @@ -156,40 +334,73 @@ def test_udf_execution_controls_apply_to_vectorized_functions():
             assert request["row_timeout_seconds"] == 1.25
         
         
        +def test_function_retry_policy_is_part_of_registration():
        +    policy = lancedb.FunctionRetryPolicy(transient=True, max_attempts=4)
        +    definition = function(retry_policy=policy)(normalize_score.__wrapped__)
        +    request = json.loads(definition.registration_request.to_canonical_json())
        +    assert request["retry_policy"] == {"max_attempts": 4, "transient": True}
        +    assert lancedb.FunctionRetryPolicy(max_attempts=1).max_attempts == 1
        +
        +
        +@pytest.mark.parametrize(
        +    "options",
        +    [
        +        {"max_attempts": 0, "transient": True},
        +        {"max_attempts": 101, "transient": True},
        +        {"max_attempts": True},
        +        {"max_attempts": 3},
        +        {"transient": True, "initial_backoff_seconds": -1},
        +        {"transient": True, "max_backoff_seconds": float("inf")},
        +        {"transient": True, "max_backoff_seconds": 0},
        +        {"message_pattern": "["},
        +        {"exception_types": [""]},
        +        {"transient": True, "typo": 1},
        +    ],
        +)
        +def test_function_retry_policy_rejects_invalid_options(options):
        +    with pytest.raises(ValueError):
        +        lancedb.FunctionRetryPolicy(**options)
        +
        +
         @pytest.mark.parametrize(
             ("options", "field"),
             [
                 ({"batch_size": 0}, "batch_size"),
                 ({"batch_size": 2**32}, "batch_size"),
                 ({"batch_size": True}, "batch_size"),
        +        ({"max_concurrency": 0}, "max_concurrency"),
        +        ({"max_concurrency": -1}, "max_concurrency"),
        +        ({"max_concurrency": 2**32}, "max_concurrency"),
        +        ({"max_concurrency": True}, "max_concurrency"),
        +        ({"max_concurrency": 1.5}, "max_concurrency"),
                 ({"row_timeout_seconds": 0}, "row_timeout_seconds"),
                 ({"row_timeout_seconds": -0.25}, "row_timeout_seconds"),
                 ({"row_timeout_seconds": float("inf")}, "row_timeout_seconds"),
                 ({"row_timeout_seconds": True}, "row_timeout_seconds"),
             ],
         )
        -def test_udf_execution_controls_require_their_positive_ranges(options, field):
        +def test_function_execution_controls_require_their_positive_ranges(options, field):
             def identity(value: int) -> int:
                 return value
         
             with pytest.raises(ValueError, match=field):
        -        udf(**options)(identity)
        +        function(**options)(identity)
         
         
         @pytest.mark.parametrize(
             "name", ["examples.image_info", "image-info", "image_info.", "image_info-"]
         )
        -def test_udf_rejects_function_names_with_periods_or_hyphens(name):
        +def test_function_rejects_function_names_with_periods_or_hyphens(name):
             with pytest.raises(ValueError, match="invalid Function name"):
         
        -        @udf(name=name)
        +        @function(name=name)
                 def image_info(value: int) -> int:
                     return value
         
         
         @pytest.mark.parametrize("name", ["image_info", "ImageInfo123", "_image_info", "f"])
        -def test_udf_accepts_function_names_with_letters_digits_and_underscores(name):
        -    @udf(name=name)
        +def test_function_accepts_function_names_with_letters_digits_and_underscores(name):
        +    @function(name=name)
             def image_info(value: int) -> int:
                 return value
         
        @@ -197,7 +408,7 @@ def test_udf_accepts_function_names_with_letters_digits_and_underscores(name):
             assert image_info(1) == 1
         
         
        -def test_secret_bound_udf_matches_its_shared_registration_golden():
        +def test_secret_bound_function_matches_its_shared_registration_golden():
             assert analyze_caption("  hello  ") == "hello"
             bound = analyze_caption.bind_secrets(
                 [EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")]
        @@ -443,15 +654,15 @@ def test_a_secret_name_admits_what_a_namespace_name_does():
                     )
         
         
        -def _main_udf_source(
        +def _main_function_source(
             *, threshold: int = 20, input_annotation: str = "int", comparison: str = ">="
         ) -> str:
             return (
                 "from __future__ import annotations\n"
        -        "from lancedb.functions import udf\n"
        +        "from lancedb.functions import function\n"
                 f"THRESHOLD = {threshold}\n"
                 "\n"
        -        "@udf\n"
        +        "@function\n"
                 f"def label(value: {input_annotation}) -> str:\n"
                 f"    return 'big' if value {comparison} THRESHOLD else 'small'\n"
                 "\n"
        @@ -460,7 +671,7 @@ def _main_udf_source(
             )
         
         
        -def _run_main_udf(path: Path, source: str) -> dict:
        +def _run_main_function(path: Path, source: str) -> dict:
             path.parent.mkdir(parents=True, exist_ok=True)
             path.write_text(source)
             result = subprocess.run(
        @@ -472,15 +683,15 @@ def _run_main_udf(path: Path, source: str) -> dict:
             return json.loads(result.stdout)
         
         
        -def test_main_udf_registration_identity_is_stable_across_processes_and_paths(
        +def test_main_function_registration_identity_is_stable_across_processes_and_paths(
             tmp_path,
         ):
        -    source = _main_udf_source()
        +    source = _main_function_source()
             original_path = tmp_path / "original" / "job.py"
             moved_path = tmp_path / "moved" / "renamed_job.py"
         
        -    original_runs = [_run_main_udf(original_path, source) for _ in range(2)]
        -    moved_run = _run_main_udf(moved_path, source)
        +    original_runs = [_run_main_function(original_path, source) for _ in range(2)]
        +    moved_run = _run_main_function(moved_path, source)
         
             assert len({run["artifact"]["digest"] for run in [*original_runs, moved_run]}) == 1
             assert all(
        @@ -489,15 +700,15 @@ def test_main_udf_registration_identity_is_stable_across_processes_and_paths(
             )
             assert original_runs[0] == original_runs[1] == moved_run
         
        -    body_change = _run_main_udf(
        -        tmp_path / "changes" / "body.py", _main_udf_source(comparison=">")
        +    body_change = _run_main_function(
        +        tmp_path / "changes" / "body.py", _main_function_source(comparison=">")
             )
        -    global_change = _run_main_udf(
        -        tmp_path / "changes" / "global.py", _main_udf_source(threshold=21)
        +    global_change = _run_main_function(
        +        tmp_path / "changes" / "global.py", _main_function_source(threshold=21)
             )
        -    annotation_change = _run_main_udf(
        +    annotation_change = _run_main_function(
                 tmp_path / "changes" / "annotation.py",
        -        _main_udf_source(input_annotation="float"),
        +        _main_function_source(input_annotation="float"),
             )
         
             baseline = original_runs[0]
        @@ -521,11 +732,13 @@ def _run_packaged(definition, *args):
             """Execute the shipped artifact in a fresh namespace, as a worker would."""
             source = base64.b64decode(definition.registration_request.artifact.content.data)
             namespace: dict = {}
        -    exec(compile(source, "", "exec"), namespace)
        +    exec(compile(source, "", "exec"), namespace)
             return namespace[definition.registration_request.artifact.entrypoint](*args)
         
         
        -def _execute_registered_array_udf_v1(request: dict, batch: pa.RecordBatch) -> pa.Array:
        +def _execute_registered_array_function_v1(
        +    request: dict, batch: pa.RecordBatch
        +) -> pa.Array:
             """Exercise adapter-v1 annotation dispatch over a registered artifact."""
             assert request["artifact"]["adapter"] == {
                 "kind": "scalar_to_arrow_batch",
        @@ -539,7 +752,7 @@ def _execute_registered_array_udf_v1(request: dict, batch: pa.RecordBatch) -> pa
                 "RecordBatch": pa.RecordBatch,
                 "typing": typing,
             }
        -    exec(compile(source, "", "exec"), namespace)
        +    exec(compile(source, "", "exec"), namespace)
             function = namespace[request["artifact"]["entrypoint"]]
             parameters = tuple(inspect.signature(function).parameters.values())
             annotations = typing.get_type_hints(function)
        @@ -552,8 +765,8 @@ def _execute_registered_array_udf_v1(request: dict, batch: pa.RecordBatch) -> pa
             return result
         
         
        -def test_udf_conda_environment():
        -    @udf(conda=["scipy", "numpy"], conda_channels=["conda-forge", "defaults"])
        +def test_function_conda_environment():
        +    @function(conda=["scipy", "numpy"], conda_channels=["conda-forge", "defaults"])
             def halve(value: float) -> float:
                 return value / 2
         
        @@ -567,13 +780,13 @@ def test_udf_conda_environment():
             assert "channels" not in pip_request["runtime"]["environment"]
         
             with pytest.raises(ValueError, match="not both"):
        -        udf(name="both", pip=["numpy"], conda=["numpy"])(lambda value: value)
        +        function(name="both", pip=["numpy"], conda=["numpy"])(lambda value: value)
             with pytest.raises(ValueError, match="requires conda"):
        -        udf(name="channels", conda_channels=["conda-forge"])(lambda value: value)
        +        function(name="channels", conda_channels=["conda-forge"])(lambda value: value)
         
         
        -def test_udf_apt_system_packages():
        -    @udf(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"])
        +def test_function_apt_system_packages():
        +    @function(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"])
             def decode(value: float) -> float:
                 return value
         
        @@ -584,7 +797,7 @@ def test_udf_apt_system_packages():
                 "system_packages": ["libavcodec60", "libavutil58"],
             }
         
        -    @udf(conda=["numpy"], apt=["libsndfile1"])
        +    @function(conda=["numpy"], apt=["libsndfile1"])
             def conda_decode(value: float) -> float:
                 return value
         
        @@ -593,14 +806,14 @@ def test_udf_apt_system_packages():
             pip_request = json.loads(normalize_score.registration_request.to_canonical_json())
             assert "system_packages" not in pip_request["runtime"]["environment"]
             with pytest.raises(ValueError, match="trimmed"):
        -        udf(name="padded", apt=[" libsndfile1"])(lambda value: value)
        +        function(name="padded", apt=[" libsndfile1"])(lambda value: value)
         
         
         @pytest.mark.parametrize("packages", [{"pip": ["numpy"]}, {"conda": ["numpy"]}])
        -def test_udf_image(packages):
        +def test_function_image(packages):
             image = "ghcr.io/acme/embedder@sha256:" + "a" * 64
         
        -    @udf(image=image, **packages)
        +    @function(image=image, **packages)
             def embed(value: float) -> float:
                 return value
         
        @@ -613,22 +826,25 @@ def test_udf_image(packages):
         @pytest.mark.parametrize(
             "image", ["ghcr.io/acme/embedder:latest", "embedder@sha256:" + "a" * 64, ""]
         )
        -def test_udf_image_requires_digest_reference(image):
        +def test_function_image_requires_digest_reference(image):
             with pytest.raises(ValueError, match="sha256"):
        -        udf(name="pinned", image=image)(lambda value: value)
        +        function(name="pinned", image=image)(lambda value: value)
         
         
        -def test_udf_gpu_marker_uses_gpu_runtime():
        -    @udf(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
        -    def double_on_gpu(value: int) -> int:
        -        return value * 2
        +def test_function_gpu_marker_uses_gpu_runtime():
        +    with pytest.warns(UserWarning, match="uses a scalar callable"):
        +
        +        @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g", gpu_count=2)
        +        def double_on_gpu(value: int) -> int:
        +            return value * 2
         
             request = json.loads(double_on_gpu.registration_request.to_canonical_json())
             assert request["runtime"]["kind"] == "python_v2"
             assert request["runtime"]["gpu"] is True
             assert request["runtime"]["gpu_class"] == "a10g"
        +    assert request["runtime"]["gpus_per_worker"] == 2
         
        -    @udf(pip=["pyarrow"])
        +    @function(pip=["pyarrow"])
             def cpu_function(value: int) -> int:
                 return value
         
        @@ -642,14 +858,29 @@ def test_udf_gpu_marker_uses_gpu_runtime():
             def identity(value: int) -> int:
                 return value
         
        -    for invalid in [None, 0, 1, -1, 1.5, "", "true", "1", "H100"]:
        -        with pytest.raises(ValueError, match="gpu must be a boolean"):
        -            udf(name="invalid_gpu", gpu=invalid)(identity)
        -    for invalid in ["H100", "a_b", "-a10g", "a10g-", "a" * 64]:
        +    for invalid in [
        +        0,
        +        1,
        +        -1,
        +        1.5,
        +        "",
        +        "true",
        +        "1",
        +        "a_b",
        +        "-a10g",
        +        "a10g-",
        +        "a" * 64,
        +    ]:
        +        with pytest.raises(ValueError, match="gpu"):
        +            function(name="invalid_gpu", gpu=invalid)(identity)
        +    for enabled in (None, False):
        +        for options in ({"gpu_class": "h100"}, {"gpu_count": 2}):
        +            with pytest.raises(ValueError, match="require gpu=True"):
        +                function(gpu=enabled, **options)(identity)
        +    for invalid_class in ("H100", "a_b", "-h100", "h100-", "", "a" * 64):
                 with pytest.raises(ValueError, match="gpu_class"):
        -            udf(name="invalid_gpu_class", gpu=True, gpu_class=invalid)(identity)
        -    with pytest.raises(ValueError, match="requires gpu=True"):
        -        udf(name="gpu_class_without_gpu", gpu_class="a10g")(identity)
        +            function(gpu=True, gpu_class=invalid_class)(identity)
        +    assert function(gpu=False)(identity).registration_request.runtime.gpu is None
         
             base_runtime = {
                 "kind": "python_v2",
        @@ -671,6 +902,120 @@ def test_udf_gpu_marker_uses_gpu_runtime():
                 )
         
         
        +class _GpuScalarFunction:
        +    def __call__(self, value: str) -> int:
        +        return len(value)
        +
        +
        +class _GpuArrayFunction:
        +    def __call__(self, value: pa.Array) -> pa.Array:
        +        return value
        +
        +
        +@pytest.mark.parametrize(
        +    "name, count", [(None, 1), ("h100", 2), ("a10g", 4), ("any", 2)]
        +)
        +def test_gpu_count_is_part_of_runtime_identity(name, count):
        +    with pytest.warns(UserWarning):
        +        definition = function(gpu=True, gpu_class=name, gpu_count=count)(
        +            normalize_score.__wrapped__
        +        )
        +    runtime = definition.registration_request.runtime
        +    assert runtime.gpu is True
        +    assert runtime.gpu_class == name
        +    assert runtime.gpus_per_worker == count
        +    encoded = definition.registration_request.to_canonical_json()
        +    assert json.loads(encoded)["runtime"]["gpus_per_worker"] == count
        +    different = runtime._copy(update={"gpus_per_worker": count + 1})
        +    assert runtime.digest != different.digest
        +
        +
        +@pytest.mark.parametrize("count", [0, -1, True, 1.5, "2", 2**32])
        +def test_gpu_annotation_rejects_invalid_counts(count):
        +    with pytest.raises(ValueError, match="gpu_count"):
        +        function(gpu=True, gpu_count=count)(normalize_score.__wrapped__)
        +
        +
        +@pytest.mark.parametrize("count", [0, -1, True, 1.5, "2", 2**32])
        +def test_gpu_wire_count_is_a_strict_positive_uint32(count):
        +    with pytest.raises(ValueError):
        +        PythonRuntimeSpec.model_validate(
        +            {
        +                "kind": "python_v2",
        +                "python_version": "3.12",
        +                "environment": {"kind": "pip"},
        +                "gpu": True,
        +                "gpus_per_worker": count,
        +            }
        +        )
        +
        +
        +def test_function_annotation_carries_independent_total_defaults():
        +    definition = function(
        +        total_cpu_millis=8000,
        +        total_memory_bytes=16 * 1024**3,
        +        total_gpu_count=0,
        +    )(normalize_score.__wrapped__)
        +    request = json.loads(definition.registration_request.to_canonical_json())
        +    assert request["total_cpu_millis"] == 8000
        +    assert request["total_memory_bytes"] == 16 * 1024**3
        +    assert request["total_gpu_count"] == 0
        +    assert "gpu" not in request["runtime"]
        +    for values in (
        +        {"total_cpu_millis": 0},
        +        {"total_memory_bytes": True},
        +        {"total_memory_bytes": 2**64},
        +        {"total_gpu_count": -1},
        +        {"total_gpu_count": 2**32},
        +    ):
        +        with pytest.raises(ValueError):
        +            function(**values)(normalize_score.__wrapped__)
        +
        +
        +def test_gpu_scalar_warning_names_the_vectorized_alternative():
        +    with pytest.warns(UserWarning, match="model batch is not inferred"):
        +
        +        @function(gpu=True)
        +        def scalar_embedding(value: str) -> list[int]:
        +            return [len(value)]
        +
        +    input_schema = pa.schema([pa.field("value", pa.string(), nullable=False)])
        +    with pytest.warns(UserWarning, match="uses a scalar callable"):
        +        class_scalar = function(_GpuScalarFunction, gpu=True)
        +    with warnings.catch_warnings(record=True) as caught:
        +        warnings.simplefilter("always")
        +
        +        @function(
        +            gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64())
        +        )
        +        def array_embedding(value: pa.Array) -> pa.Array:
        +            return value
        +
        +        @function(
        +            gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64())
        +        )
        +        def record_batch_embedding(value: pa.RecordBatch) -> pa.Array:
        +            return value.column(0)
        +
        +        @function
        +        def cpu_scalar(value: str) -> int:
        +            return len(value)
        +
        +        class_embedding = function(
        +            _GpuArrayFunction,
        +            gpu=True,
        +            input_schema=input_schema,
        +            output_schema=pa.list_(pa.int64()),
        +        )
        +
        +    assert not caught
        +    assert array_embedding.registration_request.batch_size is None
        +    assert record_batch_embedding.registration_request.batch_size is None
        +    assert cpu_scalar.registration_request.batch_size is None
        +    assert class_scalar.registration_request.batch_size is None
        +    assert class_embedding.registration_request.batch_size is None
        +
        +
         def test_unknown_runtime_discards_payload_before_known_field_validation():
             for payload in [
                 {
        @@ -689,8 +1034,8 @@ def test_unknown_runtime_discards_payload_before_known_field_validation():
                 assert runtime.to_canonical_json() == '{"kind":"python_v3"}'
         
         
        -def test_udf_packages_attribute_access_and_body_imports():
        -    @udf
        +def test_function_packages_attribute_access_and_body_imports():
        +    @function
             def word_norm(body: str) -> float:
                 import numpy as np
         
        @@ -703,14 +1048,14 @@ def test_udf_packages_attribute_access_and_body_imports():
             assert _run_packaged(word_norm, "aa bb") == pytest.approx(8**0.5)
         
         
        -def test_udf_packages_module_globals_and_global_caches():
        -    @udf
        +def test_function_packages_module_globals_and_global_caches():
        +    @function
             def label(value: int) -> str:
                 return "big" if value >= THRESHOLD else "small"
         
             assert _run_packaged(label, 21) == "big"
         
        -    @udf
        +    @function
             def cached(value: int) -> int:
                 global _CACHE
                 if _CACHE is None:
        @@ -720,16 +1065,16 @@ def test_udf_packages_module_globals_and_global_caches():
             assert _run_packaged(cached, 2) == 42
         
         
        -def test_udf_annotations_are_not_runtime_names():
        -    @udf
        +def test_function_annotations_are_not_runtime_names():
        +    @function
             def identity(value: date) -> date:
                 return value
         
             assert _run_packaged(identity, date(2026, 8, 25)) == date(2026, 8, 25)
         
         
        -def test_udf_nested_scopes_resolve_lexically():
        -    @udf
        +def test_function_nested_scopes_resolve_lexically():
        +    @function
             def score(value: int) -> int:
                 offset = 2
         
        @@ -741,7 +1086,7 @@ def test_udf_nested_scopes_resolve_lexically():
             assert _run_packaged(score, 3) == 5
         
         
        -def test_udf_resolves_module_globals_before_builtins(tmp_path):
        +def test_function_resolves_module_globals_before_builtins(tmp_path):
             module_path = tmp_path / "shadowing_udfs.py"
             module_path.write_text(
                 "max = 7\n"
        @@ -762,10 +1107,10 @@ def test_udf_resolves_module_globals_before_builtins(tmp_path):
             spec.loader.exec_module(module)
         
             # The module's `max = 7` is what the interpreter would use, so it ships.
        -    assert _run_packaged(udf(module.uses_literal_shadow), 1) == 8
        +    assert _run_packaged(function(module.uses_literal_shadow), 1) == 8
             # A callable global cannot ship; it must not be silently swapped for the builtin.
             with pytest.raises(TypeError, match="unsupported global value of type function"):
        -        udf(module.uses_callable_shadow)
        +        function(module.uses_callable_shadow)
         
         
         def test_canonical_arrow_type_prefers_the_compact_grammar():
        @@ -787,19 +1132,17 @@ def test_canonical_arrow_type_prefers_the_compact_grammar():
                 == "large_list"
             )
             for outside in [
        -        pa.timestamp("us"),
        -        pa.decimal128(10, 2),
                 pa.binary(4),
        -        pa.duration("s"),
        +        pa.time32("s"),
        +        pa.time64("us"),
                 pa.list_(pa.float32(), 0),
        -        pa.list_(pa.timestamp("us")),
             ]:
                 with pytest.raises(TypeError, match="unsupported Arrow type"):
                     _canonical_arrow_type(outside)
         
         
        -def test_udf_nested_annotations_are_postponed_in_the_artifact():
        -    @udf
        +def test_function_nested_annotations_are_postponed_in_the_artifact():
        +    @function
             def score(value: int) -> int:
                 def identity(item: date) -> date:
                     return item
        @@ -810,8 +1153,8 @@ def test_udf_nested_annotations_are_postponed_in_the_artifact():
             assert _run_packaged(score, 3) == 3
         
         
        -def test_udf_ships_globals_the_body_deletes():
        -    @udf
        +def test_function_ships_globals_the_body_deletes():
        +    @function
             def clear(value: int) -> int:
                 global _CACHE
                 del _CACHE
        @@ -820,7 +1163,7 @@ def test_udf_ships_globals_the_body_deletes():
             assert _run_packaged(clear, 3) == 3
         
         
        -def test_udf_rejects_a_module_global_that_does_not_import_as_itself(tmp_path):
        +def test_function_rejects_a_module_global_that_does_not_import_as_itself(tmp_path):
             module_path = tmp_path / "fake_module_udfs.py"
             module_path.write_text(
                 "import types\n"
        @@ -834,10 +1177,10 @@ def test_udf_rejects_a_module_global_that_does_not_import_as_itself(tmp_path):
             module = importlib.util.module_from_spec(spec)
             spec.loader.exec_module(module)
             with pytest.raises(TypeError, match="does not import as 'numpy'"):
        -        udf(module.score)
        +        function(module.score)
         
         
        -def test_udf_rejects_a_module_level_namespace_alias(tmp_path):
        +def test_function_rejects_a_module_level_namespace_alias(tmp_path):
             module_path = tmp_path / "aliasing_udfs.py"
             module_path.write_text(
                 "import builtins as b\n"
        @@ -849,8 +1192,8 @@ def test_udf_rejects_a_module_level_namespace_alias(tmp_path):
             spec = importlib.util.spec_from_file_location("aliasing_udfs", module_path)
             module = importlib.util.module_from_spec(spec)
             spec.loader.exec_module(module)
        -    with pytest.raises(ValueError, match="dynamic namespace access"):
        -        udf(module.score)
        +    with pytest.raises(ValueError, match="imports from namespace-access modules"):
        +        function(module.score)
         
         
         @pytest.mark.parametrize(
        @@ -860,10 +1203,9 @@ def test_udf_rejects_a_module_level_namespace_alias(tmp_path):
                 "eval('THRESHOLD')",
                 "(lambda g: g()['THRESHOLD'])(globals)",
                 "__import__('sys').modules[__name__].THRESHOLD",
        -        "sys.modules[__name__].THRESHOLD",
             ],
         )
        -def test_udf_rejects_dynamic_namespace_access(access):
        +def test_function_rejects_dynamic_namespace_access(access):
             namespace: dict = {}
             exec(
                 f"def score(value: int) -> int:\n    return value + {access}\n",
        @@ -872,9 +1214,7 @@ def test_udf_rejects_dynamic_namespace_access(access):
             )
             with pytest.raises(ValueError, match="dynamic namespace access"):
                 _package_from_text(
        -            "def score(value: int) -> int:\n"
        -            "    import sys\n"
        -            f"    return value + {access}\n"
        +            f"def score(value: int) -> int:\n    return value + {access}\n"
                 )
         
         
        @@ -883,9 +1223,11 @@ def _package_from_text(source: str, module_globals: dict | None = None):
             import tempfile
         
             directory = tempfile.mkdtemp()
        -    path = Path(directory) / "generated_udf_module.py"
        +    path = Path(directory) / "generated_function_module.py"
             path.write_text(source)
        -    spec = importlib.util.spec_from_file_location(f"generated_udf_{id(source)}", path)
        +    spec = importlib.util.spec_from_file_location(
        +        f"generated_function_{id(source)}", path
        +    )
             module = importlib.util.module_from_spec(spec)
             if module_globals:
                 module.__dict__.update(module_globals)
        @@ -895,10 +1237,10 @@ def _package_from_text(source: str, module_globals: dict | None = None):
                 for value in vars(module).values()
                 if callable(value) and getattr(value, "__module__", None) == module.__name__
             ]
        -    return udf(functions[0])
        +    return function(functions[0])
         
         
        -def test_udf_rejects_a_non_standard_builtins_environment():
        +def test_function_rejects_a_non_standard_builtins_environment():
             def score(value: int) -> int:
                 return len([1]) + value
         
        @@ -913,7 +1255,7 @@ def test_udf_rejects_a_non_standard_builtins_environment():
             patched.__annotations__ = score.__annotations__
             assert patched(3) == 102
             with pytest.raises(ValueError, match="non-standard builtins environment"):
        -        udf(patched)
        +        function(patched)
         
             class ReportingDict(dict):  # reports standard entries, resolves differently
                 def __missing__(self, key):
        @@ -925,7 +1267,7 @@ def test_udf_rejects_a_non_standard_builtins_environment():
             disguised.__annotations__ = score.__annotations__
             assert disguised(3) == 102
             with pytest.raises(ValueError, match="non-standard builtins environment"):
        -        udf(disguised)
        +        function(disguised)
         
             hooked = types.FunctionType(
                 score.__code__,
        @@ -934,10 +1276,10 @@ def test_udf_rejects_a_non_standard_builtins_environment():
             )
             hooked.__annotations__ = score.__annotations__
             with pytest.raises(ValueError, match="non-standard builtins environment"):
        -        udf(hooked)
        +        function(hooked)
         
         
        -def test_udf_recursion_versus_a_rebound_module_name(tmp_path):
        +def test_function_recursion_versus_a_rebound_module_name(tmp_path):
             module_path = tmp_path / "rebound_udfs.py"
             module_path.write_text(
                 "def fact(value: int) -> int:\n"
        @@ -949,20 +1291,20 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path):
             spec = importlib.util.spec_from_file_location("rebound_udfs", module_path)
             module = importlib.util.module_from_spec(spec)
             spec.loader.exec_module(module)
        -    assert _run_packaged(udf(module.fact), 5) == 120
        +    assert _run_packaged(function(module.fact), 5) == 120
             raw = module.score
             module.score = 10
             with pytest.raises(ValueError, match="binds that name to another value"):
        -        udf(raw)
        +        function(raw)
             # A wrapper that merely exposes __wrapped__ is not the function.
             module.score = functools.wraps(raw)(lambda value: 41)
             with pytest.raises(ValueError, match="binds that name to another value"):
        -        udf(raw)
        +        function(raw)
             # The decorator's own result is; a subclass of it is not.
        -    module.fact = udf(module.fact)
        +    module.fact = function(module.fact)
             assert _run_packaged(module.fact, 4) == 24
         
        -    class Twisted(UdfDefinition):
        +    class Twisted(FunctionDefinition):
                 def __call__(self, *args, **kwargs):
                     return 41
         
        @@ -977,7 +1319,7 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path):
                 python_version=None,
             )
             with pytest.raises(ValueError, match="binds that name to another value"):
        -        udf(raw_fact)
        +        function(raw_fact)
         
         
         def test_canonical_arrow_type_uses_exact_json_for_list_child_properties():
        @@ -1048,12 +1390,12 @@ def _shadows_missing_in_a_lambda(value: int) -> int:
         
         
         @pytest.mark.parametrize(
        -    "function",
        +    "target",
             [_calls_missing, _shadows_missing_in_a_comprehension, _shadows_missing_in_a_lambda],
         )
        -def test_udf_rejects_a_truly_unresolved_global(function):
        +def test_function_rejects_a_truly_unresolved_global(target):
             with pytest.raises(ValueError, match=r"unresolved global names: \['missing'\]"):
        -        udf(function)
        +        function(target)
         
         
         def _arrow_type_from_golden(spec: dict) -> pa.DataType:
        @@ -1108,7 +1450,7 @@ def test_explicit_arrow_schema_is_deterministic():
                 nullable=False,
             )
         
        -    @udf(input_schema=input_schema, output_schema=output_schema)
        +    @function(input_schema=input_schema, output_schema=output_schema)
             def explicit(value):
                 return [value, value, value]
         
        @@ -1119,8 +1461,342 @@ def test_explicit_arrow_schema_is_deterministic():
             assert signature.output.nullable is False
         
         
        +def test_timestamp_annotation_and_explicit_schema_serialization():
        +    for unit in ("s", "ms", "us", "ns"):
        +        for timezone in (None, "UTC", "America/New_York", "+08:00", "-05:00"):
        +            encoded = json.loads(_canonical_arrow_type(pa.timestamp(unit, tz=timezone)))
        +            if unit == "us" and timezone is None:
        +                assert encoded == {"type": "timestamp"}
        +            else:
        +                suffix = timezone if timezone is not None else "-"
        +                assert encoded == {"type": f"timestamp:{unit}:{suffix}"}
        +
        +    with pytest.raises(TypeError, match="reserved for no timezone"):
        +        _canonical_arrow_type(pa.timestamp("us", tz="-"))
        +
        +    @function
        +    def normalize(
        +        ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")],
        +    ) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]:
        +        return ts
        +
        +    signature = normalize.registration_request.signature
        +    assert json.loads(signature.inputs[0].arrow_type) == {"type": "timestamp:ns:UTC"}
        +    assert json.loads(signature.output.arrow_type) == {"type": "timestamp:ns:UTC"}
        +    round_trip = FunctionSignature.from_json(signature.to_canonical_json())
        +    assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
        +    assert round_trip.output.arrow_type == signature.output.arrow_type
        +
        +    @function
        +    def optional_timestamp(
        +        ts: Optional[Annotated[datetime, pa.timestamp("ms", tz="UTC")]],
        +    ) -> int:
        +        return 0
        +
        +    optional_input = optional_timestamp.registration_request.signature.inputs[0]
        +    assert optional_input.nullable is True
        +    assert json.loads(optional_input.arrow_type) == {"type": "timestamp:ms:UTC"}
        +
        +    @function
        +    def legacy(ts: datetime) -> datetime:
        +        return ts
        +
        +    legacy_signature = legacy.registration_request.signature
        +    assert json.loads(legacy_signature.inputs[0].arrow_type) == {"type": "timestamp"}
        +    assert json.loads(legacy_signature.output.arrow_type) == {"type": "timestamp"}
        +    legacy_round_trip = FunctionSignature.from_json(
        +        legacy_signature.to_canonical_json()
        +    )
        +    assert legacy_round_trip.inputs[0].arrow_type == '{"type":"timestamp"}'
        +
        +    input_schema = pa.schema(
        +        [pa.field("ts", pa.timestamp("ms", tz="America/New_York"), nullable=True)]
        +    )
        +    output_schema = pa.schema(
        +        [
        +            pa.field("ts", pa.timestamp("ns", tz="+08:00"), nullable=True),
        +            pa.field("elapsed", pa.duration("ms"), nullable=False),
        +        ]
        +    )
        +
        +    @function(input_schema=input_schema, output_schema=output_schema)
        +    def nested(ts):
        +        return {"ts": ts, "elapsed": None}
        +
        +    nested_signature = nested.registration_request.signature
        +    assert nested_signature.inputs[0].nullable is True
        +    assert json.loads(nested_signature.inputs[0].arrow_type) == {
        +        "type": "timestamp:ms:America/New_York"
        +    }
        +    assert nested_signature.output.kind == "named_struct"
        +    assert nested_signature.output.fields[0].nullable is True
        +    assert json.loads(nested_signature.output.fields[0].arrow_type) == {
        +        "type": "timestamp:ns:+08:00"
        +    }
        +    assert json.loads(nested_signature.output.fields[1].arrow_type) == {
        +        "type": "duration:ms"
        +    }
        +
        +    list_type = pa.list_(pa.field("item", pa.timestamp("ms", tz="UTC"), nullable=False))
        +    assert json.loads(_canonical_arrow_type(list_type)) == {
        +        "type": "list",
        +        "fields": [
        +            {
        +                "name": "item",
        +                "nullable": False,
        +                "type": {"type": "timestamp:ms:UTC"},
        +            }
        +        ],
        +    }
        +
        +
        +def test_duration_annotation_and_explicit_schema_serialization():
        +    for unit in ("s", "ms", "us", "ns"):
        +        encoded = json.loads(_canonical_arrow_type(pa.duration(unit)))
        +        expected = (
        +            {"type": "duration"} if unit == "us" else {"type": f"duration:{unit}"}
        +        )
        +        assert encoded == expected
        +
        +    @function
        +    def elapsed(
        +        value: Annotated[timedelta, pa.duration("s")],
        +    ) -> Annotated[timedelta, pa.duration("ns")]:
        +        return value
        +
        +    signature = elapsed.registration_request.signature
        +    assert json.loads(signature.inputs[0].arrow_type) == {"type": "duration:s"}
        +    assert json.loads(signature.output.arrow_type) == {"type": "duration:ns"}
        +    round_trip = FunctionSignature.from_json(signature.to_canonical_json())
        +    assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
        +    assert round_trip.output.arrow_type == signature.output.arrow_type
        +
        +    @function
        +    def optional_elapsed(
        +        value: Optional[Annotated[timedelta, pa.duration("ms")]],
        +    ) -> int:
        +        return 0
        +
        +    optional_input = optional_elapsed.registration_request.signature.inputs[0]
        +    assert optional_input.nullable is True
        +    assert json.loads(optional_input.arrow_type) == {"type": "duration:ms"}
        +
        +    with pytest.raises(
        +        TypeError, match="timedelta Function annotations require an explicit unit"
        +    ):
        +
        +        @function
        +        def missing(value: timedelta) -> timedelta:
        +            return value
        +
        +    input_schema = pa.schema([pa.field("elapsed", pa.duration("ms"), nullable=True)])
        +    output_schema = pa.field("result", pa.duration("us"), nullable=False)
        +
        +    @function(input_schema=input_schema, output_schema=output_schema)
        +    def explicit(elapsed: timedelta) -> timedelta:
        +        return elapsed
        +
        +    explicit_signature = explicit.registration_request.signature
        +    assert explicit_signature.inputs[0].nullable is True
        +    assert json.loads(explicit_signature.inputs[0].arrow_type) == {
        +        "type": "duration:ms"
        +    }
        +    assert json.loads(explicit_signature.output.arrow_type) == {"type": "duration"}
        +    explicit_round_trip = FunctionSignature.from_json(
        +        explicit_signature.to_canonical_json()
        +    )
        +    assert explicit_round_trip.output.arrow_type == '{"type":"duration"}'
        +
        +
        +def test_map_annotation_and_explicit_schema_serialization():
        +    @function
        +    def map_round_trip(values: dict[str, int]) -> dict[str, int]:
        +        return values
        +
        +    signature = map_round_trip.registration_request.signature
        +    expected = {
        +        "type": "map",
        +        "fields": [
        +            {
        +                "name": "entries",
        +                "nullable": False,
        +                "type": {
        +                    "type": "struct",
        +                    "fields": [
        +                        {
        +                            "name": "key",
        +                            "nullable": False,
        +                            "type": {"type": "utf8"},
        +                        },
        +                        {
        +                            "name": "value",
        +                            "nullable": False,
        +                            "type": {"type": "int64"},
        +                        },
        +                    ],
        +                },
        +            }
        +        ],
        +    }
        +    assert json.loads(signature.inputs[0].arrow_type) == expected
        +    assert json.loads(signature.output.arrow_type) == expected
        +    round_trip = FunctionSignature.from_json(signature.to_canonical_json())
        +    assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
        +    assert round_trip.output.arrow_type == signature.output.arrow_type
        +
        +    @function
        +    def nullable_values(
        +        values: dict[str, Optional[int]],
        +    ) -> dict[str, Optional[int]]:
        +        return values
        +
        +    nullable_signature = nullable_values.registration_request.signature
        +    nullable_map = json.loads(nullable_signature.inputs[0].arrow_type)
        +    assert nullable_map["fields"][0]["type"]["fields"][1] == {
        +        "name": "value",
        +        "nullable": True,
        +        "type": {"type": "int64"},
        +    }
        +
        +    input_schema = pa.schema(
        +        [
        +            pa.field(
        +                "values",
        +                pa.map_(pa.string(), pa.field("custom", pa.int64(), nullable=True)),
        +                nullable=False,
        +            )
        +        ]
        +    )
        +    output_schema = pa.field(
        +        "result",
        +        pa.map_(pa.string(), pa.field("value", pa.int64(), nullable=False)),
        +        nullable=False,
        +    )
        +
        +    @function(input_schema=input_schema, output_schema=output_schema)
        +    def explicit(values):
        +        return {}
        +
        +    explicit_signature = explicit.registration_request.signature
        +    explicit_input = json.loads(explicit_signature.inputs[0].arrow_type)
        +    assert explicit_input["fields"][0]["type"]["fields"][1] == {
        +        "name": "custom",
        +        "nullable": True,
        +        "type": {"type": "int64"},
        +    }
        +    explicit_output = json.loads(explicit_signature.output.arrow_type)
        +    assert explicit_output["fields"][0]["type"]["fields"][1]["nullable"] is False
        +
        +
        +def test_map_rejects_unsupported_boundaries():
        +    with pytest.raises(TypeError, match="map keys_sorted=true"):
        +        _canonical_arrow_type(pa.map_(pa.string(), pa.int64(), keys_sorted=True))
        +    with pytest.raises(TypeError, match="map keys must be non-nullable utf8"):
        +        _canonical_arrow_type(pa.map_(pa.int64(), pa.int64()))
        +    with pytest.raises(TypeError, match="Blob v2 fields nested under"):
        +        _canonical_arrow_type(pa.map_(pa.string(), lancedb.blob("image").type))
        +    with pytest.raises(TypeError, match="map keys must be str"):
        +
        +        @function
        +        def invalid_keys(values: dict[int, int]) -> int:
        +            return 0
        +
        +
        +def test_decimal_annotation_and_explicit_schema_serialization():
        +    @function
        +    def price(
        +        amount: Annotated[Decimal, pa.decimal128(10, 2)],
        +    ) -> Annotated[Decimal, pa.decimal256(50, 4)]:
        +        return Decimal("1.0000")
        +
        +    signature = price.registration_request.signature
        +    assert json.loads(signature.inputs[0].arrow_type) == {
        +        "type": "decimal128",
        +        "length": 10002,
        +    }
        +    assert json.loads(signature.output.arrow_type) == {
        +        "type": "decimal256",
        +        "length": 50004,
        +    }
        +    round_trip = FunctionSignature.from_json(signature.to_canonical_json())
        +    assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
        +    assert round_trip.output.arrow_type == signature.output.arrow_type
        +    assert json.loads(_canonical_arrow_type(pa.decimal128(10, -2))) == {
        +        "type": "decimal128",
        +        "length": 9998,
        +    }
        +    decimal_map = json.loads(
        +        _canonical_arrow_type(pa.map_(pa.string(), pa.decimal128(10, 2)))
        +    )
        +    assert decimal_map["fields"][0]["type"]["fields"][1]["type"] == {
        +        "type": "decimal128",
        +        "length": 10002,
        +    }
        +
        +    input_schema = pa.schema([pa.field("amount", pa.decimal128(12, 2), nullable=False)])
        +    output_schema = pa.field("result", pa.decimal256(60, 6), nullable=False)
        +
        +    @function(input_schema=input_schema, output_schema=output_schema)
        +    def explicit(amount: Decimal) -> Decimal:
        +        return amount
        +
        +    explicit_signature = explicit.registration_request.signature
        +    assert json.loads(explicit_signature.inputs[0].arrow_type) == {
        +        "type": "decimal128",
        +        "length": 12002,
        +    }
        +    assert json.loads(explicit_signature.output.arrow_type) == {
        +        "type": "decimal256",
        +        "length": 60006,
        +    }
        +
        +    with pytest.raises(
        +        TypeError, match="Decimal Function annotations require precision and scale"
        +    ):
        +
        +        @function
        +        def missing(amount: Decimal) -> Decimal:
        +            return amount
        +
        +
        +def test_nullable_scalar_output_annotation_and_explicit_schema():
        +    input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)])
        +
        +    @function(input_schema=input_schema)
        +    def optional_annotation(value: int) -> Optional[int]:
        +        return None if value == 0 else value * 2
        +
        +    @function(input_schema=input_schema)
        +    def optional_union(value: int) -> int | None:
        +        return None if value == 0 else value * 2
        +
        +    @function(
        +        input_schema=input_schema,
        +        output_schema=pa.field("result", pa.int64(), nullable=True),
        +    )
        +    def explicit_schema(value: int):
        +        return None if value == 0 else value * 2
        +
        +    for definition in (optional_annotation, optional_union, explicit_schema):
        +        signature = definition.registration_request.signature
        +        assert (signature.output.kind, signature.output.arrow_type) == (
        +            "scalar",
        +            "int64",
        +        )
        +        assert signature.output.nullable is True
        +        assert json.loads(signature.to_canonical_json())["output"] == {
        +            "kind": "scalar",
        +            "arrow_type": "int64",
        +            "nullable": True,
        +        }
        +        assert (
        +            FunctionSignature.from_json(signature.to_canonical_json()).output.nullable
        +            is True
        +        )
        +
        +
         def test_blob_fields_use_the_scalar_function_semantic_type():
        -    @udf(
        +    @function(
                 input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
                 output_schema=lancedb.blob("result", nullable=False),
             )
        @@ -1134,12 +1810,12 @@ def test_blob_fields_use_the_scalar_function_semantic_type():
         
         
         def test_blob_input_access_is_inferred_from_annotations():
        -    @udf
        +    @function
             def read_blob(video: BlobReader, timestamp_s: float) -> bytes:
                 video.seek(int(timestamp_s))
                 return video.read(4)
         
        -    @udf
        +    @function
             def read_bytes(video: bytes) -> int:
                 return len(video)
         
        @@ -1156,11 +1832,11 @@ def test_blob_input_access_is_inferred_from_annotations():
         
         
         def test_nullable_blob_reader_and_explicit_blob_bytes():
        -    @udf
        +    @function
             def nullable(video: Optional[BlobReader]) -> int:
                 return 0 if video is None else video.size()
         
        -    @udf(
        +    @function(
                 input_schema=pa.schema([lancedb.blob("video", nullable=False)]),
                 output_schema=pa.field("size", pa.int64(), nullable=False),
             )
        @@ -1180,7 +1856,7 @@ def test_blob_reader_rejects_an_incompatible_explicit_schema():
                 return video.size()
         
             with pytest.raises(TypeError, match="requires a Blob V2 field"):
        -        udf(
        +        function(
                     read,
                     input_schema=pa.schema([pa.field("video", pa.int64(), nullable=False)]),
                     output_schema=pa.field("size", pa.int64(), nullable=False),
        @@ -1188,7 +1864,7 @@ def test_blob_reader_rejects_an_incompatible_explicit_schema():
         
         
         def test_whole_named_struct_function_can_include_a_blob_result_field():
        -    @udf(
        +    @function(
                 input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
                 output_schema=pa.field(
                     "payload",
        @@ -1242,7 +1918,7 @@ def test_struct_blob_signature_fields_preserve_exact_metadata_and_nullability():
                 nullable=False,
             )
         
        -    @udf(input_schema=pa.schema([nested_input]), output_schema=nested_output)
        +    @function(input_schema=pa.schema([nested_input]), output_schema=nested_output)
             def copy_payload(payload):
                 return payload
         
        @@ -1286,7 +1962,7 @@ def test_struct_blob_signature_supports_multiple_struct_levels():
                 nullable=False,
             )
         
        -    @udf(
        +    @function(
                 input_schema=pa.schema([recursive]),
                 output_schema=pa.field("size", pa.int64(), nullable=False),
             )
        @@ -1307,7 +1983,7 @@ def test_struct_blob_signature_supports_multiple_struct_levels():
             ],
         )
         def test_blob_output_accepts_list_ancestors(data_type):
        -    @udf(
        +    @function(
                 input_schema=pa.schema([lancedb.blob("video", nullable=False)]),
                 output_schema=pa.field("frames", data_type, nullable=False),
             )
        @@ -1332,7 +2008,7 @@ def test_blob_output_accepts_list_ancestors(data_type):
         def test_blob_output_rejects_map_and_fixed_size_list_ancestors(data_type):
             with pytest.raises(TypeError, match="nested under collection types"):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([pa.field("id", pa.int64(), nullable=False)]),
                     output_schema=pa.field("frames", data_type, nullable=False),
                 )
        @@ -1343,7 +2019,7 @@ def test_blob_output_rejects_map_and_fixed_size_list_ancestors(data_type):
         def test_blob_output_named_struct_accepts_list_ancestor():
             frames_type = pa.list_(lancedb.blob("item", nullable=False))
         
        -    @udf(
        +    @function(
                 input_schema=pa.schema([pa.field("id", pa.int64(), nullable=False)]),
                 output_schema=pa.schema(
                     [
        @@ -1381,7 +2057,7 @@ def test_blob_signature_rejects_collection_ancestors(data_type):
                 match="Blob v2 fields nested under collection types are not supported",
             ):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([pa.field("value", data_type, nullable=False)]),
                     output_schema=pa.field("size", pa.int64(), nullable=False),
                 )
        @@ -1408,7 +2084,7 @@ def test_blob_signature_rejects_collection_below_a_struct():
                 match="Blob v2 fields nested under collection types are not supported",
             ):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([nested]),
                     output_schema=pa.field("size", pa.int64(), nullable=False),
                 )
        @@ -1417,7 +2093,7 @@ def test_blob_signature_rejects_collection_below_a_struct():
         
         
         def test_blob_fields_support_vectorized_pyarrow_arrays():
        -    @udf(
        +    @function(
                 input_schema=pa.schema([lancedb.blob("image", nullable=True)]),
                 output_schema=lancedb.blob("result", nullable=False),
             )
        @@ -1430,7 +2106,7 @@ def test_blob_fields_support_vectorized_pyarrow_arrays():
             values = pa.array([b"large blob", b"", None], type=pa.large_binary())
             request = json.loads(copy_blobs.registration_request.to_canonical_json())
             batch = pa.RecordBatch.from_arrays([values], names=["image"])
        -    result = _execute_registered_array_udf_v1(request, batch)
        +    result = _execute_registered_array_function_v1(request, batch)
             assert isinstance(result, pa.LargeBinaryArray)
             assert result.to_pylist() == [b"large blob", b"", b""]
         
        @@ -1451,7 +2127,7 @@ def test_blob_fields_support_vectorized_pyarrow_arrays():
         
         
         def test_documented_blob_array_identity_executes_packaged_artifact():
        -    @udf(
        +    @function(
                 input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
                 output_schema=lancedb.blob("copy", nullable=False),
             )
        @@ -1460,7 +2136,7 @@ def test_documented_blob_array_identity_executes_packaged_artifact():
         
             values = pa.array([b"large blob", b""], type=pa.large_binary())
             request = json.loads(copy_blobs.registration_request.to_canonical_json())
        -    result = _execute_registered_array_udf_v1(
        +    result = _execute_registered_array_function_v1(
                 request,
                 pa.RecordBatch.from_arrays([values], names=["image"]),
             )
        @@ -1468,7 +2144,7 @@ def test_documented_blob_array_identity_executes_packaged_artifact():
         
         
         def test_named_struct_function_can_include_a_blob_result_field():
        -    @udf(
        +    @function(
                 input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
                 output_schema=pa.schema(
                     [
        @@ -1489,7 +2165,7 @@ def test_named_struct_function_can_include_a_blob_result_field():
         
         
         def test_named_struct_function_preserves_nullable_result_fields():
        -    @udf(
        +    @function(
                 input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
                 output_schema=pa.schema(
                     [
        @@ -1507,7 +2183,7 @@ def test_named_struct_function_preserves_nullable_result_fields():
                 ("failure_code", False),
             ]
         
        -    @udf(
        +    @function(
                 input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
                 output_schema=pa.schema(
                     [
        @@ -1537,7 +2213,7 @@ def test_metadata_marked_blob_field_uses_the_semantic_type():
                 metadata={"ARROW:extension:name": "lance.blob.v2"},
             )
         
        -    @udf(
        +    @function(
                 input_schema=pa.schema([metadata_blob]),
                 output_schema=pa.field("size", pa.int64(), nullable=False),
             )
        @@ -1557,7 +2233,7 @@ def test_blob_marker_rejects_invalid_storage_layout():
         
             with pytest.raises(TypeError, match="requires a supported Blob storage layout"):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([malformed]),
                     output_schema=pa.field("size", pa.int64(), nullable=False),
                 )
        @@ -1584,7 +2260,7 @@ def test_nested_non_blob_extension_is_not_silently_unwrapped():
             )
             with pytest.raises(TypeError, match="unsupported Arrow type"):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([nested]),
                     output_schema=pa.field("result", pa.int64(), nullable=False),
                 )
        @@ -1596,7 +2272,7 @@ def test_explicit_large_utf8_schemas_use_the_canonical_function_name():
             input_schema = pa.schema([pa.field("text", pa.large_string(), nullable=True)])
             output_schema = pa.field("result", pa.large_string(), nullable=False)
         
        -    @udf(input_schema=input_schema, output_schema=output_schema)
        +    @function(input_schema=input_schema, output_schema=output_schema)
             def preserve(text):
                 return text
         
        @@ -1622,7 +2298,7 @@ def test_explicit_large_utf8_schemas_use_the_canonical_function_name():
         def test_large_binary_schemas_use_the_canonical_function_name():
             payload = pa.field("data", pa.large_binary(), nullable=True)
         
        -    @udf(
        +    @function(
                 input_schema=pa.schema([payload]),
                 output_schema=pa.field("result", pa.large_binary(), nullable=False),
             )
        @@ -1693,7 +2369,7 @@ def test_nested_struct_output_uses_canonical_exact_json():
                 ]
             )
         
        -    @udf(
        +    @function(
                 input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]),
                 output_schema=pa.field("analysis", analysis, nullable=False),
             )
        @@ -1743,31 +2419,25 @@ def test_nested_struct_output_uses_canonical_exact_json():
         def test_annotation_and_explicit_schema_validation_fail_closed():
             with pytest.raises(TypeError, match="missing Function annotations"):
         
        -        @udf
        +        @function
                 def missing(value):
                     return value
         
             with pytest.raises(TypeError, match="unsupported Function annotation"):
         
        -        @udf
        +        @function
                 def unsupported(value: set[str]) -> str:
                     return ""
         
        -    with pytest.raises(ValueError, match="output must be non-nullable"):
        -
        -        @udf
        -        def nullable_output(value: int) -> Optional[int]:
        -            return value
        -
             with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"):
         
        -        @udf(input_schema=pa.schema([pa.field("value", pa.int64())]))
        +        @function(input_schema=pa.schema([pa.field("value", pa.int64())]))
                 def partial_schema(value):
                     return value
         
             with pytest.raises(ValueError, match="exactly match callable parameters"):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([pa.field("other", pa.int64())]),
                     output_schema=pa.int64(),
                 )
        @@ -1776,12 +2446,27 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
         
             with pytest.raises(ValueError, match="output must be non-nullable"):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([pa.field("value", pa.int64())]),
        -            output_schema=pa.field("result", pa.int64(), nullable=True),
        +            output_schema=pa.field(
        +                "result",
        +                pa.struct([pa.field("value", pa.int64(), nullable=False)]),
        +                nullable=True,
        +            ),
                 )
        -        def nullable_explicit(value):
        -            return value
        +        def nullable_struct(value):
        +            return {"value": value}
        +
        +    with pytest.raises(
        +        ValueError, match="Blob v2 Function output must be non-nullable"
        +    ):
        +
        +        @function(
        +            input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
        +            output_schema=lancedb.blob("result", nullable=True),
        +        )
        +        def nullable_blob(image):
        +            return image
         
             for invalid_field in [
                 pa.field("", pa.int32(), nullable=False),
        @@ -1789,7 +2474,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
             ]:
                 with pytest.raises(TypeError, match="unsupported Arrow type"):
         
        -            @udf(
        +            @function(
                         input_schema=pa.schema([pa.field("value", pa.int64())]),
                         output_schema=pa.schema([invalid_field]),
                     )
        @@ -1798,7 +2483,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
         
             with pytest.raises(TypeError, match="unsupported Arrow type"):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema(
                         [pa.field("value", pa.int64(), metadata={"k": "v"})]
                     ),
        @@ -1809,7 +2494,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
         
             with pytest.raises(TypeError, match="unsupported Arrow type"):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([pa.field("value", pa.int64())]),
                     output_schema=pa.field(
                         "result", pa.int64(), nullable=False, metadata={"k": "v"}
        @@ -1821,7 +2506,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
             struct_type = pa.struct([pa.field("value", pa.int64(), nullable=False)])
             with pytest.raises(TypeError, match="unsupported Arrow type"):
         
        -        @udf(
        +        @function(
                     input_schema=pa.schema([pa.field("value", pa.int64())]),
                     output_schema=pa.field(
                         "result", struct_type, nullable=False, metadata={"k": "v"}
        @@ -1845,11 +2530,34 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
             ]:
                 with pytest.raises(TypeError, match="schema metadata"):
         
        -            @udf(input_schema=input_schema, output_schema=output_schema)
        +            @function(input_schema=input_schema, output_schema=output_schema)
                     def schema_metadata(value):
                         return value
         
         
        +def test_default_function_runtime_matches_server_identity():
        +    definition = function(python_version="3.12")(analyze_caption.__wrapped__)
        +    runtime = definition.registration_request.runtime
        +    assert runtime.env == {}
        +    cases = json.loads((FIXTURES / "runtime_identity.json").read_text(encoding="utf-8"))
        +    expected = next(
        +        case["digest"] for case in cases if case["name"] == "empty-environment"
        +    )
        +    assert runtime.digest == expected
        +
        +
        +def test_environment_changes_do_not_change_source_identity():
        +    definition = function(
        +        pip=["openai==3.46.0"],
        +        env={"MODE": "test"},
        +        python_version="3.12",
        +    )(analyze_caption.__wrapped__)
        +    previous = analyze_caption.registration_request
        +    changed = definition.registration_request
        +    assert previous.artifact.digest == changed.artifact.digest
        +    assert previous.runtime.digest != changed.runtime.digest
        +
        +
         def test_local_function_catalog_operations_are_not_supported(tmp_path):
             db = lancedb.connect(tmp_path)
             message = "Function catalog operations are not supported by this database"
        @@ -1859,12 +2567,392 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path):
                 db.create_function_async(normalize_score)
             with pytest.raises(NotImplementedError, match=message):
                 db.get_function("normalize_score", version=FUNCTION_VERSION)
        +    with pytest.raises(NotImplementedError, match=message):
        +        db.get_function("normalize_score")
             with pytest.raises(NotImplementedError, match=message):
                 list(db.list_functions())
             with pytest.raises(NotImplementedError, match=message):
                 db.drop_function("normalize_score", version=FUNCTION_VERSION)
         
         
        +class _RawFunctionCatalog:
        +    def __init__(self, definition, *, encode=False):
        +        self.definition = json.dumps(definition) if encode else definition
        +        self.requested_versions = []
        +
        +    async def get_function(self, _name, version=None, namespace_path=None):
        +        self.requested_versions.append(version)
        +        return self.definition
        +
        +    def list_functions(self, *, namespace_path=None, page_token=None, page_limit=None):
        +        return self
        +
        +    def __aiter__(self):
        +        return self
        +
        +    async def __anext__(self):
        +        if self.definition is None:
        +            raise StopAsyncIteration
        +        definition, self.definition = self.definition, None
        +        return definition
        +
        +    def num_page_results(self):
        +        return int(self.definition is not None)
        +
        +    def page_token(self):
        +        return None
        +
        +
        +def test_function_version_reads_requested_and_resolved_environments():
        +    legacy = json.loads(
        +        (FIXTURES / "remote_function_version.canonical.json").read_text()
        +    )
        +    legacy_version = FunctionVersion.from_json(json.dumps(legacy))
        +    assert legacy_version.runtime is None
        +    assert legacy_version.resolved_environment is None
        +    assert legacy_version.environment.requested is None
        +    assert legacy_version.environment.resolved is None
        +
        +    payload = _function_version_with_resolved_environment()
        +    version = FunctionVersion.from_json(json.dumps(payload))
        +    assert version.environment.requested is version.runtime
        +    assert version.environment.resolved is version.resolved_environment
        +    assert version.runtime.kind == "python"
        +    resolved = version.resolved_environment
        +    assert resolved.packages[0].version == "2.9.0+cu130"
        +    assert resolved.packages[0].source == "https://packages.example/simple"
        +    assert resolved.packages[1].source is None
        +    assert resolved.provenance.torch_version == "torch==2.9.0+cu130"
        +    assert resolved.warnings == tuple(payload["resolved_environment"]["warnings"])
        +
        +    encoded = json.loads(version.to_canonical_json())
        +    assert encoded["runtime"]["kind"] == "python"
        +    assert encoded["resolved_environment"]["packages"][0]["version"] == "2.9.0+cu130"
        +    assert "source" not in encoded["resolved_environment"]["packages"][1]
        +    assert (
        +        encoded["resolved_environment"]["provenance"]["torch_version"]
        +        == "torch==2.9.0+cu130"
        +    )
        +    assert FunctionVersion.from_json(version.to_canonical_json()) == version
        +
        +    invalid = json.loads(json.dumps(payload))
        +    del invalid["resolved_environment"]["packages"]
        +    with pytest.raises(ValueError):
        +        FunctionVersion.from_json(json.dumps(invalid))
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "build",
        +    [
        +        {},
        +        {"build": None},
        +        {"build": {}},
        +        {"build": {"index_url": None}},
        +        {"build": {"index_url": 1}},
        +        {"build": "invalid-build"},
        +        {
        +            "build": {
        +                "index_url": "https://requested.example/simple/",
        +                "find_links": ["https://downloads.example/wheels"],
        +            },
        +        },
        +    ],
        +)
        +async def test_get_pinned_function_preserves_only_the_requested_index_url(build):
        +    payload = _function_version_with_resolved_environment()
        +    payload["runtime"]["environment"].update(build)
        +    catalog = _RawFunctionCatalog(payload, encode=True)
        +    connection = AsyncConnection(catalog)
        +
        +    version = await connection.get_function(payload["name"], version=1)
        +
        +    assert catalog.requested_versions == ["1"]
        +    assert version.version == "1"
        +    requested = version.runtime.environment.build
        +    raw_build = build.get("build")
        +    index_url = raw_build.get("index_url") if isinstance(raw_build, dict) else None
        +    canonical = version.to_canonical_json()
        +    encoded = json.loads(canonical)["runtime"]["environment"]
        +    if not isinstance(index_url, str):
        +        assert requested is None
        +        assert "build" not in encoded
        +    else:
        +        assert isinstance(requested, PythonEnvironmentBuild)
        +        assert requested.index_url == index_url
        +        assert encoded["build"] == {"index_url": index_url}
        +    assert version.resolved_environment.provenance.configured_index_urls == (
        +        "https://packages.example/simple",
        +    )
        +    assert FunctionVersion.from_json(canonical) == version
        +
        +
        +def test_function_version_reads_resolved_environments_by_platform():
        +    legacy = json.loads(
        +        (FIXTURES / "remote_function_version.canonical.json").read_text()
        +    )
        +    legacy_version = FunctionVersion.from_json(json.dumps(legacy))
        +    assert legacy_version.resolved_environment is None
        +    assert legacy_version.resolved_environments == {}
        +    assert legacy_version.environment_report == {}
        +
        +    payload = _function_version_with_resolved_environments()
        +    version = FunctionVersion.from_json(json.dumps(payload))
        +    assert version.resolved_environment is None
        +    assert version.resolved_environments == version.environment_report
        +    assert set(version.environment_report) == {"linux/amd64", "linux/arm64"}
        +    assert (
        +        version.environment_report["linux/amd64"].packages[0].version == "2.9.0+cu130"
        +    )
        +    assert version.environment_report["linux/arm64"].packages == ()
        +    assert version.environment_report["linux/arm64"].warnings == (
        +        "arm64 environment warning",
        +    )
        +
        +    encoded = json.loads(version.to_canonical_json())
        +    assert "resolved_environment" not in encoded
        +    assert (
        +        encoded["resolved_environments"]["linux/amd64"]["packages"][0]["version"]
        +        == "2.9.0+cu130"
        +    )
        +    assert encoded["resolved_environments"]["linux/arm64"]["packages"] == []
        +    assert FunctionVersion.from_json(version.to_canonical_json()) == version
        +
        +    missing_platform = json.loads(json.dumps(payload))
        +    del missing_platform["resolved_environments"]["linux/arm64"]
        +    missing_version = FunctionVersion.from_json(json.dumps(missing_platform))
        +    assert "linux/arm64" not in missing_version.environment_report
        +    assert "linux/amd64" in missing_version.environment_report
        +
        +    empty_map = json.loads(json.dumps(payload))
        +    empty_map["resolved_environments"] = {}
        +    empty_version = FunctionVersion.from_json(json.dumps(empty_map))
        +    assert empty_version.resolved_environments == {}
        +    assert "resolved_environments" not in json.loads(empty_version.to_canonical_json())
        +
        +    invalid = json.loads(json.dumps(payload))
        +    del invalid["resolved_environments"]["linux/amd64"]["packages"]
        +    with pytest.raises(ValueError):
        +        FunctionVersion.from_json(json.dumps(invalid))
        +
        +
        +@pytest.mark.asyncio
        +async def test_registration_job_emits_server_environment_warnings_once():
        +    payload = _function_version_with_resolved_environment()
        +
        +    class InnerJob:
        +        async def wait(self):
        +            return json.dumps(payload)
        +
        +    class Inner:
        +        async def create_function_async(
        +            self, request_json, namespace_path=None, *, exist_ok=False
        +        ):
        +            assert "refresh_lock" not in json.loads(request_json)
        +            return InnerJob()
        +
        +    connection = object.__new__(AsyncConnection)
        +    connection._inner = Inner()
        +    job = await connection.create_function_async(normalize_score)
        +    with pytest.warns(UserWarning) as recorded:
        +        version = await job.wait()
        +    assert [str(w.message) for w in recorded] == list(
        +        payload["resolved_environment"]["warnings"]
        +    )
        +    assert version.environment.resolved.warnings == tuple(
        +        payload["resolved_environment"]["warnings"]
        +    )
        +    with warnings.catch_warnings(record=True) as caught:
        +        warnings.simplefilter("always")
        +        assert await job.wait() is not None
        +    assert caught == []
        +
        +
        +@pytest.mark.asyncio
        +async def test_registration_job_emits_per_platform_environment_warnings():
        +    payload = _function_version_with_resolved_environments()
        +
        +    class InnerJob:
        +        async def wait(self):
        +            return json.dumps(payload)
        +
        +    class Inner:
        +        async def create_function_async(
        +            self, request_json, namespace_path=None, *, exist_ok=False
        +        ):
        +            return InnerJob()
        +
        +    connection = object.__new__(AsyncConnection)
        +    connection._inner = Inner()
        +    job = await connection.create_function_async(normalize_score)
        +    with pytest.warns(UserWarning) as recorded:
        +        version = await job.wait()
        +    assert [str(w.message) for w in recorded] == [
        +        "amd64 environment warning",
        +        "arm64 environment warning",
        +    ]
        +    assert version.environment_report["linux/arm64"].warnings == (
        +        "arm64 environment warning",
        +    )
        +    with warnings.catch_warnings(record=True) as caught:
        +        warnings.simplefilter("always")
        +        assert await job.wait() is not None
        +    assert caught == []
        +
        +
        +def test_blocking_create_function_emits_server_environment_warnings():
        +    payload = _function_version_with_resolved_environment()
        +
        +    class InnerJob:
        +        async def wait(self):
        +            return json.dumps(payload)
        +
        +    class Inner:
        +        async def create_function_async(
        +            self, request_json, namespace_path=None, *, exist_ok=False
        +        ):
        +            return InnerJob()
        +
        +    connection = object.__new__(RemoteDBConnection)
        +    connection._conn = AsyncConnection(Inner())
        +    with pytest.warns(UserWarning) as recorded:
        +        version = DBConnection.create_function(connection, normalize_score)
        +    assert [str(w.message) for w in recorded] == list(
        +        payload["resolved_environment"]["warnings"]
        +    )
        +    assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
        +
        +
        +@pytest.mark.asyncio
        +async def test_catalog_readback_does_not_replay_registration_warnings():
        +    payload = _function_version_with_resolved_environment()
        +    connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
        +    with warnings.catch_warnings(record=True) as caught:
        +        warnings.simplefilter("always")
        +        version = await connection.get_function("embed")
        +        listed = [item async for item in connection.list_functions()]
        +    assert caught == []
        +    assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
        +    assert listed[0].environment.resolved == version.resolved_environment
        +
        +
        +@pytest.mark.asyncio
        +async def test_catalog_readback_does_not_replay_per_platform_warnings():
        +    payload = _function_version_with_resolved_environments()
        +    connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
        +    with warnings.catch_warnings(record=True) as caught:
        +        warnings.simplefilter("always")
        +        version = await connection.get_function("embed")
        +        listed = [item async for item in connection.list_functions()]
        +    assert caught == []
        +    assert version.environment_report == listed[0].environment_report
        +
        +
        +def _assert_execution_control_encoding(version):
        +    encoded = json.loads(version.to_canonical_json())
        +    assert type(encoded["batch_size"]) is int
        +    assert type(encoded["row_timeout_seconds"]) is float
        +    assert type(encoded["result_stability"]) is str
        +    return encoded
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_catalog_path_preserves_execution_controls():
        +    definition = json.loads(
        +        (FIXTURES / "remote_function_version.canonical.json").read_text()
        +    )
        +    definition.update(
        +        runtime_digest=normalize_score.registration_request.runtime.digest,
        +        batch_size=12,
        +        row_timeout_seconds=8.0,
        +        result_stability="input_and_context",
        +    )
        +    catalog = _RawFunctionCatalog(definition, encode=True)
        +    connection = AsyncConnection(catalog)
        +
        +    latest = await connection.get_function("embed")
        +    integer = await connection.get_function("embed", version=1)
        +    exact = await connection.get_function("embed", version="1")
        +    await connection.get_function("embed", version="001")
        +    listed = [item async for item in connection.list_functions(page_limit=32)]
        +    assert len(listed) == 1
        +    for version in [latest, integer, exact, *listed]:
        +        assert _assert_execution_control_encoding(version) == definition
        +    assert catalog.requested_versions == [None, "1", "1", "001"]
        +    with pytest.raises(TypeError, match="int, str, or None"):
        +        await connection.get_function("embed", version=True)
        +    with pytest.raises(TypeError, match="int, str, or None"):
        +        await connection.get_function("embed", version=1.5)
        +
        +
        +def test_sync_catalog_path_preserves_execution_controls():
        +    definition = json.loads(
        +        (FIXTURES / "remote_function_version.canonical.json").read_text()
        +    )
        +    definition.update(
        +        runtime_digest=normalize_score.registration_request.runtime.digest,
        +        batch_size=12,
        +        row_timeout_seconds=8.0,
        +        result_stability="input_and_context",
        +    )
        +    connection = object.__new__(RemoteDBConnection)
        +    catalog = _RawFunctionCatalog(FunctionVersion(**definition))
        +    connection._conn = catalog
        +
        +    latest = connection.get_function("embed")
        +    integer = connection.get_function("embed", version=1)
        +    exact = connection.get_function("embed", version="1")
        +    connection.get_function("embed", version="001")
        +    listed = list(connection.list_functions(page_limit=32))
        +    assert len(listed) == 1
        +    for version in [latest, integer, exact, *listed]:
        +        assert _assert_execution_control_encoding(version) == definition
        +    assert catalog.requested_versions == [None, "1", "1", "001"]
        +    with pytest.raises(TypeError, match="int, str, or None"):
        +        connection.get_function("embed", version=True)
        +    with pytest.raises(TypeError, match="int, str, or None"):
        +        connection.get_function("embed", version=1.5)
        +
        +
        +def test_sync_drop_function_emits_server_warnings_without_changing_bool_api():
        +    class _DropConnection:
        +        async def drop_function(self, name, *, version, namespace_path=None):
        +            return True
        +
        +        async def _drop_function_with_warnings(
        +            self, name, *, version, namespace_path=None
        +        ):
        +            return True, [
        +                'materialized view "pinned" references Function "embed" version "1"'
        +            ]
        +
        +    connection = object.__new__(RemoteDBConnection)
        +    connection._conn = _DropConnection()
        +
        +    with pytest.warns(UserWarning, match="references Function"):
        +        assert connection.drop_function("embed", version="1") is True
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_drop_function_emits_server_warnings_without_changing_bool_api():
        +    class _Inner:
        +        async def _drop_function_with_warnings(
        +            self, name, version, namespace_path=None
        +        ):
        +            return True, [
        +                'materialized view "pinned" references Function "embed" version "1"'
        +            ]
        +
        +        async def drop_function(self, name, version, namespace_path=None):
        +            return True
        +
        +    connection = object.__new__(AsyncConnection)
        +    connection._inner = _Inner()
        +
        +    with pytest.warns(UserWarning, match="references Function"):
        +        assert await connection.drop_function("embed", version="1") is True
        +
        +
         @contextlib.contextmanager
         def _mock_remote_function_catalog():
             state = {"requests": [], "version": None}
        @@ -1916,6 +3004,9 @@ def _mock_remote_function_catalog():
                             )["image"],
                             "signature": body["signature"],
                             "source_digest": body["artifact"]["digest"],
        +                    "runtime_digest": PythonRuntimeSpec.from_json(
        +                        json.dumps(body["runtime"])
        +                    ).digest,
                             "secret_bindings": body.get("secret_bindings", []),
                             "created_at_millis": 1787270400000,  # 2026-08-21T00:00:00Z
                         }
        @@ -2018,8 +3109,8 @@ def test_building_a_binding_contacts_no_server():
             assert state["requests"] == []
         
         
        -def test_vectorized_blob_udf_executes_packaged_artifact_and_publishes(tmp_path):
        -    @udf(
        +def test_vectorized_blob_function_executes_packaged_artifact_and_publishes(tmp_path):
        +    @function(
                 input_schema=pa.schema([lancedb.blob("image", nullable=True)]),
                 output_schema=lancedb.blob("copy", nullable=False),
             )
        @@ -2060,7 +3151,7 @@ def test_vectorized_blob_udf_executes_packaged_artifact_and_publishes(tmp_path):
             )
             hydrated = source.fetch_blobs("image", input_hits)
             assert isinstance(hydrated, pa.LargeBinaryArray)
        -    result = _execute_registered_array_udf_v1(
        +    result = _execute_registered_array_function_v1(
                 registration,
                 pa.RecordBatch.from_arrays([hydrated], names=["image"]),
             )
        @@ -2106,7 +3197,7 @@ def test_blob_list_output_fresh_artifact_survives_local_reopen(
             input_type = physical_list(pa.int64())
             item = lancedb.blob("item", nullable=True)
         
        -    @udf(
        +    @function(
                 input_schema=pa.schema([pa.field("frames", input_type, nullable=False)]),
                 output_schema=pa.field("frames", declared_list(item), nullable=False),
             )
        @@ -2124,7 +3215,7 @@ def test_blob_list_output_fresh_artifact_survives_local_reopen(
             item_field = declared["fields"][0]
             assert item_field["metadata"]["ARROW:extension:name"] == "lance.blob.v2"
         
        -    result = _execute_registered_array_udf_v1(
        +    result = _execute_registered_array_function_v1(
                 request,
                 pa.RecordBatch.from_arrays(
                     [pa.array([[0], [1]], type=input_type)],
        @@ -2189,11 +3280,11 @@ def test_a_function_namespace_path_must_be_a_list_of_segments():
         
         
         def test_one_explicit_schema_infers_the_other_from_annotations():
        -    @udf(input_schema=pa.schema([pa.field("value", pa.int64())]))
        +    @function(input_schema=pa.schema([pa.field("value", pa.int64())]))
             def explicit_input(value) -> float:
                 return float(value or 0)
         
        -    @udf(output_schema=pa.field("result", pa.float32(), nullable=False))
        +    @function(output_schema=pa.field("result", pa.float32(), nullable=False))
             def explicit_output(value: Optional[int]):
                 return float(value or 0)
         
        diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py
        index f2fcc970b..1bf019fc2 100644
        --- a/python/python/tests/test_fts.py
        +++ b/python/python/tests/test_fts.py
        @@ -29,6 +29,7 @@ from lancedb.query import (
             CombinedFieldsQuery,
             DocumentGranularity,
             FullTextOperator,
        +    FullTextSearchQuery,
             MatchQuery,
             MultiMatchQuery,
             PhraseQuery,
        @@ -530,11 +531,9 @@ async def test_fts_select_async(async_table):
         
         def test_search_fts_phrase_query(table):
             table.create_fts_index("text", with_position=False)
        -    try:
        -        phrase_results = table.search('"puppy runs"').limit(100).to_list()
        -        assert False
        -    except Exception:
        -        pass
        +    with pytest.raises(Exception) as error:
        +        table.search('"puppy runs"').limit(100).to_list()
        +    assert "FTS(with_position=True)" in exception_output(error)
             table.create_fts_index("text", with_position=True, replace=True)
             results = table.search("puppy").limit(100).to_list()
         
        @@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table):
         @pytest.mark.asyncio
         async def test_search_fts_phrase_query_async(async_table):
             await async_table.create_index("text", config=FTS(with_position=False))
        -    try:
        -        phrase_results = (
        -            await async_table.query().nearest_to_text("puppy runs").limit(100).to_list()
        -        )
        -        assert False
        -    except Exception:
        -        pass
        +    with pytest.raises(Exception) as error:
        +        await async_table.query().nearest_to_text('"puppy runs"').to_list()
        +    assert "FTS(with_position=True)" in exception_output(error)
             await async_table.create_index("text", config=FTS(with_position=True))
             results = await async_table.query().nearest_to_text("puppy").limit(100).to_list()
             phrase_results = (
        @@ -1660,7 +1655,9 @@ def test_fts_phrase_query_is_preserved_in_query_object():
         def test_fts_phrase_query_execution_preserves_user_text():
             table = mock.Mock()
             table.schema = pa.schema([])
        -    table._execute_query.return_value = pa.table({"text": ["result"]}).to_reader()
        +    # to_arrow() collects through the eager path; keep a real Table so the
        +    # reranker still receives and returns the real result contract.
        +    table._execute_arrow.return_value = pa.table({"text": ["result"]})
         
             class CapturingReranker:
                 score = "relevance"
        @@ -1682,7 +1679,7 @@ def test_fts_phrase_query_execution_preserves_user_text():
         
             query.to_arrow()
         
        -    backend_query = table._execute_query.call_args.args[0]
        +    backend_query = table._execute_arrow.call_args.args[0]
             assert (
                 backend_query.full_text_query.query,
                 reranker.queries,
        @@ -1948,3 +1945,168 @@ async def test_async_fts_code_analyzer(mem_db_async):
         
             rows = await table.query().nearest_to_text("http").to_list()
             assert len(rows) == 1
        +
        +
        +@pytest.mark.parametrize("indexed", [False, True])
        +@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
        +def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected):
        +    db = ldb.connect(tmp_path)
        +    table = db.create_table(
        +        "matches",
        +        pa.table(
        +            {
        +                "id": list(range(30)),
        +                "text": ["gripper closed"] * 15
        +                + ["gripper open"] * 10
        +                + ["camera ready"] * 5,
        +            }
        +        ),
        +    )
        +    if indexed:
        +        table.create_index("text", config=FTS())
        +    kwargs = {"fts_columns": "text"}
        +    if operator is not None:
        +        kwargs["operator"] = operator
        +    query = table.search("gripper closed", query_type="fts", **kwargs)
        +    assert query.count_rows() == expected
        +    assert len(query.limit(100).to_list()) == expected
        +    assert (
        +        table.search("gripper closed", query_type="fts", fts_columns="text")
        +        .operator("AND")
        +        .count_rows()
        +        == 15
        +    )
        +    if operator is not None:
        +        assert query.to_query_object().full_text_query.operator == operator
        +    query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1)
        +    before = query.to_query_object()
        +    assert query.count_rows() == expected - 5
        +    assert query.to_query_object() == before
        +    assert len(query.to_list()) <= 2
        +    assert (
        +        table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0
        +    )
        +    assert (
        +        table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows()
        +        == 15
        +    )
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("indexed", [False, True])
        +@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
        +async def test_simple_fts_operator_and_count_async(
        +    tmp_path, indexed, operator, expected
        +):
        +    db = await ldb.connect_async(tmp_path)
        +    table = await db.create_table(
        +        "matches",
        +        pa.table(
        +            {
        +                "id": list(range(30)),
        +                "text": ["gripper closed"] * 15
        +                + ["gripper open"] * 10
        +                + ["camera ready"] * 5,
        +            }
        +        ),
        +    )
        +    if indexed:
        +        await table.create_index("text", config=FTS())
        +    query = await table.search(
        +        "gripper closed", query_type="fts", fts_columns="text", operator=operator
        +    )
        +    assert await query.count_rows() == expected
        +    assert len(await query.limit(100).to_list()) == expected
        +    query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1)
        +    before = query.to_query_object()
        +    assert await query.count_rows() == expected - 5
        +    assert query.to_query_object() == before
        +    direct = table.query().nearest_to_text(
        +        "gripper closed", columns="text", operator="AND"
        +    )
        +    assert await direct.count_rows() == 15
        +    assert direct.to_query_object().full_text_query.query.operator == "AND"
        +    assert (
        +        await table.query().nearest_to_text("absent", columns="text").count_rows() == 0
        +    )
        +
        +
        +@pytest.mark.parametrize("with_position", [False, True])
        +@pytest.mark.parametrize(
        +    "query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
        +)
        +def test_fts_phrase_count_positions(tmp_path, with_position, query):
        +    table = ldb.connect(tmp_path).create_table(
        +        "phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
        +    )
        +    table.create_index("text", config=FTS(with_position=with_position))
        +    search = table.search(query, query_type="fts")
        +    if with_position:
        +        assert search.count_rows() == 1
        +        assert len(search.to_list()) == 1
        +        assert (
        +            table.search("gripper closed", query_type="fts", operator="AND")
        +            .phrase_query()
        +            .count_rows()
        +            == 1
        +        )
        +    else:
        +        with pytest.raises(Exception) as error:
        +            search.count_rows()
        +        assert "FTS(with_position=True)" in exception_output(error)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("with_position", [False, True])
        +@pytest.mark.parametrize(
        +    "query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
        +)
        +async def test_fts_phrase_count_positions_async(tmp_path, with_position, query):
        +    db = await ldb.connect_async(tmp_path)
        +    table = await db.create_table(
        +        "phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
        +    )
        +    await table.create_index("text", config=FTS(with_position=with_position))
        +    search = table.query().nearest_to_text(query)
        +    if with_position:
        +        assert await search.count_rows() == 1
        +        assert len(await search.to_list()) == 1
        +    else:
        +        with pytest.raises(Exception) as error:
        +            await search.count_rows()
        +        assert "FTS(with_position=True)" in exception_output(error)
        +
        +
        +def test_fts_operator_rejects_invalid_queries(table):
        +    with pytest.raises(ValueError):
        +        table.search("gripper", query_type="fts", operator="XOR")
        +    for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
        +        with pytest.raises(
        +            ValueError, match="operator requires a string full-text query"
        +        ):
        +            table.search(query, operator="AND")
        +    with pytest.raises(ValueError, match="operator requires a string full-text query"):
        +        FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND")
        +
        +
        +@pytest.mark.asyncio
        +async def test_fts_operator_rejects_invalid_queries_async(async_table):
        +    with pytest.raises(ValueError):
        +        await async_table.search("gripper", query_type="fts", operator="XOR")
        +    for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
        +        with pytest.raises(
        +            ValueError, match="operator requires a string full-text query"
        +        ):
        +            await async_table.search(query, operator="AND")
        +        with pytest.raises(ValueError):
        +            async_table.query().nearest_to_text(query, operator="AND")
        +
        +
        +def test_fts_count_fast_search(tmp_path):
        +    table = ldb.connect(tmp_path).create_table(
        +        "matches", pa.table({"text": ["gripper closed"] * 15})
        +    )
        +    table.create_index("text", config=FTS())
        +    table.add(pa.table({"text": ["gripper closed"] * 5}))
        +    assert table.search("gripper", query_type="fts").count_rows() == 20
        +    assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
        diff --git a/python/python/tests/test_function_creation.py b/python/python/tests/test_function_creation.py
        new file mode 100644
        index 000000000..ae5a2bf8b
        --- /dev/null
        +++ b/python/python/tests/test_function_creation.py
        @@ -0,0 +1,253 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import json
        +from pathlib import Path
        +
        +import pyarrow as pa
        +import pytest
        +
        +import lancedb
        +from lancedb.functions import (
        +    BlobWriter,
        +    FunctionDefinition,
        +    FunctionRegistrationRequest,
        +    FunctionVersion,
        +    function,
        +)
        +
        +
        +def _stored_function_version():
        +    fixture = (
        +        Path(__file__).parents[3]
        +        / "rust/lancedb/tests/fixtures/first_class_functions/v1"
        +        / "remote_function_version.canonical.json"
        +    )
        +    return json.loads(fixture.read_text())
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"])
        +@pytest.mark.parametrize("exist_ok", [None, False, True])
        +async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    stored = _stored_function_version()
        +    result = pa.table({"definition": [json.dumps(stored)]})
        +
        +    @function(name=stored["name"])
        +    def replacement(value: float) -> float:
        +        return value * 2
        +
        +    class FunctionServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.requests = []
        +
        +        def do_get(self, context, ticket):
        +            self.requests.append(ticket.ticket)
        +            return flight.RecordBatchStream(result)
        +
        +    with FunctionServer() as server:
        +        options = {
        +            "api_key": "test-key",
        +            "host_override": "http://localhost:10024",
        +            "sql_host_override": f"grpc://127.0.0.1:{server.port}",
        +        }
        +        kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
        +        kwargs["namespace_path"] = ["team"]
        +        if entry == "async_job":
        +            db = await lancedb.connect_async("db://analytics", **options)
        +            job = await db.create_function_async(replacement, **kwargs)
        +            version = await job.wait()
        +        else:
        +            db = lancedb.connect("db://analytics", **options)
        +            if entry == "sync_job":
        +                version = db.create_function_async(replacement, **kwargs).wait()
        +            else:
        +                version = db.create_function(replacement, **kwargs)
        +        (request,) = server.requests
        +
        +    prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION"
        +    assert f'{prefix} "{stored["name"]}" FROM '.encode() in request
        +    assert b'"exist_ok"' not in request
        +    assert json.loads(version.to_canonical_json()) == stored
        +
        +
        +@pytest.mark.asyncio
        +async def test_blob_writer_paths_round_trip_through_function_registration():
        +    flight = pytest.importorskip("pyarrow.flight")
        +    stored = _stored_function_version()
        +    expected_paths = [[{"field": "item"}], [{"field": "variants"}, "item"]]
        +    output_schema = pa.schema(
        +        [
        +            BlobWriter.field("item"),
        +            pa.field("variants", pa.list_(BlobWriter.field("asset"))),
        +            pa.field("checksum", pa.binary(), nullable=False),
        +        ]
        +    )
        +
        +    @function(name=stored["name"], output_schema=output_schema)
        +    def render(text: str):
        +        with BlobWriter.open() as output:
        +            output.write(text.encode())
        +        return {"item": output, "variants": [b"", None], "checksum": b""}
        +
        +    expected_output = json.loads(
        +        render.registration_request.signature.output.to_canonical_json()
        +    )
        +    assert expected_output["kind"] == "named_struct_blob_writer"
        +    assert expected_output["blob_writer_paths"] == expected_paths
        +    stored["signature"] = {
        +        "inputs": [{"name": "text", "arrow_type": "utf8", "nullable": False}],
        +        "output": expected_output,
        +    }
        +
        +    class FunctionServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.requests = []
        +
        +        def do_get(self, context, ticket):
        +            self.requests.append(ticket.ticket)
        +            return flight.RecordBatchStream(
        +                pa.table({"definition": [json.dumps(stored)]})
        +            )
        +
        +    with FunctionServer() as server:
        +        db = await lancedb.connect_async(
        +            "db://analytics",
        +            api_key="test-key",
        +            host_override="http://localhost:10024",
        +            sql_host_override=f"grpc://127.0.0.1:{server.port}",
        +        )
        +        job = await db.create_function_async(render)
        +        version = await job.wait()
        +        (request,) = server.requests
        +
        +    assert b"CREATE FUNCTION" in request
        +    _, marker, body = request.partition(b" FROM '{")
        +    assert marker
        +    submitted, _ = json.JSONDecoder().raw_decode("{" + body.decode(errors="replace"))
        +    assert submitted["signature"]["output"] == expected_output
        +    assert (
        +        json.loads(version.to_canonical_json())["signature"]["output"]
        +        == expected_output
        +    )
        +    application = version(text=lancedb.col("text")).rename(columns={"item": "payload"})
        +    assert json.loads(application.to_canonical_json())["output"] == expected_output
        +    assert application.columns == {"item": "payload"}
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("with_primary", [False, True])
        +async def test_function_index_inspection_is_separate_from_registration(with_primary):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    primary = "https://primary.example/simple/"
        +    extra = "https://extra.example/simple/"
        +    stored = _stored_function_version()
        +    name = stored["name"]
        +
        +    def scale(value: float) -> float:
        +        return 2 * value
        +
        +    authored = function(name=name, pip=["example==1.0"], python_version="3.12")(scale)
        +    request = authored.registration_request
        +    expected_runtime = {
        +        "kind": "python",
        +        "python_version": "3.12",
        +        "environment": {"kind": "pip", "packages": ["example==1.0"]},
        +    }
        +    stored["runtime"] = json.loads(request.runtime.to_canonical_json())
        +    build = {"extra_index_urls": [extra]}
        +    if with_primary:
        +        build["index_url"] = primary
        +    stored["runtime"]["environment"]["build"] = build
        +    stored["runtime_digest"] = "sha256:" + "1" * 64
        +    stored["resolved_environment"] = {
        +        "packages": [],
        +        "provenance": {"configured_index_urls": [extra]},
        +    }
        +
        +    class FunctionServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.requests = []
        +
        +        def do_get(self, context, ticket):
        +            self.requests.append(ticket.ticket)
        +            if b"DESCRIBE FUNCTION" in ticket.ticket:
        +                assert b"FORMAT JSON" in ticket.ticket
        +                return flight.RecordBatchStream(
        +                    pa.table(
        +                        {"description": [json.dumps(stored)]}
        +                    ).replace_schema_metadata({b"lancedb.describe.format": b"json"})
        +                )
        +            return flight.RecordBatchStream(
        +                pa.table({"definition": [json.dumps(stored)]})
        +            )
        +
        +    class IndexedDefinition(FunctionDefinition):
        +        def bind_secrets(self, secrets):
        +            payload = json.loads(super().bind_secrets(secrets).to_canonical_json())
        +            payload["runtime"]["environment"]["build"] = build
        +            return FunctionRegistrationRequest.from_json(json.dumps(payload))
        +
        +    definition = IndexedDefinition(
        +        scale,
        +        name=name,
        +        input_schema=None,
        +        output_schema=None,
        +        pip=("example==1.0",),
        +        env={},
        +        python_version="3.12",
        +    )
        +
        +    with FunctionServer() as server:
        +        options = {
        +            "api_key": "test-key",
        +            "host_override": "http://127.0.0.1:1",
        +            "sql_host_override": f"grpc://127.0.0.1:{server.port}",
        +        }
        +        db = lancedb.connect("db://analytics", **options)
        +        async_db = await lancedb.connect_async("db://analytics", **options)
        +
        +        message = r"runtime\.environment\.build is unsupported"
        +        with pytest.raises(TypeError, match=message):
        +            db.create_function(definition)
        +        with pytest.raises(TypeError, match=message):
        +            await async_db.create_function_async(definition)
        +        assert server.requests == []
        +
        +        version = db.get_function(name, version=1)
        +        assert await async_db.get_function(name, version="1") == version
        +        assert all(
        +            f"DESCRIBE FUNCTION \"{name}\" WITH (version = '1') FORMAT JSON".encode()
        +            in ticket
        +            for ticket in server.requests
        +        )
        +        assert len(server.requests) == 2
        +        assert version.runtime_digest == stored["runtime_digest"]
        +        assert version.resolved_environment.provenance.configured_index_urls == (extra,)
        +        canonical = version.to_canonical_json()
        +        encoded = json.loads(canonical)
        +        assert FunctionVersion.from_json(canonical) == version
        +        if with_primary:
        +            assert version.runtime.environment.build.index_url == primary
        +            assert encoded["runtime"]["environment"]["build"] == {"index_url": primary}
        +        else:
        +            assert version.runtime.environment.build is None
        +            assert "build" not in encoded["runtime"]["environment"]
        +        with pytest.raises(TypeError, match="runtime metadata is for inspection only"):
        +            FunctionRegistrationRequest.model_validate(
        +                {**request.model_dump(), "runtime": version.runtime}
        +            )
        +        with pytest.raises(TypeError, match="runtime metadata is for inspection only"):
        +            request.model_copy(update={"runtime": version.runtime}).to_canonical_json()
        +
        +        job = await async_db.create_function_async(authored, refresh_lock=True)
        +        assert await job.wait() == version
        +        _, marker, body = server.requests[-1].partition(b" FROM '{")
        +        assert marker
        +        sent, _ = json.JSONDecoder().raw_decode("{" + body.decode(errors="replace"))
        +        assert sent["refresh_lock"] is True
        +        assert sent["runtime"] == expected_runtime
        diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py
        index f97be9d89..fdfbbeab4 100644
        --- a/python/python/tests/test_function_packaging.py
        +++ b/python/python/tests/test_function_packaging.py
        @@ -7,7 +7,9 @@ from __future__ import annotations
         
         import base64
         import importlib
        +import hashlib
         import json
        +import os
         import subprocess
         import sys
         import textwrap
        @@ -16,11 +18,19 @@ import warnings
         from pathlib import Path
         from typing import Annotated, Optional, get_type_hints
         
        +import numpy as np
         import pyarrow as pa
        +import pyarrow.compute as pc
         import pytest
         
        -from lancedb import col
        -from lancedb.functions import FunctionVersion, udf
        +from lancedb import blob, col
        +from lancedb.functions import (
        +    BlobWriter,
        +    FunctionDefinition,
        +    FunctionVersion,
        +    function,
        +    udf,
        +)
         
         FIXTURES = (
             Path(__file__).parents[3]
        @@ -63,7 +73,7 @@ def helper_package(tmp_path, monkeypatch):
             return write
         
         
        -@udf
        +@function
         class scale:
             def __init__(
                 self,
        @@ -114,11 +124,11 @@ def test_class_function_declares_inputs_output_and_initialization():
             assert scale.registration_request.artifact.entrypoint == "scale"
             source = artifact(scale).decode()
             assert source.startswith("from __future__ import annotations\n")
        -    assert "class scale:" in source and "@udf" not in source
        +    assert "class scale:" in source and "@function" not in source
         
         
         def test_function_without_initialization_keeps_its_wire_form():
        -    @udf
        +    @function
             def double(value: int) -> int:
                 return value * 2
         
        @@ -127,6 +137,417 @@ def test_function_without_initialization_keeps_its_wire_form():
             assert request["artifact"]["kind"] == "python_callable"
         
         
        +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
        +@pytest.mark.parametrize("decorator", [function, udf])
        +@pytest.mark.parametrize("explicit_schemas", [False, True])
        +@pytest.mark.parametrize("class_function", [False, True])
        +@pytest.mark.parametrize(
        +    ("declaration", "statement"),
        +    [
        +        ("def", "yield value"),
        +        ("def", "yield from [value]"),
        +        ("async def", "yield value"),
        +    ],
        +)
        +def test_generator_functions_are_rejected_at_decoration(
        +    helper_package, decorator, explicit_schemas, class_function, declaration, statement
        +):
        +    signature = (
        +        "__call__(self, value: int)" if class_function else "generates(value: int)"
        +    )
        +    source = f"{declaration} {signature} -> int:\n    {statement}\n"
        +    if class_function:
        +        source = "class generates:\n" + textwrap.indent(source, "    ")
        +    module = helper_package("fx_generator", {"__init__.py": source})
        +    options = (
        +        {
        +            "input_schema": pa.schema([pa.field("value", pa.int64(), nullable=False)]),
        +            "output_schema": pa.int64(),
        +        }
        +        if explicit_schemas
        +        else {}
        +    )
        +    with pytest.raises(TypeError) as error:
        +        decorator(**options)(module.generates)
        +    message = str(error.value)
        +    assert "generator Functions are not supported" in message
        +    assert "return a value" in message
        +    assert "return a list" in message
        +
        +
        +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
        +@pytest.mark.parametrize("decorator", [function, udf])
        +@pytest.mark.parametrize("explicit_name", [False, True])
        +def test_lambda_functions_explain_the_named_alternative(decorator, explicit_name):
        +    options = {"name": "double"} if explicit_name else {}
        +    with pytest.raises(TypeError, match="lambda.*use a named def"):
        +        decorator(**options)(lambda value: value * 2)
        +
        +
        +@pytest.mark.parametrize("class_function", [False, True])
        +@pytest.mark.parametrize("cache_decorator", ["lru_cache", "cache"])
        +def test_cached_functions_explain_where_to_keep_caches(
        +    helper_package, class_function, cache_decorator
        +):
        +    signature = "__call__(self, value: int)" if class_function else "cached(value: int)"
        +    source = (
        +        f"@functools.{cache_decorator}\ndef {signature} -> int:\n    return value * 2\n"
        +    )
        +    if class_function:
        +        source = "class cached:\n" + textwrap.indent(source, "    ")
        +    module = helper_package("fx_cached", {"__init__.py": "import functools\n" + source})
        +    with pytest.raises(TypeError) as error:
        +        function(module.cached)
        +    message = str(error.value)
        +    assert "decorated wrappers are not supported" in message
        +    assert "inside the function body" in message
        +    assert "class Function with a cache in __init__" in message
        +
        +
        +@pytest.mark.parametrize("class_function", [False, True])
        +@pytest.mark.parametrize("keyword_only", [False, True])
        +def test_callable_defaults_explain_class_initialization(
        +    helper_package, class_function, keyword_only
        +):
        +    parameters = "value: float, " + ("*, " if keyword_only else "")
        +    parameters += "threshold: float = 0.5"
        +    signature = (
        +        f"__call__(self, {parameters})"
        +        if class_function
        +        else f"thresholded({parameters})"
        +    )
        +    source = f"def {signature} -> bool:\n    return value >= threshold\n"
        +    if class_function:
        +        source = "class thresholded:\n" + textwrap.indent(source, "    ")
        +    module = helper_package("fx_defaults", {"__init__.py": source})
        +    with pytest.raises(TypeError) as error:
        +        function(module.thresholded)
        +    message = str(error.value)
        +    assert "defaults are not supported: 'threshold'" in message
        +    assert "class Function's __init__" in message
        +    assert "binding-time initialization values" in message
        +
        +
        +def test_function_can_return_a_list_from_a_generator_expression():
        +    @function
        +    def many(value: int) -> list[int]:
        +        return list(item * 2 for item in range(value))
        +
        +    namespace = {}
        +    exec(compile(artifact(many), "user_function.py", "exec"), namespace)
        +    assert namespace["many"](3) == [0, 2, 4]
        +    assert many.registration_request.signature.output.arrow_type == "list"
        +
        +
        +@pytest.mark.parametrize("kind", ["function", "class"])
        +@pytest.mark.parametrize(
        +    ("global_value", "value_type"),
        +    [
        +        ("float('inf')", "float"),
        +        ("{'label': float('nan')}", "float"),
        +        ("[1, (2, object())]", "object"),
        +        ("{'labels': range(2)}", "range"),
        +        ("pa.array([1])", "Int64Array"),
        +        ("np.array(['label'])", "ndarray with dtype  int:\n"
        +        "        return value if CAPTURED_VALUE else 0\n"
        +        if kind == "class"
        +        else "def uses_global(value: int) -> int:\n"
        +        "    return value if CAPTURED_VALUE else 0\n"
        +    )
        +    module = helper_package(
        +        "fx_unsupported_global",
        +        {
        +            "__init__.py": "import numpy as np\nimport pyarrow as pa\n"
        +            f"CAPTURED_VALUE = {global_value}\n" + definition
        +        },
        +    )
        +    with pytest.raises(TypeError) as error:
        +        function(module.uses_global)
        +    message = str(error.value)
        +    assert "CAPTURED_VALUE" in message
        +    assert value_type in message
        +    assert "finite float" in message
        +    assert "inside the function or class body" in message
        +
        +
        +def test_supported_nested_literal_global_still_packages(helper_package):
        +    module = helper_package(
        +        "fx_literal_global",
        +        {
        +            "__init__.py": "CAPTURED_VALUE = (None, True, 1, 'label', "
        +            "b'bytes', (1.5,))\n"
        +            "def uses_global(value: int) -> int:\n"
        +            "    return value + CAPTURED_VALUE[2]\n"
        +        },
        +    )
        +    definition = function(module.uses_global)
        +    namespace = {}
        +    exec(compile(artifact(definition), "user_function.py", "exec"), namespace)
        +    assert namespace["uses_global"](3) == 4
        +    assert namespace["CAPTURED_VALUE"] == module.CAPTURED_VALUE
        +
        +
        +@pytest.mark.parametrize("kind", ["function", "class"])
        +def test_arrow_and_structured_globals_are_captured(helper_package, kind):
        +    body = (
        +        "    if x is None:\n"
        +        "        return (LABELS, EMPTY, ARROW, WEIGHTS, NUMPY)\n"
        +        "    rows = [{'label': 'pick', 'score': LABELS['pick']}] * len(x)\n"
        +        "    return pa.array(rows, type=OUT_TYPE)\n"
        +    )
        +    definition = (
        +        "class judge:\n    def __call__(self, x: pa.Array) -> pa.Array:\n"
        +        + textwrap.indent(body, "    ")
        +        if kind == "class"
        +        else "def judge(x: pa.Array) -> pa.Array:\n" + body
        +    )
        +    module = helper_package(
        +        "fx_structured_global",
        +        {
        +            "__init__.py": textwrap.dedent("""
        +                import numpy as np
        +                import pyarrow as pa
        +
        +                OUT_TYPE = pa.struct(
        +                    [pa.field("label", pa.string()), pa.field("score", pa.int32())]
        +                )
        +                LABELS = {
        +                    "pick": 0,
        +                    "place": 1,
        +                    "nested": [None, (1.5, b"x"), {"deep": frozenset({"b", "a"})}],
        +                }
        +                EMPTY = ([], {}, set(), frozenset(), ())
        +                ARROW = {
        +                    "field": pa.field(
        +                        "score", pa.int32(), nullable=False, metadata={"unit": "pts"}
        +                    ),
        +                    "schema": pa.schema(
        +                        [pa.field("label", pa.dictionary(pa.int8(), pa.utf8(), True))],
        +                        metadata={"version": "1"},
        +                    ),
        +                    "tensor": pa.fixed_shape_tensor(pa.float32(), [2, 2]),
        +                }
        +                WEIGHTS = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=np.float32)
        +                NUMPY = (
        +                    np.float32(0.5),
        +                    np.True_,
        +                    np.uint64(2**64 - 1),
        +                    np.array(1.5),
        +                    np.zeros((0, 3), dtype=np.int16),
        +                    np.array([1.0, -0.0], dtype=">f8"),
        +                )
        +            """)
        +            + definition
        +        },
        +    )
        +    out_type = module.OUT_TYPE
        +    packaged = function(
        +        input_schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]),
        +        output_schema=pa.field("out", out_type, nullable=False),
        +    )(module.judge)
        +    source = artifact(packaged).decode()
        +    assert "import numpy as _lancedb_numpy" in source
        +    assert "import pyarrow as _lancedb_pyarrow" in source
        +
        +    namespace = {}
        +    exec(compile(source, "user_function.py", "exec"), namespace)
        +    call = namespace["judge"]() if kind == "class" else namespace["judge"]
        +    result = call(pa.array([1, 2]))
        +    assert result.type == out_type
        +    assert result.to_pylist() == [{"label": "pick", "score": 0}] * 2
        +    assert namespace["OUT_TYPE"] == out_type
        +
        +    assert namespace["LABELS"] == module.LABELS
        +    assert list(namespace["LABELS"]) == list(module.LABELS)
        +    assert namespace["EMPTY"] == module.EMPTY
        +    assert [type(value) for value in namespace["EMPTY"]] == [
        +        type(value) for value in module.EMPTY
        +    ]
        +    for key, value in module.ARROW.items():
        +        assert namespace["ARROW"][key].equals(value, check_metadata=True)
        +        assert type(namespace["ARROW"][key]) is type(value)
        +
        +    weights = namespace["WEIGHTS"]
        +    assert weights.dtype == module.WEIGHTS.dtype
        +    assert np.array_equal(weights, module.WEIGHTS)
        +    for captured, original in zip(namespace["NUMPY"], module.NUMPY, strict=True):
        +        assert type(captured) is type(original)
        +        assert captured.dtype == original.dtype
        +        assert np.shape(captured) == np.shape(original)
        +        assert np.array_equal(captured, original)
        +    assert np.signbit(namespace["NUMPY"][-1][1])
        +
        +
        +@pytest.mark.parametrize("kind", ["function", "class"])
        +@pytest.mark.parametrize("shape", [(0,), (0, 3), (2, 0, 3), (500_000, 0)])
        +def test_empty_numpy_captures_preserve_shape_without_expanding(
        +    helper_package, kind, shape
        +):
        +    definition = (
        +        "class empty_size:\n    def __call__(self, value: int) -> int:\n"
        +        "        return value + EMPTY.size\n"
        +        if kind == "class"
        +        else "def empty_size(value: int) -> int:\n    return value + EMPTY.size\n"
        +    )
        +    module = helper_package(
        +        "fx_empty_numpy_global",
        +        {
        +            "__init__.py": "import numpy as np\n"
        +            f"EMPTY = np.empty({shape!r}, dtype='>i2')\n" + definition
        +        },
        +    )
        +    source = artifact(function(module.empty_size))
        +    assert len(source) < 1024
        +    namespace = {}
        +    exec(compile(source, "user_function.py", "exec"), namespace)
        +    captured = namespace["EMPTY"]
        +    assert captured.shape == shape
        +    assert captured.dtype == module.EMPTY.dtype
        +    assert captured.size == 0
        +    call = namespace["empty_size"]() if kind == "class" else namespace["empty_size"]
        +    assert call(7) == 7
        +
        +
        +def test_captured_containers_are_copied_when_decorated(helper_package):
        +    module = helper_package(
        +        "fx_captured_copy",
        +        {
        +            "__init__.py": """
        +                SHARED = [1, 2]
        +                CONFIG = {"shared": SHARED, "again": SHARED}
        +
        +                def uses_config(value: int) -> int:
        +                    return value + len(CONFIG["shared"]) + len(SHARED)
        +            """
        +        },
        +    )
        +    definition = function(module.uses_config)
        +    module.SHARED.append(3)
        +
        +    namespace = {}
        +    exec(compile(artifact(definition), "user_function.py", "exec"), namespace)
        +    assert namespace["SHARED"] == [1, 2]
        +    assert namespace["CONFIG"] == {"shared": [1, 2], "again": [1, 2]}
        +    assert namespace["CONFIG"]["shared"] is not namespace["CONFIG"]["again"]
        +    assert namespace["CONFIG"]["shared"] is not namespace["SHARED"]
        +    assert namespace["uses_config"](1) == 5
        +
        +
        +def test_captured_sets_package_deterministically(tmp_path):
        +    script = tmp_path / "sets.py"
        +    script.write_text(
        +        textwrap.dedent(
        +            """
        +            import json
        +
        +            from lancedb import function
        +
        +            WORDS = {f"word{index}" for index in range(20)}
        +            MIXED = frozenset({("pair", 1), b"bytes", None, 2.5, "text"})
        +
        +            @function
        +            def known(word: str) -> bool:
        +                return word in WORDS or word in MIXED
        +
        +            print(json.dumps([
        +                known.registration_request.artifact.digest,
        +                list(WORDS),
        +            ]))
        +            """
        +        )
        +    )
        +    runs = []
        +    for seed in ("0", "1", "2", "3"):
        +        result = subprocess.run(
        +            [sys.executable, str(script)],
        +            capture_output=True,
        +            text=True,
        +            env={**os.environ, "PYTHONHASHSEED": seed},
        +        )
        +        assert result.returncode == 0, result.stderr
        +        runs.append(json.loads(result.stdout))
        +    # Hash randomization reorders the client's set; the artifact must not change.
        +    assert len({tuple(order) for _, order in runs}) > 1
        +    assert len({digest for digest, _ in runs}) == 1
        +
        +
        +@pytest.mark.parametrize(
        +    ("global_value", "message"),
        +    [
        +        ("list(range(300_000))", "too large to capture"),
        +        ("np.zeros(2_000_000)", "too large to capture"),
        +        ("'x' * (1024 * 1024)", "too large to capture"),
        +        ("functools.reduce(lambda inner, _: [inner], range(40), [])", "32 levels"),
        +        ("_cycle()", "contains itself"),
        +        ("pa.schema([pa.field('x', pa.list_(_Extension()))])", "defined in Python"),
        +    ],
        +)
        +def test_captured_value_limits_name_the_global(helper_package, global_value, message):
        +    module = helper_package(
        +        "fx_captured_limits",
        +        {
        +            "__init__.py": textwrap.dedent("""
        +                import functools
        +
        +                import numpy as np
        +                import pyarrow as pa
        +
        +                class _Extension(pa.ExtensionType):
        +                    def __init__(self):
        +                        super().__init__(pa.int64(), "fx.extension")
        +
        +                    def __arrow_ext_serialize__(self):
        +                        return b""
        +
        +                    @classmethod
        +                    def __arrow_ext_deserialize__(cls, storage_type, serialized):
        +                        return cls()
        +
        +                def _cycle():
        +                    value = []
        +                    value.append(value)
        +                    return value
        +            """)
        +            + f"CAPTURED_VALUE = {global_value}\n"
        +            "def uses_global(value: int) -> int:\n"
        +            "    return value if CAPTURED_VALUE else 0\n"
        +        },
        +    )
        +    with pytest.raises((TypeError, ValueError)) as error:
        +        function(module.uses_global)
        +    assert "CAPTURED_VALUE" in str(error.value)
        +    assert message in str(error.value)
        +    assert "inside the function or class body" in str(error.value)
        +
        +
        +def test_captured_sets_keep_their_builtins(helper_package):
        +    module = helper_package(
        +        "fx_captured_builtins",
        +        {
        +            "__init__.py": """
        +                STOP = frozenset({"a"})
        +                frozenset = ("shadowed",)
        +
        +                def uses_sets(word: str) -> bool:
        +                    return word in STOP or word in frozenset
        +            """
        +        },
        +    )
        +    with pytest.raises(ValueError, match="cannot package 'frozenset'"):
        +        function(module.uses_sets)
        +
        +
         @pytest.mark.parametrize("annotation", ["Array", "RecordBatch"])
         @pytest.mark.parametrize("kind", ["function", "class"])
         def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package):
        @@ -147,11 +568,11 @@ def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_pac
                 """
             module = helper_package("fx_batch_annotations", {"__init__.py": source})
             with pytest.raises(TypeError, match="input_schema and output_schema"):
        -        udf(module.identity)
        +        function(module.identity)
         
         
         def test_array_batch_annotations_accept_explicit_schemas():
        -    @udf(
        +    @function(
                 input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
                 output_schema=pa.int64(),
             )
        @@ -168,7 +589,246 @@ def test_array_batch_annotations_accept_explicit_schemas():
             assert identity(values).equals(values)
         
         
        -@pytest.mark.parametrize("class_udf", [False, True])
        +def test_batch_functions_take_one_array_parameter_per_input_column():
        +    @function(
        +        input_schema=pa.schema(
        +            [
        +                pa.field("value", pa.float64(), nullable=False),
        +                pa.field("weight", pa.float64(), nullable=False),
        +            ]
        +        ),
        +        output_schema=pa.float64(),
        +    )
        +    def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array:
        +        return pc.multiply(value, weight)
        +
        +    signature = weighted_score.registration_request.signature
        +    assert [parameter.name for parameter in signature.inputs] == ["value", "weight"]
        +    result = weighted_score(pa.array([1.0, 2.0]), pa.array([3.0, 4.0]))
        +    assert result.to_pylist() == [3.0, 8.0]
        +
        +
        +@pytest.mark.parametrize(
        +    "invoke",
        +    [
        +        lambda definition: definition(col("value")),
        +        lambda definition: definition(value=col("value")),
        +        lambda definition: definition(value=col("value") * 2),
        +    ],
        +    ids=["positional", "keyword", "derived"],
        +)
        +def test_definition_calls_reject_expr_inputs_before_user_code(invoke):
        +    @function
        +    def double(value: float) -> float:
        +        raise AssertionError("user code ran")
        +
        +    with pytest.raises(TypeError, match="registered FunctionVersion"):
        +        invoke(double)
        +
        +
        +def test_class_definition_binds_initialization_only_on_a_version():
        +    with pytest.raises(TypeError, match="registered FunctionVersion"):
        +        scale(factor=col("factor"), label="x")
        +
        +
        +def test_blob_writer_scalar_annotation_and_bytes_keep_distinct_wire_shapes():
        +    @function
        +    def render(text: str) -> BlobWriter:
        +        with BlobWriter.open() as output:
        +            output.write(text.encode())
        +        return output
        +
        +    @function(output_schema=blob("image", nullable=False))
        +    def render_bytes(text: str) -> bytes:
        +        return text.encode()
        +
        +    scalar = {"kind": "scalar", "arrow_type": "blob_v2", "nullable": False}
        +    writer = {**scalar, "kind": "scalar_blob_writer", "blob_writer_paths": [[]]}
        +    for definition, expected in ((render, writer), (render_bytes, scalar)):
        +        request = json.loads(definition.registration_request.to_canonical_json())
        +        assert request["signature"]["output"] == expected
        +        assert request["artifact"]["adapter"] == {
        +            "kind": "scalar_to_arrow_batch",
        +            "version": 1,
        +        }
        +    assert render_bytes("text") == b"text"
        +    with pytest.raises(RuntimeError, match="computed column refresh"):
        +        render("text")
        +
        +
        +@pytest.mark.parametrize("input_type", ["Array", "RecordBatch"])
        +@pytest.mark.parametrize("return_type", ["list[Writer]", "tuple[Writer, ...]"])
        +def test_blob_writer_vectorized_annotations_resolve_in_the_artifact(
        +    helper_package, monkeypatch, input_type, return_type
        +):
        +    as_tuple = return_type.startswith("tuple")
        +    result = "tuple(results)" if as_tuple else "results"
        +    column = "values" if input_type == "Array" else "values.column(0)"
        +    module = helper_package(
        +        "fx_blob_writers",
        +        {
        +            "__init__.py": f"""
        +                from __future__ import annotations
        +
        +                import pyarrow as pa
        +                from pyarrow import {input_type} as Batch
        +                from lancedb.functions import BlobWriter as Writer, function
        +
        +                Output = {return_type}
        +
        +                @function(input_schema=pa.schema([pa.field("values", pa.string())]))
        +                def render(values: Batch) -> Output:
        +                    results = []
        +                    for text in {column}:
        +                        with Writer.open() as output:
        +                            output.write(text.as_py().encode())
        +                        results.append(output)
        +                    return {result}
        +            """,
        +        },
        +    )
        +    assert json.loads(
        +        module.render.registration_request.signature.output.to_canonical_json()
        +    ) == {
        +        "kind": "scalar_blob_writer",
        +        "arrow_type": "blob_v2",
        +        "nullable": False,
        +        "blob_writer_paths": [[]],
        +    }
        +
        +    class WorkerWriter:
        +        def __init__(self):
        +            self.payload = bytearray()
        +            self.closed = False
        +
        +        @classmethod
        +        def open(cls):
        +            return cls()
        +
        +        def write(self, data):
        +            self.payload.extend(data)
        +            return len(data)
        +
        +        def __enter__(self):
        +            return self
        +
        +        def __exit__(self, *_):
        +            self.closed = True
        +
        +    worker = types.ModuleType("lance_blob")
        +    worker.BlobWriter = WorkerWriter
        +    monkeypatch.setitem(sys.modules, "lance_blob", worker)
        +    namespace = {}
        +    exec(compile(artifact(module.render), "user_function.py", "exec"), namespace)
        +    render = namespace["render"]
        +    input_annotation = getattr(pa, input_type)
        +    output_annotation = (
        +        tuple[WorkerWriter, ...]
        +        if return_type.startswith("tuple")
        +        else list[WorkerWriter]
        +    )
        +    assert get_type_hints(render) == {
        +        "values": input_annotation,
        +        "return": output_annotation,
        +    }
        +    column = pa.array(["alpha", "", "omega"])
        +    batch = column if input_type == "Array" else pa.record_batch([column], names=["x"])
        +    output = render(batch)
        +    assert [(type(value), value.closed, bytes(value.payload)) for value in output] == [
        +        (WorkerWriter, True, b"alpha"),
        +        (WorkerWriter, True, b""),
        +        (WorkerWriter, True, b"omega"),
        +    ]
        +
        +
        +@pytest.mark.parametrize("list_type", [pa.list_, pa.large_list])
        +def test_blob_writer_nested_paths_keep_logical_arrow_schema(list_type):
        +    def output_schema(blob_field):
        +        return list_type(
        +            pa.field(
        +                "asset",
        +                pa.struct(
        +                    [
        +                        blob_field("item"),
        +                        blob("bytes_sibling"),
        +                        pa.field("checksum", pa.binary(), nullable=False),
        +                        blob_field("rendered.blob", nullable=False),
        +                    ]
        +                ),
        +            )
        +        )
        +
        +    def render_batch(values: pa.Array):
        +        return [
        +            [
        +                {
        +                    "item": None,
        +                    "bytes_sibling": b"",
        +                    "checksum": b"ok",
        +                    "rendered.blob": b"",
        +                }
        +            ]
        +        ] * len(values)
        +
        +    input_schema = pa.schema([pa.field("values", pa.string())])
        +    streaming = function(
        +        render_batch,
        +        input_schema=input_schema,
        +        output_schema=output_schema(BlobWriter.field),
        +    )
        +    materialized = function(
        +        render_batch, input_schema=input_schema, output_schema=output_schema(blob)
        +    )
        +    plain = json.loads(
        +        materialized.registration_request.signature.output.to_canonical_json()
        +    )
        +    writer = json.loads(
        +        streaming.registration_request.signature.output.to_canonical_json()
        +    )
        +    assert writer == {
        +        **plain,
        +        "kind": "scalar_blob_writer",
        +        "blob_writer_paths": [
        +            ["item", {"field": "item"}],
        +            ["item", {"field": "rendered.blob"}],
        +        ],
        +    }
        +    item = json.loads(writer["arrow_type"])["fields"][0]
        +    assert item["name"] == "asset"
        +    assert item["nullable"] is True
        +    assert item["type"]["fields"][0]["metadata"] == {
        +        "ARROW:extension:name": "lance.blob.v2"
        +    }
        +
        +
        +def test_blob_writer_requires_supported_output_leaves():
        +    def annotated(value: str) -> BlobWriter:
        +        return BlobWriter.open()
        +
        +    def optional(value: str) -> BlobWriter | None:
        +        return None
        +
        +    def explicit(value: str):
        +        return value
        +
        +    with pytest.raises(TypeError, match="requires a Blob v2 field"):
        +        function(annotated, output_schema=pa.binary())
        +    with pytest.raises(ValueError, match="must be non-nullable"):
        +        function(optional)
        +    invalid_field = pa.field(
        +        "value", pa.binary(), metadata={"lance.function.blob_writer": "true"}
        +    )
        +    with pytest.raises(TypeError, match="requires a Blob v2 field"):
        +        function(explicit, output_schema=pa.struct([invalid_field]))
        +    for schema in (
        +        pa.list_(BlobWriter.field("item"), 2),
        +        pa.map_(pa.string(), BlobWriter.field("value")),
        +    ):
        +        with pytest.raises(TypeError, match="nested under collection types"):
        +            function(explicit, output_schema=schema)
        +
        +
        +@pytest.mark.parametrize("class_function", [False, True])
         @pytest.mark.parametrize("postponed", [False, True])
         @pytest.mark.parametrize(
             ("annotation", "nullable"),
        @@ -185,13 +845,13 @@ def test_array_batch_annotations_accept_explicit_schemas():
             ],
         )
         def test_blob_reader_annotations_resolve_in_the_artifact(
        -    helper_package, monkeypatch, class_udf, postponed, annotation, nullable
        +    helper_package, monkeypatch, class_function, postponed, annotation, nullable
         ):
             definition = (
                 f"class read_blob:\n"
                 f"    def __call__(self, video: {annotation}) -> int:\n"
                 f"        return 0\n"
        -        if class_udf
        +        if class_function
                 else f"def read_blob(video: {annotation}) -> int:\n    return 0\n"
             )
             module = helper_package(
        @@ -202,9 +862,9 @@ def test_blob_reader_annotations_resolve_in_the_artifact(
                         + "import lancedb\n"
                         "from typing import Optional\n"
                         "from lancedb import BlobReader, BlobReader as Reader\n"
        -                "from lancedb.functions import udf\n"
        +                "from lancedb.functions import function\n"
                         "MaybeReader = Optional[Reader]\n\n"
        -                f"@udf\n{definition}"
        +                f"@function\n{definition}"
                     )
                 },
             )
        @@ -221,7 +881,7 @@ def test_blob_reader_annotations_resolve_in_the_artifact(
             namespace = {}
             exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace)
             packaged = namespace["read_blob"]
        -    if class_udf:
        +    if class_function:
                 packaged = packaged.__call__
             assert get_type_hints(packaged) == {
                 "video": Optional[worker.BlobReader] if nullable else worker.BlobReader,
        @@ -237,11 +897,11 @@ def test_blob_reader_annotation_does_not_shadow_body_globals(
                 {
                     "__init__.py": """
                         from lancedb import BlobReader
        -                from lancedb.functions import udf
        +                from lancedb.functions import function
         
                         _lance_blob_reader = 7
         
        -                @udf
        +                @function
                         def read_blob(video: BlobReader) -> int:
                             return _lance_blob_reader
                     """
        @@ -280,14 +940,14 @@ def test_class_function_rejects_unsupported_initialization(init, message):
                 namespace,
             )
             with pytest.raises((TypeError, ValueError), match=message):
        -        udf(namespace["bad"])
        +        function(namespace["bad"])
         
         
         def test_class_function_requires_call_and_a_plain_close():
             with pytest.raises(TypeError, match="synchronous __call__"):
        -        udf(NoCall)
        +        function(NoCall)
             with pytest.raises(TypeError, match="close must be a method taking no"):
        -        udf(BadClose)
        +        function(BadClose)
         
         
         def test_nested_class_and_closure_are_rejected_with_the_reason():
        @@ -299,17 +959,275 @@ def test_nested_class_and_closure_are_rejected_with_the_reason():
                 return nested
         
             with pytest.raises(ValueError, match="defined at module level"):
        -        udf(build())
        +        function(build())
         
             factor = 3
         
             with pytest.raises(ValueError, match="capture closure values"):
         
        -        @udf
        +        @function
                 def closes_over(value: int) -> int:
                     return value * factor
         
         
        +@pytest.mark.parametrize(
        +    "module_name",
        +    [
        +        "builtins",
        +        "importlib",
        +        "inspect",
        +        "gc",
        +        "ctypes",
        +        "types",
        +        "ctypes.util",
        +    ],
        +)
        +@pytest.mark.parametrize("import_style", ["import", "from", "global"])
        +@pytest.mark.parametrize("class_function", [False, True])
        +def test_namespace_module_errors_explain_the_rule_and_remedy(
        +    helper_package, module_name, import_style, class_function
        +):
        +    statement = f"import {module_name} as namespace_module"
        +    body = f"{statement}\nreturn value\n"
        +    preamble = ""
        +    if import_style == "from":
        +        body = f"from {module_name} import __name__\nreturn value\n"
        +    elif import_style == "global":
        +        preamble = statement + "\n"
        +        body = "return str(namespace_module)\n"
        +    if class_function:
        +        definition = "class blocked:\n    def __call__(self, value: str) -> str:\n"
        +        source = preamble + definition + textwrap.indent(body, "        ")
        +    else:
        +        definition = "def blocked(value: str) -> str:\n"
        +        source = preamble + definition + textwrap.indent(body, "    ")
        +    module = helper_package("fx_namespace_import", {"__init__.py": source})
        +
        +    with pytest.raises(ValueError) as error:
        +        function(module.blocked)
        +    message = str(error.value)
        +    assert "imports from namespace-access modules" in message
        +    assert repr(module_name) in message
        +    assert "builtins, ctypes, gc, importlib, inspect, sys, types" in message
        +    assert "including submodules" in message
        +    assert "reconstructed module namespace" in message
        +    assert "importable helper module" in message
        +    assert "code=, pip=, or conda=" in message
        +    assert "dynamic namespace access" not in message
        +
        +
        +@pytest.mark.parametrize("module_level", [False, True], ids=["body", "module"])
        +@pytest.mark.parametrize(
        +    ("import_statement", "expression"),
        +    [
        +        ("import sys", "sys.stderr"),
        +        ("import sys as diagnostic", "diagnostic.stderr"),
        +        ("from sys import stderr", "stderr"),
        +        ("from sys import stderr as error_stream", "error_stream"),
        +        ("import sys", "sys.version_info"),
        +        ("import sys as diagnostic", "diagnostic.version_info"),
        +        ("from sys import version_info", "version_info"),
        +        ("from sys import version_info as python_version", "python_version"),
        +        ("import importlib.metadata", "importlib.metadata.version('pytest')"),
        +        ("import importlib.metadata as diagnostic", "diagnostic.version('pytest')"),
        +        ("from importlib import metadata", "metadata.version('pytest')"),
        +        (
        +            "from importlib import metadata as diagnostic",
        +            "diagnostic.version('pytest')",
        +        ),
        +        ("from importlib.metadata import version", "version('pytest')"),
        +        (
        +            "from importlib.metadata import version as diagnostic",
        +            "diagnostic('pytest')",
        +        ),
        +    ],
        +)
        +def test_diagnostic_namespace_operations_package_and_run(
        +    helper_package, module_level, import_statement, expression
        +):
        +    if module_level:
        +        source = (
        +            f"{import_statement}\n\n"
        +            "def probe(value: str) -> str:\n"
        +            f"    return str({expression}) + value\n"
        +        )
        +    else:
        +        source = (
        +            "def probe(value: str) -> str:\n"
        +            f"    {import_statement}\n"
        +            f"    return str({expression}) + value\n"
        +        )
        +    module = helper_package("fx_diagnostic_operation", {"__init__.py": source})
        +
        +    packaged = artifact(function(module.probe)).decode()
        +    namespace = {}
        +    exec(compile(packaged, "user_function.py", "exec"), namespace)
        +    assert namespace["probe"]("!").endswith("!")
        +
        +
        +@pytest.mark.parametrize(
        +    ("body", "operation"),
        +    [
        +        ("import sys\nreturn str(sys.modules)", "sys.modules"),
        +        ("import sys as s\nreturn str(s.path)", "s.path"),
        +        ("import sys\nreturn str(sys.version)", "sys.version"),
        +        ("import sys\nreturn str(sys.stdout)", "sys.stdout"),
        +        ("import sys\nreturn str(getattr(sys, 'stderr'))", "sys"),
        +        ("import sys\nstream = sys\nreturn str(stream)", "sys"),
        +        ("import sys\nsys = object()\nreturn str(sys)", "sys"),
        +        ("from sys import path\nreturn str(path)", "sys.path"),
        +        (
        +            "import importlib.metadata\n"
        +            "return importlib.metadata.distribution('pytest').version",
        +            "importlib.metadata.distribution",
        +        ),
        +        (
        +            "import importlib.metadata as m\nreturn m.distribution('pytest').version",
        +            "m.distribution",
        +        ),
        +        (
        +            "from importlib.metadata import distribution\n"
        +            "return distribution('pytest').version",
        +            "importlib.metadata.distribution",
        +        ),
        +        (
        +            "from importlib.metadata import version\nreturn str(version.__globals__)",
        +            "version.__globals__",
        +        ),
        +        (
        +            "import importlib\nreturn str(importlib.import_module('os'))",
        +            "importlib",
        +        ),
        +        (
        +            "from importlib import import_module\nreturn str(import_module('os'))",
        +            "importlib",
        +        ),
        +        (
        +            "import importlib.resources\nreturn str(importlib.resources.files('x'))",
        +            "importlib.resources",
        +        ),
        +        ("import inspect\nreturn str(inspect.currentframe())", "inspect"),
        +        (
        +            "from ctypes import util\nreturn str(util.find_library('c'))",
        +            "ctypes",
        +        ),
        +        ("import gc\nreturn str(gc.get_objects())", "gc"),
        +        ("import builtins\nreturn str(builtins)", "builtins"),
        +        ("import types\nreturn str(types.SimpleNamespace())", "types"),
        +    ],
        +)
        +def test_unsupported_namespace_operations_are_rejected(helper_package, body, operation):
        +    source = "def blocked(value: str) -> str:\n" + textwrap.indent(body, "    ")
        +    module = helper_package(
        +        "fx_unsupported_namespace_operation", {"__init__.py": source}
        +    )
        +
        +    with pytest.raises(ValueError) as error:
        +        function(module.blocked)
        +    message = str(error.value)
        +    assert repr(operation) in message
        +    assert "supported diagnostic operations" in message
        +
        +
        +@pytest.mark.parametrize(
        +    ("preamble", "body", "operation"),
        +    [
        +        (
        +            "import sys as diagnostic",
        +            "return str(diagnostic.modules)",
        +            "diagnostic.modules",
        +        ),
        +        (
        +            "import importlib.metadata as diagnostic",
        +            "return diagnostic.distribution('pytest').version",
        +            "diagnostic.distribution",
        +        ),
        +        ("from sys import stderr", "return str(stderr.__class__)", "stderr.__class__"),
        +    ],
        +)
        +def test_module_level_diagnostic_alias_rejects_unsupported_use(
        +    helper_package, preamble, body, operation
        +):
        +    source = f"{preamble}\n\ndef blocked(value: str) -> str:\n    {body}\n"
        +    module = helper_package("fx_diagnostic_alias", {"__init__.py": source})
        +
        +    with pytest.raises(ValueError) as error:
        +        function(module.blocked)
        +    assert repr(operation) in str(error.value)
        +
        +
        +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
        +def test_udf_namespace_import_error_explains_the_helper_alternative():
        +    with pytest.raises(ValueError, match="ctypes.util.*importable helper module"):
        +
        +        @udf
        +        def probe(value: str) -> str:
        +            import ctypes.util
        +
        +            return str(ctypes.util.find_library(value))
        +
        +
        +@pytest.mark.parametrize(
        +    "operation", ["globals", "locals", "vars", "eval", "exec", "compile", "__import__"]
        +)
        +def test_dynamic_namespace_errors_name_the_operation_and_remedy(
        +    helper_package, operation
        +):
        +    module = helper_package(
        +        "fx_namespace_operation",
        +        {
        +            "__init__.py": (
        +                f"def blocked(value: str) -> str:\n    return str({operation})\n"
        +            )
        +        },
        +    )
        +    with pytest.raises(ValueError) as error:
        +        function(module.blocked)
        +    message = str(error.value)
        +    assert f"dynamic namespace access: ['{operation}']" in message
        +    assert "Reference dependencies explicitly" in message
        +    assert "importable helper module" in message
        +
        +
        +@pytest.mark.parametrize("ship_source", [False, True])
        +def test_namespace_access_in_importable_helpers_keeps_its_module_namespace(
        +    helper_package, ship_source
        +):
        +    helpers = helper_package(
        +        "fx_namespace_helper",
        +        {
        +            "__init__.py": """
        +                import ctypes.util
        +
        +                def module_name():
        +                    return ctypes.util.__name__
        +            """,
        +        },
        +    )
        +    entry = helper_package(
        +        "fx_namespace_entry",
        +        {
        +            "__init__.py": """
        +                from fx_namespace_helper import module_name
        +
        +                def probe(value: str) -> str:
        +                    return module_name() + value
        +            """,
        +        },
        +    )
        +    options = {"code": [helpers]} if ship_source else {"pip": ["fx-namespace-helper"]}
        +    definition = function(**options)(entry.probe)
        +    if ship_source:
        +        files = bundle_files(definition)
        +        assert "import ctypes.util" in files["fx_namespace_helper/__init__.py"]
        +        source = files["user_function.py"]
        +    else:
        +        source = artifact(definition).decode()
        +    namespace = {}
        +    exec(compile(source, "user_function.py", "exec"), namespace)
        +    assert namespace["probe"]("!") == "ctypes.util!"
        +
        +
         def test_binding_passes_initialization_as_constants():
             version = FunctionVersion.from_json(
                 json.dumps(
        @@ -352,6 +1270,102 @@ def test_binding_passes_initialization_as_constants():
                 version(text=col("body"), model=object())
         
         
        +def test_vendored_package_resources_survive_an_isolated_import(
        +    tmp_path, helper_package
        +):
        +    package = helper_package(
        +        "fx_vendor",
        +        {
        +            "__init__.py": "from .vendor.model import predict",
        +            "vendor/__init__.py": "",
        +            "vendor/model.py": """
        +                import hashlib
        +                import json
        +                from importlib.resources import files
        +
        +                def predict(value):
        +                    root = files("fx_vendor")
        +                    payload = root.joinpath("label-maps/payload.bin").read_bytes()
        +                    metadata = json.loads(root.joinpath("models.json").read_text())
        +                    source = root.joinpath("vendor/model.py").read_bytes()
        +                    source_digest = hashlib.sha256(source).hexdigest()
        +                    assert source_digest == metadata["source_sha256"]
        +                    assert hashlib.sha256(payload).hexdigest() == metadata["sha256"]
        +                    return value + metadata["offset"]
        +            """,
        +            "models.json": "{}",
        +        },
        +    )
        +    payload = b"\x00\xff\r\nvendored model data"
        +    package_root = Path(package.__file__).parent
        +    (package_root / "label-maps").mkdir()
        +    (package_root / "label-maps/payload.bin").write_bytes(payload)
        +    module_path = package_root / "vendor/model.py"
        +    module_bytes = (
        +        module_path.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")
        +    )
        +    module_path.write_bytes(module_bytes)
        +    (package_root / "models.json").write_bytes(
        +        json.dumps(
        +            {
        +                "sha256": hashlib.sha256(payload).hexdigest(),
        +                "source_sha256": hashlib.sha256(module_bytes).hexdigest(),
        +                "offset": 7,
        +            }
        +        ).encode()
        +        + b"\r\n"
        +    )
        +
        +    entry = helper_package(
        +        "fx_vendor_entry",
        +        {
        +            "__init__.py": """
        +        import fx_vendor
        +        from lancedb import function
        +
        +        @function(code=[fx_vendor])
        +        def vendored(value: int) -> int:
        +            return fx_vendor.predict(value)
        +    """
        +        },
        +    )
        +    vendored = entry.vendored
        +
        +    first_digest = vendored.registration_request.artifact.digest
        +    bundle = json.loads(artifact(vendored))
        +    isolated = tmp_path / "isolated"
        +    isolated.mkdir()
        +    for name, content in bundle["files"].items():
        +        target = isolated / name
        +        target.parent.mkdir(parents=True, exist_ok=True)
        +        target.write_bytes(content.encode("utf-8"))
        +    for name, content in bundle["resources"].items():
        +        target = isolated / name
        +        target.parent.mkdir(parents=True, exist_ok=True)
        +        target.write_bytes(base64.b64decode(content))
        +    assert (isolated / "fx_vendor/models.json").read_bytes().endswith(b"\r\n")
        +    result = subprocess.run(
        +        [
        +            sys.executable,
        +            "-I",
        +            "-c",
        +            "import sys; sys.path.insert(0, sys.argv[1]); "
        +            "from user_function import vendored; assert vendored(3) == 10",
        +            str(isolated),
        +        ],
        +        capture_output=True,
        +        text=True,
        +    )
        +    assert result.returncode == 0, result.stderr
        +    (package_root / "models.json").write_text('{"offset": 8}')
        +    assert (
        +        function(code=[package])(
        +            vendored._function
        +        ).registration_request.artifact.digest
        +        != first_digest
        +    )
        +
        +
         def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
             tmp_path, helper_package
         ):
        @@ -372,10 +1386,10 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
                     """
                     import fx_helpers
                     from fx_helpers.rate import TokenBucket
        -            from lancedb import udf
        +            from lancedb import function
         
         
        -            @udf(code=[fx_helpers])
        +            @function(code=[fx_helpers])
                     class limited:
                         def __init__(self, tpm: int):
                             self.limiter = TokenBucket(tpm)
        @@ -396,14 +1410,13 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
                 first = define()
             assert len(caught) == 1
             warning = str(caught[0].message)
        -    assert "fx_helpers/fixtures/data.json" in warning
        +    assert "fx_helpers/fixtures/data.json" not in warning
             assert "fx_helpers/not-a-module.py" in warning
        -    assert warning.index("fx_helpers/fixtures/data.json") < warning.index(
        -        "fx_helpers/not-a-module.py"
        -    )
        -    assert "remove 'fx_helpers' from code=" in warning
        -    assert "pip=" in warning
        -    assert "conda=" in warning
        +
        +    assert "safe relative names" in warning
        +    assert "importable Python module names" in warning
        +    resources = json.loads(artifact(first))["resources"]
        +    assert base64.b64decode(resources["fx_helpers/fixtures/data.json"]) == b"{}"
             assert "__pycache__" not in warning
             assert ".pyc" not in warning
             shipped = bundle_files(first)
        @@ -445,7 +1458,7 @@ def test_code_package_cache_artifacts_do_not_warn(helper_package):
             with warnings.catch_warnings(record=True) as caught:
                 warnings.simplefilter("always")
         
        -        @udf(code=[cache])
        +        @function(code=[cache])
                 def cache_only(value: int) -> int:
                     return value
         
        @@ -456,7 +1469,7 @@ def test_code_package_cache_artifacts_do_not_warn(helper_package):
             ]
         
         
        -def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_package):
        +def test_code_package_resources_keep_nonidentifier_directories(helper_package):
             resources = helper_package(
                 "fx_resources",
                 {
        @@ -468,15 +1481,13 @@ def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_packag
             with warnings.catch_warnings(record=True) as caught:
                 warnings.simplefilter("always")
         
        -        @udf(code=[resources])
        +        @function(code=[resources])
                 def resource_boundary(value: int) -> int:
                     return value
         
        -    assert len(caught) == 1
        -    warning = str(caught[0].message)
        -    assert "fx_resources/label-maps/" in warning
        -    assert "remove 'fx_resources' from code=" in warning
        -    assert "labels.json" not in warning
        +    assert not caught
        +    resources = json.loads(artifact(resource_boundary))["resources"]
        +    assert base64.b64decode(resources["fx_resources/label-maps/labels.json"]) == b"{}"
             assert sorted(bundle_files(resource_boundary)) == [
                 "fx_resources/__init__.py",
                 "user_function.py",
        @@ -495,7 +1506,7 @@ def test_code_rejects_submodules_duplicates_and_non_modules(helper_package):
             ]:
                 with pytest.raises((TypeError, ValueError), match=message):
         
        -            @udf(code=code)
        +            @function(code=code)
                     def f(value: int) -> int:
                         return value
         
        @@ -514,10 +1525,10 @@ def test_local_module_outside_code_warns_at_registration(tmp_path, helper_packag
                     textwrap.dedent(
                         f"""
                         from fx_local import normalize
        -                from lancedb import udf
        +                from lancedb import function
         
         
        -                @udf({options})
        +                @function({options})
                         def {name}(value: int) -> int:
                             return normalize(value)
                         """
        @@ -551,10 +1562,10 @@ def test_local_module_imported_in_function_body_warns_at_registration(
                 (tmp_path / f"{name}.py").write_text(
                     textwrap.dedent(
                         f"""
        -                from lancedb import udf
        +                from lancedb import function
         
         
        -                @udf({options})
        +                @function({options})
                         def {name}(value: int) -> int:
                             import fx_body_local
         
        @@ -575,6 +1586,94 @@ def test_local_module_imported_in_function_body_warns_at_registration(
             assert "import fx_body_local" in artifact(installed).decode()
         
         
        +def test_missing_module_without_declared_package_warns_at_registration(
        +    tmp_path, monkeypatch
        +):
        +    package = "fx_missing_remote_package_ent3448"
        +    monkeypatch.syspath_prepend(str(tmp_path))
        +
        +    def define(name):
        +        (tmp_path / f"{name}.py").write_text(
        +            textwrap.dedent(
        +                f"""
        +                from lancedb import function
        +
        +
        +                @function(pip=())
        +                def {name}(value: int) -> int:
        +                    import {package}.plugin
        +
        +                    return value
        +                """
        +            )
        +        )
        +        importlib.invalidate_caches()
        +        return getattr(importlib.import_module(name), name)
        +
        +    with pytest.warns(UserWarning) as caught:
        +        definition = define("fx_uses_missing_package")
        +
        +    message = str(caught[0].message)
        +    assert f"imports {package!r}" in message
        +    assert "unavailable in the client environment" in message
        +    assert "no declared pip/conda dependencies" in message
        +    assert "Remote availability cannot be verified" in message
        +    assert "confirm that the base image provides it" in message
        +    assert "cannot import" not in message
        +    assert f"import {package}.plugin" in artifact(definition).decode()
        +
        +    with warnings.catch_warnings():
        +        warnings.simplefilter("error", UserWarning)
        +        with pytest.raises(UserWarning, match="Remote availability cannot be verified"):
        +            define("fx_missing_package_as_error")
        +
        +
        +def test_resolved_or_declared_module_imports_do_not_warn(tmp_path, helper_package):
        +    package = "fx_missing_remote_package_ent3448"
        +    helper_package("fx_declared_code_package", {"__init__.py": ""})
        +
        +    def define(name, body, options, imports=""):
        +        (tmp_path / f"{name}.py").write_text(
        +            textwrap.dedent(
        +                f"""
        +                {imports}
        +                from lancedb import function
        +
        +
        +                @function({options})
        +                def {name}(value: int) -> int:
        +                    {body}
        +                    return value
        +                """
        +            )
        +        )
        +        importlib.invalidate_caches()
        +        return getattr(importlib.import_module(name), name)
        +
        +    with warnings.catch_warnings(record=True) as caught:
        +        warnings.simplefilter("always")
        +        define("fx_imports_stdlib", "import os.path", "")
        +        # Distribution names need not match the imported top-level module.
        +        define(
        +            "fx_imports_declared_pip",
        +            f"import {package}.plugin",
        +            "pip=['Pillow>=10']",
        +        )
        +        define(
        +            "fx_imports_declared_conda",
        +            f"import {package}.plugin",
        +            "conda=['numpy']",
        +        )
        +        define(
        +            "fx_imports_shipped_code",
        +            "import fx_declared_code_package",
        +            "code=[fx_declared_code_package]",
        +            "import fx_declared_code_package",
        +        )
        +
        +    assert not caught
        +
        +
         MMLB_HELPERS = {
             "__init__.py": "",
             "rate.py": """
        @@ -610,20 +1709,20 @@ import pyarrow as pa
         
         import fx_mmlb
         from fx_mmlb.embedding import OpenAIEmbedder
        -from lancedb import udf
        +from lancedb import function
         
         TEXT = pa.schema([pa.field("text", pa.string())])
         EMBEDDING = pa.list_(pa.field("item", pa.float64(), nullable=False))
         
         
        -@udf(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING)
        +@function(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING)
         class openai_embedding_batch(OpenAIEmbedder):
             def __call__(self, text: pa.Array) -> pa.Array:
                 item = pa.field("item", pa.float64(), nullable=False)
                 return pa.array(self.embed(text.to_pylist()), pa.list_(item))
         
         
        -@udf(code=[fx_mmlb])
        +@function(code=[fx_mmlb])
         class openai_embedding(OpenAIEmbedder):
             def __call__(self, text: str) -> list[float]:
                 return self.embed([text])[0]
        @@ -695,7 +1794,7 @@ def test_main_definitions_travel_by_source(tmp_path):
                     import math
                     from dataclasses import dataclass
         
        -            from lancedb import udf
        +            from lancedb import function
         
                     SCALE = 2
         
        @@ -714,7 +1813,7 @@ def test_main_definitions_travel_by_source(tmp_path):
                             return helper(value) * self.settings.factor
         
         
        -            @udf
        +            @function
                     class scaled(Base):
                         def __init__(self, factor: int):
                             self.settings = Settings(factor)
        @@ -750,11 +1849,11 @@ def test_main_lambdas_are_rejected(tmp_path):
             script.write_text(
                 textwrap.dedent(
                     """
        -            from lancedb import udf
        +            from lancedb import function
         
                     double = lambda value: value * 2
         
        -            @udf
        +            @function
                     def uses_lambda(value: int) -> int:
                         return double(value)
                     """
        @@ -765,3 +1864,33 @@ def test_main_lambdas_are_rejected(tmp_path):
             )
             assert result.returncode != 0
             assert "not lambdas, closures, or nested definitions" in result.stderr
        +
        +
        +def test_udf_alias_warns_and_packages_like_function(helper_package):
        +    def source(decorator: str) -> str:
        +        return f"""
        +            import lancedb
        +            from lancedb import function, udf
        +
        +            @{decorator}
        +            def double(value: int) -> int:
        +                return value * 2
        +        """
        +
        +    current = helper_package("fx_alias_current", {"__init__.py": source("function")})
        +    expected = current.double.registration_request.artifact.digest
        +    for name, decorator in (("fx_alias_bare", "udf"), ("fx_alias_attr", "lancedb.udf")):
        +        with pytest.warns(DeprecationWarning, match="lancedb.udf is deprecated"):
        +            module = helper_package(name, {"__init__.py": source(decorator)})
        +        assert isinstance(module.double, FunctionDefinition)
        +        assert "udf" not in artifact(module.double).decode()
        +        assert module.double.registration_request.artifact.digest == expected
        +
        +
        +def test_udf_definition_alias_warns():
        +    with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"):
        +        from lancedb import UdfDefinition
        +    assert UdfDefinition is FunctionDefinition
        +    with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"):
        +        from lancedb.functions import UdfDefinition as module_alias
        +    assert module_alias is FunctionDefinition
        diff --git a/python/python/tests/test_function_requirements.py b/python/python/tests/test_function_requirements.py
        new file mode 100644
        index 000000000..6f94d1313
        --- /dev/null
        +++ b/python/python/tests/test_function_requirements.py
        @@ -0,0 +1,125 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import pytest
        +
        +from lancedb import function, udf
        +from lancedb.functions import FunctionDefinition
        +
        +
        +def identity(value: int) -> int:
        +    return value
        +
        +
        +@pytest.mark.parametrize(
        +    "package",
        +    [
        +        "torch>=2.0,,<3",
        +        "torch>=",
        +        "torch=>2.0",
        +        "torch[",
        +        "torch; python_version >=",
        +        "",
        +        " torch",
        +        "torch ",
        +    ],
        +)
        +def test_invalid_pip_requirement_fails_before_packaging(package, monkeypatch):
        +    def unexpected_packaging(*args, **kwargs):
        +        pytest.fail("invalid requirements must fail before packaging the function")
        +
        +    monkeypatch.setattr("lancedb.functions._infer_signature", unexpected_packaging)
        +    with pytest.raises(ValueError) as error:
        +        function(pip=["numpy", package])(identity)
        +    assert "pip[1]" in str(error.value)
        +    assert repr(package) in str(error.value)
        +
        +
        +@pytest.mark.parametrize(
        +    "package",
        +    [
        +        "numpy>=1,,<3",
        +        "numpy>=",
        +        "numpy[version=]",
        +        "numpy[unknown_field=value]",
        +        "",
        +        " numpy",
        +        "numpy ",
        +    ],
        +)
        +def test_invalid_conda_requirement_names_entry(package):
        +    with pytest.raises(ValueError) as error:
        +        function(conda=["scipy", package])(identity)
        +    assert "conda[1]" in str(error.value)
        +    assert repr(package) in str(error.value)
        +
        +
        +@pytest.mark.parametrize("kind", ["pip", "conda"])
        +@pytest.mark.parametrize("package", [None, 42, ["numpy"]])
        +def test_requirement_must_be_a_string(kind, package):
        +    with pytest.raises(TypeError, match=rf"{kind}\[1\] must be a string"):
        +        function(**{kind: ["numpy", package]})(identity)
        +
        +
        +@pytest.mark.parametrize(
        +    "package",
        +    [
        +        "numpy",
        +        "torch>=2.0,<3",
        +        'requests[security,socks]>=2; python_version >= "3.10"',
        +        "numpy (>=1.26, <3)",
        +        "six @ https://example.com/six-1.16.0.tar.gz",
        +        "six @ git+https://github.com/benjaminp/six.git@main",
        +        "https://example.com/six-1.16.0.tar.gz",
        +        "git+https://github.com/benjaminp/six.git@main",
        +        "git+ssh://git@github.com/benjaminp/six.git@main",
        +    ],
        +)
        +def test_supported_pip_requirements_are_preserved(package):
        +    definition = function(pip=[package])(identity)
        +    assert definition.registration_request.runtime.environment.packages == (package,)
        +
        +
        +@pytest.mark.parametrize(
        +    "package",
        +    [
        +        "numpy",
        +        "numpy=1.26",
        +        "numpy>=1.26,<3",
        +        "numpy=1.26=py310_0",
        +        "numpy 1.26 py310_0",
        +        "conda-forge::numpy>=1.26",
        +        "conda-forge/linux-64::numpy>=1.26",
        +        "numpy[version='>=1.26,<3',build='py310*']",
        +    ],
        +)
        +def test_supported_conda_requirements_are_preserved(package):
        +    definition = function(conda=[package])(identity)
        +    assert definition.registration_request.runtime.environment.packages == (package,)
        +
        +
        +def test_requirements_still_sort_and_deduplicate():
        +    definition = function(pip=["torch>=2", "numpy", "torch>=2"])(identity)
        +    assert definition.registration_request.runtime.environment.packages == (
        +        "numpy",
        +        "torch>=2",
        +    )
        +
        +
        +def test_deprecated_udf_alias_validates_requirements():
        +    with pytest.warns(DeprecationWarning, match="use lancedb.function"):
        +        with pytest.raises(ValueError, match=r"pip\[0\]"):
        +            udf(pip=["torch>=2.0,,<3"])(identity)
        +
        +
        +def test_direct_function_definition_validates_requirements():
        +    with pytest.raises(ValueError, match=r"pip\[0\]"):
        +        FunctionDefinition(
        +            identity,
        +            name=None,
        +            input_schema=None,
        +            output_schema=None,
        +            pip=("torch>=2.0,,<3",),
        +            env={},
        +            python_version=None,
        +        )
        diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py
        index 443fdebc4..ec6060db3 100644
        --- a/python/python/tests/test_hybrid_query.py
        +++ b/python/python/tests/test_hybrid_query.py
        @@ -81,6 +81,31 @@ async def test_async_hybrid_query_with_row_ids(table: AsyncTable):
             assert result["_rowid"].to_pylist() == [0, 3]
         
         
        +def test_hybrid_fragment_constraints_fail_loud(sync_table: Table):
        +    query = (
        +        sync_table.search("dog", query_type="hybrid")
        +        .vector([0.5, -0.5])
        +        .fragment_ids([0])
        +    )
        +
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        query.to_arrow()
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        query.explain_plan()
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_hybrid_fragment_constraints_fail_loud(table: AsyncTable):
        +    query = (
        +        table.query().nearest_to([0.5, -0.5]).nearest_to_text("dog").fragment_ids([0])
        +    )
        +
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        await query.to_arrow()
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        await query.analyze_plan()
        +
        +
         @pytest.mark.asyncio
         async def test_async_hybrid_query_filters(table: AsyncTable):
             # test that query params are passed down from the regular builder to
        diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py
        index 1b252f993..c38948eb2 100644
        --- a/python/python/tests/test_index.py
        +++ b/python/python/tests/test_index.py
        @@ -3,11 +3,13 @@
         
         from datetime import timedelta
         import random
        +import struct
         from typing import get_args, get_type_hints
         
         import pyarrow as pa
         import pytest
         import pytest_asyncio
        +import lancedb
         from lancedb import AsyncConnection, AsyncTable, connect_async
         from lancedb.index import (
             BTree,
        @@ -22,6 +24,9 @@ from lancedb.index import (
             LabelList,
             Fm,
             NGram,
        +    ZoneMap,
        +    RTree,
        +    ScalarPlugin,
             HnswPq,
             HnswSq,
             HnswFlat,
        @@ -88,7 +93,7 @@ async def binary_table(db_async):
         @pytest.mark.asyncio
         async def test_create_index_async_returns_done_job(some_table: AsyncTable):
             job = await some_table.create_index_async("id", config=BTree())
        -    assert job.id is None
        +    assert job.id() is None
             assert await job.wait() is None
             assert len(await some_table.list_indices()) == 1
             await job.cancel()
        @@ -249,6 +254,388 @@ async def test_create_fm_index(some_table: AsyncTable):
             assert indices[0].columns == ["data"]
         
         
        +POINT_TYPE = pa.struct([("x", pa.float64()), ("y", pa.float64())])
        +POLYGON_TYPE = pa.list_(pa.field("rings", pa.list_(pa.field("vertices", POINT_TYPE))))
        +
        +
        +def geoarrow_field(name: str, extension: str, data_type: pa.DataType) -> pa.Field:
        +    return pa.field(
        +        name,
        +        data_type,
        +        metadata={
        +            "ARROW:extension:name": extension,
        +            "ARROW:extension:metadata": "{}",
        +        },
        +    )
        +
        +
        +# The triangle's bounding box covers the 25 grid points with x <= 4 and y <= 4,
        +# but only the 15 with x + y <= 4 intersect the triangle itself.
        +TRIANGLE = "ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))')"
        +INTERSECTS_TRIANGLE = f"ST_Intersects(geom, {TRIANGLE})"
        +TRIANGLE_IDS = [10 * y + x for y in range(10) for x in range(10) if x + y <= 4]
        +
        +
        +def grid_points(nrows: int) -> pa.Table:
        +    """A grid of GeoArrow points in which row ``10 * y + x`` sits at ``(x, y)``."""
        +    ids = list(range(nrows))
        +    geom = pa.StructArray.from_arrays(
        +        [
        +            pa.array([float(i % 10) for i in ids]),
        +            pa.array([float(i // 10) for i in ids]),
        +        ],
        +        names=["x", "y"],
        +    )
        +    schema = pa.schema(
        +        [
        +            pa.field("id", pa.int64()),
        +            geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
        +            pa.field("vector", pa.list_(pa.float32(), DIM)),
        +        ]
        +    )
        +    return pa.Table.from_arrays(
        +        [pa.array(ids, pa.int64()), geom, sample_fixed_size_list_array(nrows, DIM)],
        +        schema=schema,
        +    )
        +
        +
        +@pytest_asyncio.fixture
        +async def point_table(db_async):
        +    return await db_async.create_table("point_table", grid_points(100))
        +
        +
        +async def query_ids(query) -> list:
        +    return (await query.to_arrow())["id"].to_pylist()
        +
        +
        +@pytest.mark.asyncio
        +async def test_create_rtree_index(point_table: AsyncTable):
        +    assert sorted(await query_ids(point_table.query().where(INTERSECTS_TRIANGLE))) == (
        +        TRIANGLE_IDS
        +    )
        +
        +    await point_table.create_index("geom", config=RTree())
        +    indices = await point_table.list_indices()
        +    assert len(indices) == 1
        +    assert indices[0].name == "geom_idx"
        +    assert indices[0].index_type == "RTree"
        +    assert indices[0].columns == ["geom"]
        +    stats = await point_table.index_stats("geom_idx")
        +    assert stats.index_type == "RTREE"
        +    assert stats.num_indexed_rows == 100
        +    assert stats.num_unindexed_rows == 0
        +
        +    # The index narrows the scan to the bounding box; the exact predicate then
        +    # drops the candidates that fall outside the triangle.
        +    query = point_table.query().where(INTERSECTS_TRIANGLE)
        +    assert "ScalarIndexQuery" in await query.explain_plan(True)
        +    assert sorted(await query_ids(query)) == TRIANGLE_IDS
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "predicate, expected_ids",
        +    [
        +        (INTERSECTS_TRIANGLE, TRIANGLE_IDS),
        +        (f"ST_Within(geom, {TRIANGLE})", [11, 12, 21]),
        +        (f"ST_CoveredBy(geom, {TRIANGLE})", TRIANGLE_IDS),
        +        (
        +            f"ST_Touches(geom, {TRIANGLE})",
        +            [0, 1, 2, 3, 4, 10, 13, 20, 22, 30, 31, 40],
        +        ),
        +        (f"ST_Intersects(geom, {TRIANGLE}) AND id > 20", [21, 22, 30, 31, 40]),
        +        ("ST_Intersects(geom, ST_Point(3.0, 3.0))", [33]),
        +        ("ST_Contains(geom, ST_Point(3.0, 3.0))", [33]),
        +        ("ST_Covers(geom, ST_Point(3.0, 3.0))", [33]),
        +    ],
        +)
        +async def test_rtree_index_accelerates_spatial_filters(
        +    point_table: AsyncTable, predicate: str, expected_ids: list
        +):
        +    unindexed = sorted(await query_ids(point_table.query().where(predicate)))
        +    assert unindexed == expected_ids
        +
        +    await point_table.create_index("geom", config=RTree())
        +    query = point_table.query().where(predicate)
        +    assert "ScalarIndexQuery" in await query.explain_plan(True)
        +    assert sorted(await query_ids(query)) == expected_ids
        +
        +
        +@pytest.mark.asyncio
        +async def test_rtree_index_prefilters_vector_search(point_table: AsyncTable):
        +    await point_table.create_index("geom", config=RTree())
        +    # Row 99 sits outside the triangle, and its nearest vectors are rows 98, 97, ...
        +    far_corner = list(range(99 * DIM, 100 * DIM))
        +
        +    prefiltered = point_table.query().nearest_to(far_corner).where(INTERSECTS_TRIANGLE)
        +    assert "ScalarIndexQuery" in await prefiltered.explain_plan(True)
        +    assert await query_ids(prefiltered.limit(5)) == [40, 31, 30, 22, 21]
        +
        +    postfiltered = (
        +        point_table.query()
        +        .nearest_to(far_corner)
        +        .where(INTERSECTS_TRIANGLE)
        +        .postfilter()
        +        .limit(5)
        +    )
        +    assert await query_ids(postfiltered) == []
        +
        +
        +def square(corner: float) -> list:
        +    """A 2 x 2 square polygon with its lower left corner at ``(corner, corner)``."""
        +    ring = [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]
        +    return [[{"x": corner + x, "y": corner + y} for x, y in ring]]
        +
        +
        +@pytest_asyncio.fixture
        +async def polygon_table(db_async):
        +    """Ten overlapping squares; row ``i`` covers ``(i, i)`` to ``(i + 2, i + 2)``."""
        +    schema = pa.schema(
        +        [
        +            pa.field("id", pa.int64()),
        +            geoarrow_field("area", "geoarrow.polygon", POLYGON_TYPE),
        +        ]
        +    )
        +    data = pa.Table.from_arrays(
        +        [
        +            pa.array(range(10), pa.int64()),
        +            pa.array([square(float(i)) for i in range(10)], POLYGON_TYPE),
        +        ],
        +        schema=schema,
        +    )
        +    return await db_async.create_table("polygons", data)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "predicate, expected_ids",
        +    [
        +        ("ST_Intersects(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
        +        ("ST_Contains(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
        +        ("ST_Covers(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
        +        ("ST_Crosses(area, ST_GeomFromText('LINESTRING (2.5 2.5, 2.5 10)'))", [1, 2]),
        +        (
        +            "ST_Overlaps(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
        +            [2, 4],
        +        ),
        +        (
        +            "ST_Touches(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
        +            [1, 5],
        +        ),
        +    ],
        +)
        +async def test_create_rtree_index_on_polygons(
        +    polygon_table: AsyncTable, predicate: str, expected_ids: list
        +):
        +    assert sorted(await query_ids(polygon_table.query().where(predicate))) == (
        +        expected_ids
        +    )
        +
        +    await polygon_table.create_index("area", config=RTree(page_size=2))
        +    assert (await polygon_table.list_indices())[0].index_type == "RTree"
        +
        +    query = polygon_table.query().where(predicate)
        +    assert "ScalarIndexQuery" in await query.explain_plan(True)
        +    assert sorted(await query_ids(query)) == expected_ids
        +
        +
        +@pytest.mark.asyncio
        +async def test_rtree_index_with_null_geometries(db_async):
        +    # Every third row has no geometry; the others sit on the diagonal at (i, i).
        +    geom = pa.array(
        +        [None if i % 3 == 0 else {"x": float(i), "y": float(i)} for i in range(10)],
        +        POINT_TYPE,
        +    )
        +    schema = pa.schema(
        +        [
        +            pa.field("id", pa.int64()),
        +            geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
        +        ]
        +    )
        +    table = await db_async.create_table(
        +        "nulls",
        +        pa.Table.from_arrays([pa.array(range(10), pa.int64()), geom], schema=schema),
        +    )
        +    box = "ST_GeomFromText('POLYGON ((-1 -1, 1.5 -1, 1.5 1.5, -1 1.5, -1 -1))')"
        +    expected = {
        +        "geom IS NULL": [0, 3, 6, 9],
        +        "geom IS NOT NULL": [1, 2, 4, 5, 7, 8],
        +        # Row 0 is inside the box but has no geometry, so it matches neither.
        +        f"ST_Intersects(geom, {box})": [1],
        +        f"NOT ST_Intersects(geom, {box})": [2, 4, 5, 7, 8],
        +    }
        +    for predicate, ids in expected.items():
        +        assert sorted(await query_ids(table.query().where(predicate))) == ids
        +
        +    await table.create_index("geom", config=RTree())
        +    for predicate, ids in expected.items():
        +        assert sorted(await query_ids(table.query().where(predicate))) == ids
        +    for predicate in ["geom IS NULL", f"ST_Intersects(geom, {box})"]:
        +        assert "ScalarIndexQuery" in await table.query().where(predicate).explain_plan(
        +            True
        +        )
        +
        +
        +@pytest.mark.asyncio
        +async def test_create_rtree_index_on_wkb(db_async):
        +    """GeoParquet and GeoPandas data usually arrives as well-known binary."""
        +
        +    def wkb_point(x: float, y: float) -> bytes:
        +        # Byte order (1 = little endian), geometry type (1 = point), x, y.
        +        return struct.pack("= 90").to_arrow()
        +    assert sorted(result["id"].to_pylist()) == list(range(90, 100))
        +
        +
        +def plugin_table_data():
        +    return pa.table(
        +        {"id": [1, 2, 3, 4], "text": ["abc", "xyz", None, ""]},
        +        schema=pa.schema([("id", pa.int32()), ("text", pa.string())]),
        +    )
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "index_type, params, column, expected_type, predicate, expected_ids",
        +    [
        +        ("ZoneMap", None, "id", "ZoneMap", "id >= 2 AND id < 4", [2, 3]),
        +        ("  BTREE ", None, "id", "BTree", "id = 3", [3]),
        +        (
        +            "bloomfilter",
        +            {"number_of_items": 2, "probability": 0.01},
        +            "text",
        +            "BloomFilter",
        +            "text = 'abc'",
        +            [1],
        +        ),
        +        (
        +            "BloomFilter",
        +            '{"number_of_items": 2}',
        +            "text",
        +            "BloomFilter",
        +            "text = 'abc'",
        +            [1],
        +        ),
        +    ],
        +)
        +async def test_create_scalar_plugin_index(
        +    db_async, index_type, params, column, expected_type, predicate, expected_ids
        +):
        +    # Lance's built-in plugins, created by name, are listed with the same type
        +    # as their dedicated configs and serve the filters those configs serve.
        +    table = await db_async.create_table("plugin_table", plugin_table_data())
        +    config = ScalarPlugin(index_type, params)
        +    await table.create_index(column, config=config, name="plugin_idx")
        +
        +    indices = await table.list_indices()
        +    assert [(i.name, i.index_type, i.columns) for i in indices] == [
        +        ("plugin_idx", expected_type, [column])
        +    ]
        +    stats = await table.index_stats("plugin_idx")
        +    assert stats.num_indexed_rows == 4
        +
        +    query = table.query().where(predicate)
        +    assert "ScalarIndexQuery" in await query.explain_plan()
        +    result = await query.to_arrow()
        +    assert sorted(result["id"].to_pylist()) == expected_ids
        +
        +
        +@pytest.mark.asyncio
        +async def test_scalar_plugin_without_lancedb_type_lists_plugin_name(db_async):
        +    data = pa.table({"text": ["alpha beta", "beta gamma", "gamma delta"]})
        +    table = await db_async.create_table("minhash_table", data)
        +    await table.create_index("text", config=ScalarPlugin("minhashlsh"))
        +
        +    indices = await table.list_indices()
        +    assert len(indices) == 1
        +    assert indices[0].index_type == "MinHashLsh"
        +    assert 'index_type="MinHashLsh"' in repr(indices[0])
        +    stats = await table.index_stats(indices[0].name)
        +    assert stats.index_type == "MinHashLsh"
        +
        +
        +def test_scalar_plugin_sync_table_and_job(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("plugin_table", plugin_table_data())
        +
        +    table.create_index("id", config=ScalarPlugin("zonemap"))
        +    job = table.create_index_async(
        +        "text",
        +        config=ScalarPlugin("bloomfilter", {"probability": 0.01}),
        +        name="text_bloom",
        +    )
        +    job.wait()
        +
        +    types = {index.name: index.index_type for index in table.list_indices()}
        +    assert types == {"id_idx": "ZoneMap", "text_bloom": "BloomFilter"}
        +    assert "ScalarIndexQuery" in table.search().where("text = 'abc'").explain_plan()
        +
        +
        +@pytest.mark.parametrize(
        +    "kwargs, error, match",
        +    [
        +        ({"index_type": ""}, ValueError, "must not be empty"),
        +        ({"index_type": "  "}, ValueError, "must not be empty"),
        +        ({"index_type": None}, TypeError, "index_type must be a str"),
        +        ({"index_type": "zonemap", "params": "[1]"}, ValueError, "got list"),
        +        ({"index_type": "zonemap", "params": "null"}, ValueError, "got NoneType"),
        +        ({"index_type": "zonemap", "params": "{x"}, ValueError, "not valid JSON"),
        +        ({"index_type": "zonemap", "params": [1]}, TypeError, "got list"),
        +        ({"index_type": "zonemap", "params": 1}, TypeError, "got int"),
        +    ],
        +)
        +def test_scalar_plugin_rejects_invalid_config(kwargs, error, match):
        +    with pytest.raises(error, match=match):
        +        ScalarPlugin(**kwargs)
        +
        +
        +@pytest.mark.asyncio
        +async def test_scalar_plugin_errors_reach_the_caller(db_async):
        +    table = await db_async.create_table("plugin_table", plugin_table_data())
        +
        +    # The native layer checks the params again, after the dataclass is mutated.
        +    config = ScalarPlugin("zonemap")
        +    config.params = "[1]"
        +    with pytest.raises(ValueError, match="must be a JSON object, got an array"):
        +        await table.create_index("id", config=config)
        +
        +    with pytest.raises(
        +        ValueError, match="No scalar index plugin found for name 'nosuchplugin'"
        +    ):
        +        await table.create_index("id", config=ScalarPlugin("NoSuchPlugin"))
        +    with pytest.raises(ValueError, match="ngram index can only be created on a Utf8"):
        +        await table.create_index("id", config=ScalarPlugin("ngram"))
        +    with pytest.raises(RuntimeError, match='invalid type: string "many"'):
        +        await table.create_index(
        +            "text",
        +            config=ScalarPlugin("bloomfilter", {"number_of_items": "many"}),
        +        )
        +    assert await table.list_indices() == []
        +
        +
         @pytest.mark.asyncio
         async def test_create_bitmap_index(some_table: AsyncTable):
             await some_table.create_index("id", config=Bitmap())
        @@ -591,9 +1126,53 @@ def test_index_statistics_index_type_lists_all_supported_values():
                 "BITMAP",
                 "LABEL_LIST",
                 "NGRAM",
        +        "ZONEMAP",
        +        "RTREE",
             }
         
             assert (
                 set(get_args(get_type_hints(IndexStatistics)["index_type"]))
                 == expected_index_types
             )
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("background", [False, True])
        +@pytest.mark.parametrize(
        +    "column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))]
        +)
        +async def test_index_exist_ok_preserves_existing_index(
        +    some_table, background, column, config
        +):
        +    await some_table.create_index(column, config=config, exist_ok=True)
        +    version = await some_table.version()
        +    original = await some_table.list_indices()
        +    if background:
        +        job = await some_table.create_index_async(
        +            column, config=config, replace=True, exist_ok=True
        +        )
        +        await job.wait()
        +    else:
        +        await some_table.create_index(
        +            column, config=config, replace=True, exist_ok=True
        +        )
        +    assert await some_table.version() == version
        +    assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [
        +        (i.name, i.index_type) for i in original
        +    ]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("background", [False, True])
        +async def test_named_index_exist_ok_checks_before_column_validation(
        +    some_table, background
        +):
        +    await some_table.create_index("id", config=BTree(), name="kept")
        +    version = await some_table.version()
        +    method = some_table.create_index_async if background else some_table.create_index
        +    result = await method("missing", config=BTree(), name="kept", exist_ok=True)
        +    if background:
        +        assert result.id() is None
        +        await result.wait()
        +    assert await some_table.version() == version
        +    assert [index.name for index in await some_table.list_indices()] == ["kept"]
        diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py
        index c3189cbad..e1b844969 100644
        --- a/python/python/tests/test_job.py
        +++ b/python/python/tests/test_job.py
        @@ -2,17 +2,253 @@
         # SPDX-FileCopyrightText: Copyright The LanceDB Authors
         
         import asyncio
        +import json
         import time
         from datetime import timedelta
        +from types import SimpleNamespace
         from unittest.mock import AsyncMock, MagicMock
         
         import pytest
        +import pyarrow as pa
         
         from lancedb.exceptions import JobCancelledError, JobFailedError
        -from lancedb.job import AsyncJob, Job, _progress_eta
        +from lancedb.db import DBConnection
        +from lancedb.job import AsyncJob, Job, JobState, _progress_eta
         from lancedb.remote.errors import HttpError, RetryError
         
         
        +@pytest.mark.parametrize("job_class", [AsyncJob, Job])
        +def test_job_handle_data_access_uses_methods(job_class):
        +    assert all(
        +        name.startswith("_")
        +        for name, member in vars(job_class).items()
        +        if isinstance(member, property)
        +    )
        +    job = job_class(None)
        +    expected = {
        +        "id": None,
        +        "state": "finished",
        +        "job_type": None,
        +        "creation_ms": None,
        +        "spec": None,
        +        "result": None,
        +        "failure": None,
        +    }
        +    for name, value in expected.items():
        +        assert callable(getattr(job, name))
        +        assert getattr(job, name)() == value
        +        assert getattr(job, f"_{name}") == value
        +
        +
        +@pytest.fixture(params=[False, True], ids=["async", "sync"])
        +def job_snapshot(request):
        +    def create(inner):
        +        job = AsyncJob(inner)
        +        if request.param:
        +            job = Job(job)
        +
        +        async def call(method="checkout_latest"):
        +            if request.param:
        +                return await asyncio.to_thread(getattr(job, method))
        +            return await getattr(job, method)()
        +
        +        return job, call
        +
        +    return create
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("method", ["checkout_latest", "refresh"])
        +@pytest.mark.parametrize("state", ["finished", "failed", "cancelled", "future_state"])
        +async def test_job_checkout_latest_refreshes_the_complete_snapshot(
        +    job_snapshot, method, state
        +):
        +    spec = {"column": "vector", "initialization": list(range(1000))}
        +    result = {"rows_assigned": 1000} if state == "finished" else None
        +    failure = SimpleNamespace(message="worker failed") if state == "failed" else None
        +    description = SimpleNamespace(
        +        creation_ms=2000, spec=spec, result=result, failure=failure
        +    )
        +    inner = SimpleNamespace(
        +        id="operation-1",
        +        _state=None,
        +        _description=None,
        +        job_type=None,
        +        status=AsyncMock(),
        +    )
        +
        +    async def observe():
        +        inner._state = state
        +        inner.job_type = "refresh_column"
        +        inner._description = description
        +        inner.job_id = "attempt-2"
        +        inner.operation_id = "operation-1"
        +        inner.attempt = 2
        +        inner.retry_of = "attempt-1"
        +        inner.lifecycle_state = str(JobState(state))
        +        inner.source_table_version = 7
        +        inner.execution_epoch = 3
        +
        +    inner.refresh = AsyncMock(side_effect=observe)
        +    job, call = job_snapshot(inner)
        +    assert job.state() is None
        +    assert job.job_id() == "operation-1"
        +    assert job.lifecycle_state() is None
        +    assert job.job_type() is None
        +    assert job.creation_ms() is None
        +    assert job.spec() is None
        +    assert job.result() is None
        +    assert job.failure() is None
        +    inner.refresh.assert_not_called()
        +
        +    assert await call(method) is None
        +    assert job.state() == state
        +    assert job.job_type() == "refresh_column"
        +    assert job.creation_ms() == 2000
        +    assert job.spec() is spec
        +    assert job.result() is result
        +    assert job.failure() is failure
        +    assert job.id() == "operation-1"
        +    assert job.job_id() == "attempt-2"
        +    assert job.operation_id() == "operation-1"
        +    assert job.attempt() == 2
        +    assert job.retry_of() == "attempt-1"
        +    assert job.lifecycle_state() == JobState(state)
        +    assert job.source_table_version() == 7
        +    assert job.execution_epoch() == 3
        +    inner.refresh.assert_awaited_once_with()
        +    inner.status.assert_not_called()
        +
        +
        +@pytest.mark.asyncio
        +async def test_job_checkout_latest_keeps_cached_details_on_request_error(job_snapshot):
        +    error = HttpError("not found", "req-job", 404)
        +    description = SimpleNamespace(
        +        creation_ms=2000, spec={"column": "vector"}, result=None, failure=None
        +    )
        +    inner = SimpleNamespace(
        +        _state="running",
        +        _description=description,
        +        job_type="refresh_column",
        +        refresh=AsyncMock(side_effect=error),
        +    )
        +    job, call = job_snapshot(inner)
        +
        +    with pytest.raises(HttpError) as exc:
        +        await call()
        +    assert exc.value is error
        +    assert job.state() == "running"
        +    assert job.spec() is description.spec
        +    assert job.result() is None
        +    assert job.failure() is None
        +    inner.refresh.assert_awaited_once_with()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_job_checkout_latest_preserves_refresh_overrides(sync, monkeypatch):
        +    job = AsyncJob(None)
        +    if sync:
        +        job = Job(job)
        +    refresh = MagicMock() if sync else AsyncMock()
        +    monkeypatch.setattr(job, "refresh", refresh)
        +
        +    if sync:
        +        assert await asyncio.to_thread(job.checkout_latest) is None
        +    else:
        +        assert await job.checkout_latest() is None
        +        refresh.assert_awaited_once_with()
        +    refresh.assert_called_once_with()
        +
        +
        +@pytest.mark.asyncio
        +async def test_job_checkout_latest_for_completed_local_jobs(job_snapshot):
        +    job, call = job_snapshot(None)
        +    assert await call() is None
        +    assert job.state() == "finished"
        +    assert job.job_type() is None
        +    assert job.spec() is None
        +    assert job.result() is None
        +    assert job.failure() is None
        +    assert Job(None).checkout_latest() is None
        +
        +
        +@pytest.mark.parametrize("sync", [False, True])
        +def test_local_jobs_retain_identity_and_typed_state(sync):
        +    job = AsyncJob(None)
        +    if sync:
        +        job = Job(job)
        +    assert job.job_id() == job.operation_id()
        +    assert job.job_id() == job.job_id()
        +    assert job.attempt() == 1
        +    assert job.retry_of() is None
        +    assert job.lifecycle_state() is JobState.SUCCEEDED
        +
        +
        +def test_unknown_job_state_is_preserved_without_becoming_success():
        +    state = JobState("future_publication_state")
        +    assert state.value == "future_publication_state"
        +    assert str(state) == "future_publication_state"
        +    assert not state.is_terminal
        +    assert not state.is_success
        +
        +
        +@pytest.mark.asyncio
        +async def test_history_follows_page_tokens():
        +    first = pa.table({"event_seq": [2, 1]}).replace_schema_metadata(
        +        {b"lancedb.job_coordinator.page_token": b"next"}
        +    )
        +    last = pa.table({"event_seq": [0]})
        +    inner = SimpleNamespace(events=AsyncMock(side_effect=[first, last]))
        +    pages = [page async for page in AsyncJob(inner).history(limit=2)]
        +    assert [page["event_seq"].to_pylist() for page in pages] == [[2, 1], [0]]
        +    assert inner.events.call_args_list[1].kwargs["page_token"] == "next"
        +
        +
        +@pytest.mark.parametrize("sync", [False, True])
        +def test_job_repr_bounds_large_payloads_without_fetching(sync):
        +    spec = {"initialization": list(range(100000)), "source": "x" * 100000}
        +    result = {"rows_computed": 7, "details": [{"data": b"x" * 10000}] * 1000}
        +    inner = SimpleNamespace(
        +        id="job-repr",
        +        _state="failed",
        +        job_type="function_refresh",
        +        _description=SimpleNamespace(
        +            creation_ms=2000,
        +            spec=spec,
        +            result=result,
        +            failure="worker failed " + "x" * 10000,
        +        ),
        +    )
        +    job = AsyncJob(inner)
        +    if sync:
        +        job = Job(job)
        +    rendered = repr(job)
        +    assert len(rendered) < 1600
        +    assert len(rendered.splitlines()) <= 10
        +    assert "id='job-repr'" in rendered
        +    assert "state='failed'" in rendered
        +    assert "job_type='function_refresh'" in rendered
        +    assert "rows_computed" in rendered
        +    assert "worker failed" in rendered
        +    assert "..." in rendered
        +    assert len(repr(job.status)) < 1700
        +    assert job.spec() is spec
        +    assert job.result() is result
        +    assert len(job.spec()["initialization"]) == 100000
        +
        +
        +@pytest.mark.parametrize("sync", [False, True])
        +def test_job_repr_handles_unobserved_and_local_jobs(sync):
        +    unobserved = AsyncJob(SimpleNamespace(id="job-pending", _state=None))
        +    local = AsyncJob(None)
        +    if sync:
        +        unobserved, local = Job(unobserved), Job(local)
        +    assert "id='job-pending', not refreshed" in repr(unobserved)
        +    assert "state='finished'" in repr(local)
        +    assert "failure=" not in repr(local)
        +
        +
         @pytest.fixture(params=["async", "sync"])
         def wait_job(request):
             async def wait(inner, timeout=None, result_decoder=None):
        @@ -683,15 +919,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing(
         
         
         @pytest.mark.asyncio
        -async def test_wait_progress_false_keeps_legacy_inner_wait_call():
        +@pytest.mark.parametrize("progress", [False, None])
        +async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress):
             class NoProgressArgument:
                 id = "job-legacy"
        -        job_type = None
        +
        +        @property
        +        def job_type(self):
        +            raise AssertionError("quiet waits must not inspect progress metadata")
         
                 async def wait(self):
                     return None
         
        -    assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None
        +    assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None
        +
        +
        +class _RegistrationQuery:
        +    id = "registration-query"
        +    job_type = "query"
        +    _description = None
        +
        +    def __init__(self, error=None):
        +        self.ready = asyncio.Event()
        +        self.error = error
        +        self.state = "running"
        +        self.wait_calls = 0
        +        self.cancel_calls = 0
        +
        +    async def status(self):
        +        return self.state
        +
        +    async def wait(self, progress=None):
        +        self.wait_calls += 1
        +        await self.ready.wait()
        +        if self.error is not None:
        +            self.state = (
        +                "cancelled" if isinstance(self.error, JobCancelledError) else "failed"
        +            )
        +            raise self.error
        +        self.state = "finished"
        +        return '{"version": "1"}'
        +
        +    async def cancel(self):
        +        self.cancel_calls += 1
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch):
        +    monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0)
        +    inner = _RegistrationQuery()
        +    job = AsyncJob(inner, json.loads)
        +    updates = []
        +
        +    def observe(snapshot):
        +        updates.append(snapshot)
        +        if len(updates) == 2:
        +            inner.ready.set()
        +
        +    if sync:
        +        result = await asyncio.to_thread(Job(job).wait, progress=observe)
        +    else:
        +        result = await job.wait(progress=observe)
        +    assert result == {"version": "1"}
        +    assert inner.wait_calls == 1
        +    assert inner.cancel_calls == 0
        +    assert updates[0]["state"] == "running"
        +    assert updates[-1]["state"] == "finished"
        +    assert all(snapshot["job_id"] == inner.id for snapshot in updates)
        +    elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates]
        +    assert elapsed == sorted(elapsed)
        +    assert elapsed[0] >= 0
        +    assert all("phase" not in snapshot for snapshot in updates)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "error",
        +    [
        +        JobFailedError("bake failed", job_id="registration-query"),
        +        JobCancelledError("cancelled"),
        +    ],
        +)
        +async def test_query_progress_preserves_terminal_exceptions(error):
        +    inner = _RegistrationQuery(error)
        +    inner.ready.set()
        +    updates = []
        +    with pytest.raises(type(error)) as raised:
        +        await AsyncJob(inner).wait(progress=updates.append)
        +    assert raised.value is error
        +    assert updates[-1]["state"] == inner.state
        +    assert inner.wait_calls == 1
        +
        +
        +@pytest.mark.asyncio
        +async def test_query_progress_display_has_no_row_counter_and_closes_on_failure(
        +    monkeypatch,
        +):
        +    tqdm_module = pytest.importorskip("tqdm.auto")
        +    bar = SimpleNamespace(
        +        n=0,
        +        total=None,
        +        update=MagicMock(),
        +        set_postfix_str=MagicMock(),
        +        close=MagicMock(),
        +    )
        +    constructor = MagicMock(return_value=bar)
        +    monkeypatch.setattr(tqdm_module, "tqdm", constructor)
        +    inner = _RegistrationQuery(JobFailedError("bake failed"))
        +    inner.ready.set()
        +
        +    with pytest.raises(JobFailedError, match="bake failed"):
        +        await AsyncJob(inner).wait(progress=True)
        +    assert "elapsed" in constructor.call_args.kwargs["bar_format"]
        +    assert "rows" not in str(constructor.call_args)
        +    assert bar.set_postfix_str.call_args.args == ("failed",)
        +    bar.close.assert_called_once_with()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("failed", [False, True])
        +@pytest.mark.parametrize("observer_error", ["status", "callback"])
        +async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure(
        +    failed, observer_error, caplog
        +):
        +    error = (
        +        JobFailedError("bake failed", job_id="registration-query") if failed else None
        +    )
        +    inner = _RegistrationQuery(error)
        +    inner.ready.set()
        +    if observer_error == "status":
        +        inner.status = AsyncMock(side_effect=RuntimeError("observer failed"))
        +
        +    def observe(snapshot):
        +        if observer_error == "callback":
        +            raise RuntimeError("observer failed")
        +
        +    job = AsyncJob(inner, json.loads)
        +    if failed:
        +        with pytest.raises(JobFailedError) as raised:
        +            await job.wait(progress=observe)
        +        assert raised.value is error
        +    else:
        +        assert await job.wait(progress=observe) == {"version": "1"}
        +    assert inner.wait_calls == 1
        +    assert inner.cancel_calls == 0
        +    assert "job progress observer failed" in caplog.text
        +
        +
        +@pytest.mark.asyncio
        +async def test_query_progress_timeout_keeps_registration_available_on_same_handle():
        +    inner = _RegistrationQuery()
        +    job = AsyncJob(inner, json.loads)
        +    updates = []
        +    with pytest.raises(TimeoutError, match="keep this handle"):
        +        await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append)
        +    assert inner.state == "running"
        +    assert inner.cancel_calls == 0
        +    inner.ready.set()
        +    assert await job.wait(progress=updates.append) == {"version": "1"}
        +    assert inner.wait_calls == 2
        +    assert updates[-1]["state"] == "finished"
        +
        +
        +@pytest.mark.parametrize("refresh_lock", [False, True])
        +def test_blocking_create_function_forwards_progress_to_registration_handle(
        +    refresh_lock,
        +):
        +    connection = MagicMock()
        +    definition = object()
        +    progress = object()
        +    result = DBConnection.create_function(
        +        connection, definition, refresh_lock=refresh_lock, progress=progress
        +    )
        +    connection.create_function_async.assert_called_once_with(
        +        definition,
        +        secrets=None,
        +        exist_ok=False,
        +        namespace_path=None,
        +        refresh_lock=refresh_lock,
        +    )
        +    connection.create_function_async.return_value.wait.assert_called_once_with(
        +        progress=progress
        +    )
        +    assert result is connection.create_function_async.return_value.wait.return_value
        +
        +
        +@pytest.mark.parametrize("progress", [False, None])
        +def test_blocking_create_function_preserves_quiet_wait_call(progress):
        +    connection = MagicMock()
        +    result = DBConnection.create_function(connection, object(), progress=progress)
        +    connection.create_function_async.return_value.wait.assert_called_once_with()
        +    assert result is connection.create_function_async.return_value.wait.return_value
         
         
         @pytest.mark.asyncio
        @@ -706,3 +1125,298 @@ async def test_query_wait_timeout_requires_keeping_original_handle():
             assert "continues on the server" in message
             assert "keep this handle to continue waiting" in message
             assert "db.open_job" not in message
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_stats_returns_fresh_report_without_waiting_or_printing(sync, capsys):
        +    reports = [
        +        None,
        +        "Function job: finished\nWorker utilization: unavailable\n",
        +        "Function job: finished\nWorker utilization: 25.0%\n",
        +    ]
        +    inner = SimpleNamespace(
        +        stats=AsyncMock(side_effect=reports),
        +        wait=AsyncMock(),
        +        cancel=AsyncMock(),
        +    )
        +    job = AsyncJob(inner)
        +    for expected in reports:
        +        actual = await asyncio.to_thread(Job(job).stats) if sync else await job.stats()
        +        assert actual == expected
        +    inner.wait.assert_not_awaited()
        +    inner.cancel.assert_not_awaited()
        +    assert capsys.readouterr().out == ""
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_stats_preserves_errors_and_rejects_untracked_jobs(sync):
        +    error = RuntimeError("run reports are unavailable on this server")
        +    job = AsyncJob(SimpleNamespace(stats=AsyncMock(side_effect=error)))
        +    with pytest.raises(RuntimeError) as exc:
        +        if sync:
        +            await asyncio.to_thread(Job(job).stats)
        +        else:
        +            await job.stats()
        +    assert exc.value is error
        +    with pytest.raises(NotImplementedError, match="server-side Function job"):
        +        if sync:
        +            Job(None).stats()
        +        else:
        +            await AsyncJob(None).stats()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path):
        +    trace = {
        +        "traceEvents": [{"ph": "X", "ts": 0, "dur": 1000}],
        +        "metadata": {"partial": True},
        +    }
        +    inner = SimpleNamespace(
        +        timeline=AsyncMock(return_value=json.dumps(trace)),
        +        wait=AsyncMock(),
        +        cancel=AsyncMock(),
        +    )
        +    job = AsyncJob(inner)
        +    path = tmp_path / "job.trace.json"
        +    if sync:
        +        await asyncio.to_thread(Job(job).export_timeline, str(path))
        +    else:
        +        await job.export_timeline(path)
        +    assert json.loads(path.read_text()) == trace
        +    inner.timeline.assert_awaited_once_with()
        +    inner.wait.assert_not_awaited()
        +    inner.cancel.assert_not_awaited()
        +
        +
        +@pytest.mark.asyncio
        +async def test_export_timeline_failure_preserves_existing_file(tmp_path):
        +    path = tmp_path / "job.trace.json"
        +    path.write_text("previous recording")
        +    job = AsyncJob(
        +        SimpleNamespace(
        +            timeline=AsyncMock(side_effect=RuntimeError("unsupported server"))
        +        )
        +    )
        +    with pytest.raises(RuntimeError, match="unsupported server"):
        +        await job.export_timeline(path)
        +    assert path.read_text() == "previous recording"
        +    with pytest.raises(NotImplementedError, match="server-side Function job"):
        +        await AsyncJob(None).export_timeline(path)
        +    with pytest.raises(NotImplementedError, match="server-side Function job"):
        +        Job(None).export_timeline(path)
        +
        +
        +@pytest.mark.asyncio
        +async def test_export_timeline_reports_filesystem_errors(tmp_path):
        +    job = AsyncJob(
        +        SimpleNamespace(timeline=AsyncMock(return_value='{"traceEvents":[]}'))
        +    )
        +    with pytest.raises(FileNotFoundError):
        +        await job.export_timeline(tmp_path / "missing" / "trace.json")
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_stack_preserves_evidence_and_does_not_wait(sync):
        +    evidence = {
        +        "worker_id": "worker",
        +        "status": "unavailable",
        +        "execution_epoch": 1,
        +        "stacks": [],
        +        "omitted_sessions": 0,
        +    }
        +    inner = SimpleNamespace(
        +        stack=AsyncMock(return_value=json.dumps(evidence)),
        +        wait=AsyncMock(),
        +        cancel=AsyncMock(),
        +    )
        +    job = AsyncJob(inner)
        +    actual = (
        +        await asyncio.to_thread(Job(job).stack, "worker")
        +        if sync
        +        else await job.stack("worker")
        +    )
        +    assert actual == evidence
        +    inner.stack.assert_awaited_once_with("worker")
        +    inner.wait.assert_not_awaited()
        +    inner.cancel.assert_not_awaited()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_stack_propagates_errors_and_rejects_local_handles(sync):
        +    error = RuntimeError("system operate privilege required")
        +    job = AsyncJob(SimpleNamespace(stack=AsyncMock(side_effect=error)))
        +    with pytest.raises(RuntimeError) as failure:
        +        if sync:
        +            await asyncio.to_thread(Job(job).stack, "worker")
        +        else:
        +            await job.stack("worker")
        +    assert failure.value is error
        +    with pytest.raises(NotImplementedError):
        +        if sync:
        +            Job(None).stack("worker")
        +        else:
        +            await AsyncJob(None).stack("worker")
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "kind,planned_key,completed_key,unit",
        +    [
        +        ("compact", "rows_planned", "rows_rewritten", " rows"),
        +        (
        +            "prewarm_page_cache",
        +            "executors_targeted",
        +            "executors_completed",
        +            " executors",
        +        ),
        +    ],
        +)
        +async def test_maintenance_progress_bar_uses_operation_counters_and_handles_retry(
        +    monkeypatch, kind, planned_key, completed_key, unit
        +):
        +    tqdm_module = pytest.importorskip("tqdm.auto")
        +
        +    class Bar:
        +        total = None
        +        n = 0
        +        unit = " rows"
        +        closed = False
        +
        +        def update(self, delta):
        +            self.n += delta
        +
        +        def close(self):
        +            self.closed = True
        +
        +    bar = Bar()
        +    monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
        +
        +    class MaintenanceJob:
        +        id = "maintenance-job"
        +        job_type = kind
        +
        +        async def wait(self, progress):
        +            progress({"job_type": kind, "phase": "planning"})
        +            assert bar.total is None
        +            progress({"job_type": kind, planned_key: 4, completed_key: 2})
        +            assert bar.n == 2
        +            # Older responses can omit an epoch; revised observations still
        +            # replace the previous attempt's displayed work.
        +            progress({"job_type": kind, planned_key: 4, completed_key: 1})
        +            assert bar.n == 1
        +            progress({"job_type": kind, planned_key: 4, completed_key: 4})
        +
        +    assert await AsyncJob(MaintenanceJob()).wait(progress=True) is None
        +    assert bar.n == 4
        +    assert bar.total == 4
        +    assert bar.unit == unit
        +    assert bar.closed
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("known_empty", [False, True])
        +async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals(
        +    monkeypatch, known_empty
        +):
        +    tqdm_module = pytest.importorskip("tqdm.auto")
        +
        +    class Bar:
        +        total = None
        +        n = 0
        +        unit = " rows"
        +
        +        def update(self, delta):
        +            self.n += delta
        +
        +        def close(self):
        +            pass
        +
        +    bar = Bar()
        +    monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
        +
        +    class PrewarmJob:
        +        id = "prewarm-job"
        +        job_type = "prewarm_page_cache"
        +
        +        async def wait(self, progress):
        +            snapshot = {"job_type": self.job_type, "phase": "succeeded"}
        +            if known_empty:
        +                snapshot.update(executors_targeted=0, executors_completed=0)
        +            progress(snapshot)
        +
        +    assert await AsyncJob(PrewarmJob()).wait(progress=True) is None
        +    assert bar.n == 0
        +    assert bar.total == (0 if known_empty else None)
        +    assert bar.unit == " executors"
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_profile_wait_preserves_timeout_and_never_waits_or_cancels_parent(sync):
        +    error = TimeoutError("capture and refresh continue")
        +    inner = SimpleNamespace(
        +        wait_for_profile=AsyncMock(side_effect=error),
        +        wait=AsyncMock(),
        +        cancel=AsyncMock(),
        +    )
        +    job = AsyncJob(inner)
        +    kwargs = {
        +        "timeout": timedelta(milliseconds=50),
        +        "poll_interval": timedelta(seconds=5),
        +    }
        +    with pytest.raises(TimeoutError) as caught:
        +        if sync:
        +            await asyncio.to_thread(Job(job).wait_for_profile, "profile-1", **kwargs)
        +        else:
        +            await job.wait_for_profile("profile-1", **kwargs)
        +    assert caught.value.args == error.args
        +    # On Python 3.11 and 3.12, run_coroutine_threadsafe re-creates TimeoutError
        +    # when copying it across futures, so identity only holds on the async path.
        +    if not sync:
        +        assert caught.value is error
        +    inner.wait_for_profile.assert_awaited_once_with(
        +        "profile-1", timeout_seconds=0.05, poll_interval_seconds=5.0
        +    )
        +    inner.wait.assert_not_awaited()
        +    inner.cancel.assert_not_awaited()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_profile_export_failure_preserves_destination_and_server_error(
        +    sync, tmp_path
        +):
        +    error = HttpError("403: System Operate required", "request-1", 403)
        +    inner = SimpleNamespace(profile_artifact=AsyncMock(side_effect=error))
        +    job = AsyncJob(inner)
        +    path = tmp_path / "profile.json"
        +    path.write_text("previous capture")
        +    with pytest.raises(HttpError) as caught:
        +        if sync:
        +            await asyncio.to_thread(Job(job).export_profile, "profile-1", path)
        +        else:
        +            await job.export_profile("profile-1", path)
        +    assert caught.value is error
        +    assert path.read_text() == "previous capture"
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "method,args",
        +    [
        +        ("capture_profile", ("worker-1",)),
        +        ("profile_status", ("profile-1",)),
        +        ("wait_for_profile", ("profile-1",)),
        +        ("profile_artifact", ("profile-1",)),
        +    ],
        +)
        +async def test_function_profiles_reject_embedded_handles(method, args):
        +    with pytest.raises(NotImplementedError, match="Enterprise Function refresh job"):
        +        await getattr(AsyncJob(None), method)(*args)
        +    with pytest.raises(NotImplementedError, match="Enterprise Function refresh job"):
        +        getattr(Job(None), method)(*args)
        diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py
        index cc1c44e90..d18e8580b 100644
        --- a/python/python/tests/test_listing.py
        +++ b/python/python/tests/test_listing.py
        @@ -268,7 +268,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous)
                 if kind == "jobs":
                     assert verb == "POST"
                     assert path.path == "/v1/jobs/list"
        -            assert body == {"page_token": token, "limit": 2}
        +            assert body == {"database": "dev", "page_token": token, "limit": 2}
                 else:
                     namespace = "team"
                     resource = kind.removesuffix("s")
        @@ -326,3 +326,179 @@ async def test_listing_invalid_limit_does_not_fetch(listing_server, kind, page_l
             with pytest.raises(ValueError, match="limit"):
                 await items.__anext__()
             assert requests == []
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize("namespace", [[], ["team", "project"]])
        +@pytest.mark.parametrize("multiple_types", [False, True])
        +async def test_job_filters_persist_across_pages_and_resume(
        +    listing_server, asynchronous, namespace, multiple_types
        +):
        +    endpoint, requests, responses = listing_server
        +    responses.extend(
        +        (200, response_page("jobs", names, token))
        +        for names, token in [(["a"], "empty"), ([], "last"), (["b"], None)]
        +    )
        +    db = await connection(endpoint, asynchronous)
        +    types = ["column_refresh", "materialized_view_refresh"]
        +    filters = dict(
        +        table="events",
        +        namespace_path=namespace,
        +        state="in_progress",
        +        created_at_gte_millis=100,
        +        created_at_lt_millis=200,
        +        **({"job_types": types} if multiple_types else {"job_type": types[0]}),
        +    )
        +    items = db.list_jobs(page_limit=1, **filters)
        +    assert requests == []
        +    assert (await advance(items, asynchronous)).job_id == "a"
        +    assert len(requests) == 1
        +    resumed = db.list_jobs(page_token=items.page_token(), page_limit=1, **filters)
        +    assert (await advance(resumed, asynchronous)).job_id == "b"
        +    assert resumed.page_token() is None
        +    assert len(requests) == 3
        +    expected = dict(
        +        database="dev",
        +        limit=1,
        +        table_ref={
        +            "db_name": "dev",
        +            "table_id": {"namespace_path": namespace, "table_name": "events"},
        +        },
        +        state="in_progress",
        +        job_types=types if multiple_types else types[:1],
        +        created_at_gte_millis=100,
        +        created_at_lt_millis=200,
        +    )
        +    for (_, path, body), token in zip(requests, [None, "empty", "last"]):
        +        assert path == "/v1/jobs/list"
        +        assert body == {**expected, **({"page_token": token} if token else {})}
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "filters",
        +    [
        +        {},
        +        {"state": "failed"},
        +        {"job_types": ["column_refresh"]},
        +        {"created_at_lt_millis": 200},
        +    ],
        +)
        +async def test_job_listing_without_table_stays_in_connected_database(
        +    listing_server, asynchronous, filters
        +):
        +    endpoint, requests, responses = listing_server
        +    responses.append((200, response_page("jobs", ["a"], None)))
        +    db = await connection(endpoint, asynchronous)
        +    items = db.list_jobs(**filters)
        +    assert (await advance(items, asynchronous)).job_id == "a"
        +    assert requests[0][2] == {"database": "dev", **filters}
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "filters, message",
        +    [
        +        ({"namespace_path": ["team"]}, "requires a table"),
        +        ({"created_at_gte_millis": 200, "created_at_lt_millis": 200}, "less than"),
        +        ({"created_at_gte_millis": 201, "created_at_lt_millis": 200}, "less than"),
        +        ({"job_type": "column_refresh", "job_types": []}, "only one"),
        +        ({"state": "unknown"}, "state must be"),
        +    ],
        +)
        +async def test_invalid_job_filters_do_not_fetch(
        +    listing_server, asynchronous, filters, message
        +):
        +    endpoint, requests, _ = listing_server
        +    db = await connection(endpoint, asynchronous)
        +    with pytest.raises(ValueError, match=message):
        +        items = db.list_jobs(**filters)
        +        await advance(items, asynchronous)
        +    assert requests == []
        +
        +
        +@pytest.mark.asyncio
        +async def test_listing_slice_and_index_fetch_only_needed_pages(listing_server):
        +    endpoint, requests, responses = listing_server
        +    responses.extend(
        +        (200, response_page("jobs", names, token))
        +        for names, token in [(["a", "b"], "second"), (["c", "d"], "last")]
        +    )
        +    db = await connection(endpoint, False)
        +    items = db.list_jobs(table="events", page_limit=2)
        +    assert items[:0] == []
        +    assert items[5:2] == []
        +    assert requests == []
        +    assert [job.job_id for job in items[:2]] == ["a", "b"]
        +    assert len(requests) == 1
        +    assert items.num_page_results() == 2
        +    assert items.page_token() == "second"
        +    assert items[1].job_id == "b"
        +    assert next(items).job_id == "a"
        +    assert [job.job_id for job in items[:2]] == ["b", "c"]
        +    assert len(requests) == 2
        +    assert items.num_page_results() == 3
        +    assert items.page_token() == "last"
        +    assert [job.job_id for job in items[0:3:2][:1]] == ["b"]
        +    assert len(requests) == 2
        +
        +
        +@pytest.mark.asyncio
        +async def test_listing_length_and_slices_preserve_remaining_items(listing_server):
        +    endpoint, requests, responses = listing_server
        +    responses.extend(
        +        (200, response_page("jobs", names, token))
        +        for names, token in [(["a", "b"], "empty"), ([], "last"), (["c", "d"], None)]
        +    )
        +    db = await connection(endpoint, False)
        +    items = db.list_jobs(page_limit=2)
        +    assert bool(items)
        +    assert len(requests) == 1
        +    assert next(items).job_id == "a"
        +    assert len(items) == 3
        +    assert len(requests) == 3
        +    assert items.num_page_results() == 3
        +    assert items.page_token() is None
        +    assert items[-1].job_id == "d"
        +    assert [job.job_id for job in items[::-1]] == ["d", "c", "b"]
        +    assert [job.job_id for job in items[1:]] == ["c", "d"]
        +    assert [job.job_id for job in items[:100:2]] == ["b", "d"]
        +    assert [job.job_id for job in items[: 2**100 : 2**100]] == ["b"]
        +    with pytest.raises(IndexError):
        +        _ = items[3]
        +    assert [job.job_id for job in items] == ["b", "c", "d"]
        +    assert len(items) == 0
        +    assert not items
        +    assert len(requests) == 3
        +
        +
        +@pytest.mark.asyncio
        +async def test_listing_invalid_slice_does_not_fetch(listing_server):
        +    endpoint, requests, _ = listing_server
        +    db = await connection(endpoint, False)
        +    items = db.list_jobs()
        +    with pytest.raises(ValueError, match="step"):
        +        _ = items[::0]
        +    with pytest.raises(TypeError):
        +        _ = items["invalid"]
        +    with pytest.raises(TypeError):
        +        _ = items[:1.5]
        +    assert requests == []
        +
        +
        +@pytest.mark.asyncio
        +async def test_listing_slice_failure_preserves_cache_and_retry_token(listing_server):
        +    endpoint, requests, responses = listing_server
        +    responses.extend([(200, response_page("jobs", ["a", "b"], "retry")), (401, {})])
        +    db = await connection(endpoint, False)
        +    items = db.list_jobs(page_limit=2)
        +    with pytest.raises(HttpError):
        +        _ = items[:3]
        +    assert items.page_token() == "retry"
        +    assert items.num_page_results() == 2
        +    assert [job.job_id for job in items[:2]] == ["a", "b"]
        +    assert [job.job_id for job in items] == ["a", "b"]
        +    assert len(requests) == 2
        diff --git a/python/python/tests/test_materialized_view_creation.py b/python/python/tests/test_materialized_view_creation.py
        new file mode 100644
        index 000000000..0d9a4c2b4
        --- /dev/null
        +++ b/python/python/tests/test_materialized_view_creation.py
        @@ -0,0 +1,84 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import pytest
        +
        +import lancedb
        +
        +
        +@pytest.mark.experimental_functions
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize("background", [False, True])
        +@pytest.mark.parametrize("namespace", [False, True])
        +@pytest.mark.parametrize("defining_query", [False, True])
        +async def test_exist_ok_preserves_materialized_data(
        +    tmp_path, asynchronous, background, namespace, defining_query
        +):
        +    source_args = (
        +        {"query": "SELECT * FROM source"} if defining_query else {"source": "source"}
        +    )
        +    replacement_args = {
        +        **(
        +            {"query": "SELECT * FROM missing"}
        +            if defining_query
        +            else {"source": "missing"}
        +        ),
        +        "auto_refresh_enabled": True,
        +        "auto_refresh_interval_seconds": 1,
        +    }
        +    options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}}
        +    if asynchronous:
        +        db = (
        +            lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options)
        +            if namespace
        +            else await lancedb.connect_async(tmp_path, **options)
        +        )
        +        source = await db.create_table("source", [{"id": 1}])
        +        original = await db.create_materialized_view(
        +            "saved", **source_args, exist_ok=True
        +        )
        +        definition = await original.definition()
        +        version = await original.table.version()
        +        await source.add([{"id": 2}])
        +        if background:
        +            job = await db.create_materialized_view_async(
        +                "saved", **replacement_args, exist_ok=True
        +            )
        +            await job.wait()
        +            kept = await db.open_materialized_view("saved")
        +        else:
        +            kept = await db.create_materialized_view(
        +                "saved", **replacement_args, exist_ok=True
        +            )
        +        assert (await kept.definition()).query == definition.query
        +        assert await kept.table.version() == version
        +        assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}]
        +        with pytest.raises(ValueError, match="already exists"):
        +            await db.create_materialized_view("saved", **source_args)
        +    else:
        +        db = (
        +            lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options)
        +            if namespace
        +            else lancedb.connect(tmp_path, **options)
        +        )
        +        source = db.create_table("source", [{"id": 1}])
        +        original = db.create_materialized_view("saved", **source_args, exist_ok=True)
        +        definition = original.definition
        +        version = original.table.version
        +        source.add([{"id": 2}])
        +        if background:
        +            job = db.create_materialized_view_async(
        +                "saved", **replacement_args, exist_ok=True
        +            )
        +            job.wait()
        +            kept = db.open_materialized_view("saved")
        +        else:
        +            kept = db.create_materialized_view(
        +                "saved", **replacement_args, exist_ok=True
        +            )
        +        assert kept.definition.query == definition.query
        +        assert kept.table.version == version
        +        assert kept.table.to_arrow().to_pylist() == [{"id": 1}]
        +        with pytest.raises(ValueError, match="already exists"):
        +            db.create_materialized_view("saved", **source_args)
        diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py
        index ebb632300..22995a8e1 100644
        --- a/python/python/tests/test_materialized_views.py
        +++ b/python/python/tests/test_materialized_views.py
        @@ -10,6 +10,7 @@ import lancedb
         import pytest
         import pyarrow as pa
         from lancedb.db import AsyncConnection
        +from lancedb.exceptions import JobFailedError
         from lancedb.materialized_view import MaterializedViewDefinition
         from lancedb.remote.db import RemoteDBConnection
         from utils import start_server_thread
        @@ -63,7 +64,21 @@ def mock_remote_materialized_view_refresh():
         @pytest.mark.parametrize("sync", [False, True])
         @pytest.mark.parametrize("background", [False, True])
         @pytest.mark.parametrize("full", [False, True])
        -async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
        +@pytest.mark.parametrize(
        +    "resources",
        +    [
        +        {},
        +        {"total_gpu_count": 2, "gpu_class": "h100"},
        +        {
        +            "total_cpu_millis": 8000,
        +            "total_memory_bytes": 16 * 1024**3,
        +            "total_gpu_count": 0,
        +        },
        +    ],
        +)
        +async def test_remote_refresh_reports_unknown_metrics(
        +    sync, background, full, resources
        +):
             flight = pytest.importorskip("pyarrow.flight")
         
             class RefreshServer(flight.FlightServerBase):
        @@ -77,10 +92,13 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
                         return flight.RecordBatchStream(
                             pa.table(
                                 {
        -                            "name": ["view"],
        -                            "query": ["SELECT * FROM source"],
        +                            "description": [
        +                                json.dumps(
        +                                    {"name": "view", "query": "SELECT * FROM source"}
        +                                )
        +                            ],
                                 }
        -                    )
        +                    ).replace_schema_metadata({b"lancedb.describe.format": b"json"})
                         )
                     assert b"REFRESH MATERIALIZED VIEW" in ticket.ticket
                     # SQL completion carries no refresh statistics.
        @@ -90,7 +108,7 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
                 mock_remote_materialized_view_refresh() as (host, requests),
                 RefreshServer() as server,
             ):
        -        options = {"full": True} if full else {}
        +        options = {"full": full, **resources}
                 connect = lancedb.connect if sync else lancedb.connect_async
                 db = connect(
                     "db://dev",
        @@ -136,15 +154,37 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
                 assert len(describes) == 2
                 assert len(refreshes) == 1
                 assert all(
        -            b'DESCRIBE MATERIALIZED VIEW "view"' in command for command in describes
        +            b'DESCRIBE MATERIALIZED VIEW "view" FORMAT JSON' in command
        +            for command in describes
                 )
                 (refresh,) = refreshes
                 assert b'REFRESH MATERIALIZED VIEW "view"' in refresh
        -        assert (b"WITH (full = true)" in refresh) is full
        +        assert (b"full = true" in refresh) is full
        +        for key, value in resources.items():
        +            expected = (
        +                f"{key} = '{value}'" if key == "gpu_class" else f"{key} = {value}"
        +            )
        +            assert expected.encode() in refresh
        +        previous = len(server.commands)
        +        for invalid in [
        +            {"total_cpu_millis": 0},
        +            {"total_gpu_count": -1},
        +            {"total_gpu_count": True},
        +            {"total_gpu_count": 2**32},
        +            {"gpu_class": "H200:8"},
        +            {"total_gpu_count": 0, "gpu_class": "h100"},
        +        ]:
        +            with pytest.raises(ValueError):
        +                if sync:
        +                    view.refresh(**invalid)
        +                else:
        +                    await view.refresh(**invalid)
        +        assert len(server.commands) == previous
                 assert not any("count_rows" in path for path in requests)
         
         
        -def test_sync_remote_create_uses_public_async_connection():
        +@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"])
        +def test_sync_remote_create_uses_public_async_connection(query):
             calls = []
         
             class StubAsyncTable:
        @@ -159,17 +199,25 @@ def test_sync_remote_create_uses_public_async_connection():
                     name,
                     source,
                     *,
        +            query=None,
                     select=None,
                     where=None,
                     limit=None,
                     with_no_data=False,
        +            exist_ok=False,
                     auto_refresh_enabled=None,
                     auto_refresh_interval_seconds=None,
        +            total_cpu_millis=None,
        +            total_memory_bytes=None,
        +            total_gpu_count=None,
        +            gpu_class=None,
        +            gpu_count=None,
                 ):
                     calls.append(
                         (
                             name,
                             source,
        +                    query,
                             select,
                             where,
                             limit,
        @@ -188,18 +236,24 @@ def test_sync_remote_create_uses_public_async_connection():
             db.db_name = "example"
             db.serialize = lambda: "{}"
         
        -    view = db.create_materialized_view(
        -        "adults",
        -        "people",
        -        select=["name"],
        -        where="age >= 18",
        -        limit=10,
        -        with_no_data=True,
        -        auto_refresh_enabled=True,
        -        auto_refresh_interval_seconds=0.5,
        -    )
        +    if query is None:
        +        view = db.create_materialized_view(
        +            "adults",
        +            "people",
        +            select=["name"],
        +            where="age >= 18",
        +            limit=10,
        +            with_no_data=True,
        +            auto_refresh_enabled=True,
        +            auto_refresh_interval_seconds=0.5,
        +        )
        +        assert calls == [
        +            ("adults", "people", None, ["name"], "age >= 18", 10, True, True, 0.5)
        +        ]
        +    else:
        +        view = db.create_materialized_view("adults", query=query)
        +        assert calls == [("adults", None, query, None, None, None, False, None, None)]
             assert view.name == "adults"
        -    assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)]
         
             db.drop_materialized_view("adults", namespace_path=["analytics"])
             assert calls[-1] == ("drop", "adults", ["analytics"])
        @@ -227,21 +281,21 @@ def test_create_and_refresh_jobs(tmp_path):
             create_job = db.create_materialized_view_async(
                 "adults", "people", where="age >= 18", with_no_data=True
             )
        -    assert create_job.id is None
        -    assert create_job.job_type is None
        +    assert create_job.id() is None
        +    assert create_job.job_type() is None
             assert create_job.wait() is None
         
             view = db.open_materialized_view("adults")
             refresh_job = view.refresh_async()
        -    assert refresh_job.id is None
        -    assert refresh_job.job_type is None
        +    assert refresh_job.id() is None
        +    assert refresh_job.job_type() is None
             result = refresh_job.wait()
             assert result.mode == "rebuild"
             assert result.rows_written == 2
             assert view.table.count_rows() == 2
         
             drop_job = db.drop_materialized_view_async("adults")
        -    assert drop_job.id is None
        +    assert drop_job.id() is None
             assert drop_job.wait() is None
             assert "adults" not in list(db.list_materialized_views())
         
        @@ -400,20 +454,20 @@ async def test_async_create_and_refresh_jobs(tmp_path):
             create_job = await db.create_materialized_view_async(
                 "adults", "people", with_no_data=True
             )
        -    assert create_job.id is None
        -    assert create_job.job_type is None
        +    assert create_job.id() is None
        +    assert create_job.job_type() is None
             assert await create_job.wait() is None
         
             view = await db.open_materialized_view("adults")
             refresh_job = await view.refresh_async()
        -    assert refresh_job.id is None
        -    assert refresh_job.job_type is None
        +    assert refresh_job.id() is None
        +    assert refresh_job.job_type() is None
             result = await refresh_job.wait()
             assert result.mode == "rebuild"
             assert result.rows_written == 1
         
             drop_job = await db.drop_materialized_view_async("adults")
        -    assert drop_job.id is None
        +    assert drop_job.id() is None
             assert await drop_job.wait() is None
             assert "adults" not in [item async for item in db.list_materialized_views()]
         
        @@ -667,6 +721,11 @@ class CapturingCreateConnection:
                 {},
                 {"auto_refresh_enabled": True},
                 {"auto_refresh_enabled": False, "auto_refresh_interval_seconds": 0.5},
        +        {"total_cpu_millis": 8000, "total_gpu_count": 0},
        +        {"total_memory_bytes": 16 * 1024**3},
        +        {"gpu_class": "any"},
        +        {"gpu_count": 2},
        +        {"gpu_class": "h100", "gpu_count": 2, "total_gpu_count": 4},
             ],
         )
         def test_remote_create_forwards_refresh_options_without_interval_default(options):
        @@ -674,8 +733,8 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
             db = RemoteDBConnection.__new__(RemoteDBConnection)
             db._conn = AsyncConnection(native)
             job = db.create_materialized_view_async("adults", "people", **options)
        -    assert job.id == QueryBackedCreateJob.id
        -    assert job.job_type == "query"
        +    assert job.id() == QueryBackedCreateJob.id
        +    assert job.job_type() == "query"
             assert not hasattr(job, "query_id")
             assert job.wait() is None
             assert job.status() == "finished"
        @@ -688,6 +747,12 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
                         "filter": None,
                         "limit": None,
                         "with_no_data": False,
        +                "exist_ok": False,
        +                "total_cpu_millis": options.get("total_cpu_millis"),
        +                "total_memory_bytes": options.get("total_memory_bytes"),
        +                "total_gpu_count": options.get("total_gpu_count"),
        +                "gpu_class": options.get("gpu_class"),
        +                "gpu_count": options.get("gpu_count"),
                         "auto_refresh_enabled": options.get("auto_refresh_enabled"),
                         "auto_refresh_interval_seconds": options.get(
                             "auto_refresh_interval_seconds"
        @@ -704,8 +769,8 @@ async def test_async_remote_create_keeps_interval_unspecified():
             job = await db.create_materialized_view_async(
                 "adults", "people", auto_refresh_enabled=True
             )
        -    assert job.id == QueryBackedCreateJob.id
        -    assert job.job_type == "query"
        +    assert job.id() == QueryBackedCreateJob.id
        +    assert job.job_type() == "query"
             assert not hasattr(job, "query_id")
             assert await job.wait() is None
             assert await job.status() == "finished"
        @@ -740,18 +805,34 @@ def test_remote_create_rejects_invalid_interval_without_request(seconds):
         
         
         @pytest.mark.experimental_functions
        -def test_namespace_forwards_automatic_refresh_request(tmp_path):
        +@pytest.mark.parametrize(
        +    "options",
        +    [
        +        {"auto_refresh_enabled": True},
        +        {"total_cpu_millis": 8000, "total_gpu_count": 0},
        +        {"total_memory_bytes": 1024},
        +    ],
        +)
        +def test_namespace_forwards_automatic_refresh_request(tmp_path, options):
             db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
             with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"):
        -        db.create_materialized_view("mv", "source", auto_refresh_enabled=True)
        +        db.create_materialized_view("mv", "source", **options)
         
         
         @pytest.mark.experimental_functions
         @pytest.mark.asyncio
        -async def test_async_namespace_forwards_automatic_refresh_request(tmp_path):
        +@pytest.mark.parametrize(
        +    "options",
        +    [
        +        {"auto_refresh_enabled": True},
        +        {"total_cpu_millis": 8000, "total_gpu_count": 0},
        +        {"total_memory_bytes": 1024},
        +    ],
        +)
        +async def test_async_namespace_forwards_automatic_refresh_request(tmp_path, options):
             db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)})
             with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"):
        -        await db.create_materialized_view("mv", "source", auto_refresh_enabled=True)
        +        await db.create_materialized_view("mv", "source", **options)
         
         
         @pytest.mark.experimental_functions
        @@ -759,3 +840,144 @@ def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path):
             db = make_db(tmp_path)
             view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False)
             assert view.table.count_rows() == 3
        +
        +
        +@pytest.mark.experimental_functions
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +@pytest.mark.parametrize("namespace", [False, True])
        +@pytest.mark.parametrize("background", [False, True])
        +@pytest.mark.parametrize(
        +    "query, expected",
        +    [
        +        (
        +            "SELECT kind, count(*) AS n FROM events GROUP BY kind",
        +            [{"kind": "a", "n": 2}, {"kind": "b", "n": 1}],
        +        ),
        +        (
        +            "SELECT id, tag FROM events, UNNEST(tags) AS tag",
        +            [{"id": 1, "tag": "x"}, {"id": 1, "tag": "y"}, {"id": 3, "tag": "z"}],
        +        ),
        +    ],
        +)
        +async def test_query_defined_materialized_view(
        +    tmp_path, sync, namespace, background, query, expected
        +):
        +    if namespace:
        +        connect = lancedb.connect_namespace if sync else lancedb.connect_namespace_async
        +        db = connect("dir", {"root": str(tmp_path)}, storage_options=STABLE_ROW_IDS)
        +    elif sync:
        +        db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS)
        +    else:
        +        db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS)
        +    rows = [
        +        {"id": 1, "kind": "a", "tags": ["x", "y"]},
        +        {"id": 2, "kind": "a", "tags": []},
        +        {"id": 3, "kind": "b", "tags": ["z"]},
        +    ]
        +    if sync:
        +        db.create_table("events", rows, storage_options=STABLE_ROW_IDS)
        +        if background:
        +            db.create_materialized_view_async("result", query=query).wait()
        +            view = db.open_materialized_view("result")
        +        else:
        +            view = db.create_materialized_view("result", query=query)
        +        actual = view.table.to_arrow().to_pylist()
        +        assert view.definition.query == query
        +        view.refresh()
        +        refreshed = view.table.to_arrow().to_pylist()
        +    else:
        +        await db.create_table("events", rows, storage_options=STABLE_ROW_IDS)
        +        if background:
        +            job = await db.create_materialized_view_async("result", query=query)
        +            await job.wait()
        +            view = await db.open_materialized_view("result")
        +        else:
        +            view = await db.create_materialized_view("result", query=query)
        +        actual = (await view.table.to_arrow()).to_pylist()
        +        assert (await view.definition()).query == query
        +        await view.refresh()
        +        refreshed = (await view.table.to_arrow()).to_pylist()
        +    assert sorted(actual, key=str) == sorted(expected, key=str)
        +    assert sorted(refreshed, key=str) == sorted(expected, key=str)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +@pytest.mark.parametrize("background", [False, True])
        +@pytest.mark.parametrize(
        +    "clauses",
        +    [{"source": "people"}, {"select": []}, {"select": {}}, {"where": ""}, {"limit": 0}],
        +)
        +async def test_query_rejects_source_clauses_before_submission(
        +    sync, background, clauses
        +):
        +    connect = lancedb.connect if sync else lancedb.connect_async
        +    db = connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1")
        +    if not sync:
        +        db = await db
        +    create = (
        +        db.create_materialized_view_async if background else db.create_materialized_view
        +    )
        +    with pytest.raises(ValueError, match="query cannot be combined"):
        +        if sync:
        +            create("invalid", query="SELECT * FROM people", **clauses)
        +        else:
        +            await create("invalid", query="SELECT * FROM people", **clauses)
        +    with pytest.raises(ValueError, match="either source or query"):
        +        if sync:
        +            create("missing")
        +        else:
        +            await create("missing")
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +@pytest.mark.parametrize(
        +    "query",
        +    [
        +        "SELECT kind, count(*) AS n FROM events GROUP BY kind",
        +        "SELECT id, c.text FROM docs, chunk(body) AS c",
        +        "SELECT id, tag FROM events, UNNEST(tags) AS tag",
        +        "SELECT a.id FROM a JOIN b ON a.id = b.id",
        +    ],
        +)
        +async def test_remote_create_forwards_defining_query(sync, query):
        +    native = CapturingCreateConnection()
        +    db = AsyncConnection(native)
        +    if sync:
        +        remote = RemoteDBConnection.__new__(RemoteDBConnection)
        +        remote._conn = db
        +        job = remote.create_materialized_view_async("result", query=query)
        +        job.wait()
        +    else:
        +        job = await db.create_materialized_view_async("result", query=query)
        +        await job.wait()
        +    assert native.calls[0][0:2] == ("result", None)
        +    assert native.calls[0][2]["query"] == query
        +
        +
        +@pytest.mark.experimental_functions
        +@pytest.mark.parametrize("background", [False, True])
        +def test_query_with_no_data_and_invalid_query(tmp_path, background):
        +    db = make_db(tmp_path)
        +    query = "SELECT name FROM people WHERE age >= 18"
        +    if background:
        +        db.create_materialized_view_async(
        +            "adults", query=query, with_no_data=True
        +        ).wait()
        +        view = db.open_materialized_view("adults")
        +    else:
        +        view = db.create_materialized_view("adults", query=query, with_no_data=True)
        +    assert view.table.count_rows() == 0
        +    view.refresh()
        +    assert view.table.count_rows() == 2
        +    create = (
        +        db.create_materialized_view_async if background else db.create_materialized_view
        +    )
        +    error = JobFailedError if background else ValueError
        +    with pytest.raises(error, match="unsupported clause"):
        +        result = create("invalid", query="SELECT * FROM people ORDER BY age")
        +        if background:
        +            result.wait()
        +    assert "invalid" not in db.table_names()
        diff --git a/python/python/tests/test_merge_insert_lsm.py b/python/python/tests/test_merge_insert_lsm.py
        index c7d69d779..5b4114112 100644
        --- a/python/python/tests/test_merge_insert_lsm.py
        +++ b/python/python/tests/test_merge_insert_lsm.py
        @@ -241,6 +241,25 @@ def test_lsm_read_sees_active_memtable(tmp_path):
             assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
         
         
        +def test_lsm_read_to_batches_sees_active_memtable(tmp_path):
        +    db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
        +    table = db.create_table("t", _reader([1, 2, 3]))  # base ids 1,2,3
        +    table.set_unenforced_primary_key("id")
        +    table.enable_rte(RTEWriteSpec.unsharded())
        +
        +    _lsm_upsert(table, [4, 5])  # active memtable only, not committed to base
        +
        +    # The sync batch reader keeps the default LSM route and its pending writes.
        +    lsm = pa.Table.from_batches(list(table.search().to_batches(batch_size=2)))
        +    assert sorted(lsm["id"].to_pylist()) == [1, 2, 3, 4, 5]
        +
        +    # use_rte(False) still takes the base-only escape hatch through to_batches.
        +    base_only = pa.Table.from_batches(
        +        list(table.search().use_rte(False).to_batches(batch_size=2))
        +    )
        +    assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
        +
        +
         def test_lsm_read_dedup_newest_wins(tmp_path):
             db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
             table = db.create_table("t", _reader([1, 2, 3]))  # id 2 -> value 1
        @@ -278,7 +297,7 @@ def test_lsm_read_unsupported_shape_errors_without_use_rte_false(tmp_path):
         
             # with_row_id is unsupported by the LSM scanner; on an RTE table the default
             # (auto-routed) read hard-errors instead of silently reading a stale base.
        -    with pytest.raises(Exception):
        +    with pytest.raises(Exception, match=r"with_row_id.*use_rte\(false\)"):
                 table.search().with_row_id(True).to_arrow()
         
             # use_rte(False) is the escape hatch: it reads the base table only.
        @@ -563,19 +582,28 @@ def test_lsm_read_time_travel_errors(tmp_path):
             assert sorted(base["id"].to_pylist()) == [1, 2, 3]
         
         
        -def test_lsm_read_take_row_ids_errors(tmp_path):
        +@pytest.mark.parametrize("with_row_id", [False, True])
        +@pytest.mark.parametrize("use_rte", [None, True])
        +def test_lsm_read_take_row_ids_errors(tmp_path, with_row_id, use_rte):
             db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
             table = db.create_table("t", _reader([1, 2, 3]))
             table.set_unenforced_primary_key("id")
             table.enable_rte(RTEWriteSpec.unsharded())
             _lsm_upsert(table, [4])
        -    # take-by-row-id auto-routes through the LSM scanner, which has no stable _rowid,
        -    # so it hard-errors instead of failing with an opaque column-not-found error.
        -    with pytest.raises(Exception, match="row id"):
        -        table.take_row_ids([0, 1]).to_arrow()
        +    # Automatic and explicit RTE routing must explain the unsupported take,
        +    # including when row IDs are only requested internally for ordering.
        +    take = table.take_row_ids([1, 0, 1, 2**64 - 1], with_row_id=with_row_id)
        +    if use_rte is not None:
        +        take = take.use_rte(use_rte)
        +    with pytest.raises(Exception, match=r"take by row id.*use_rte\(false\)"):
        +        take.to_arrow()
             # use_rte(False) is the escape hatch: it reads the base table.
        -    base = table.take_row_ids([0, 1]).use_rte(False).to_arrow()
        -    assert base.num_rows == 2
        +    base = take.use_rte(False).to_arrow()
        +    assert base["id"].to_pylist() == [2, 1, 2]
        +    assert base["value"].to_pylist() == [1, 0, 1]
        +    assert ("_rowid" in base.column_names) == with_row_id
        +    if with_row_id:
        +        assert base["_rowid"].to_pylist() == [1, 0, 1]
         
         
         def test_lsm_read_fts_postfilter_errors(tmp_path):
        diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py
        index 5eb9c02bd..2c999d1b0 100644
        --- a/python/python/tests/test_namespace.py
        +++ b/python/python/tests/test_namespace.py
        @@ -6,6 +6,8 @@
         import tempfile
         import shutil
         import importlib
        +import asyncio
        +import pickle
         import warnings
         import http.server
         import json
        @@ -16,8 +18,10 @@ import copy
         import pyarrow as pa
         import lancedb
         from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
        +from lance_namespace import DescribeTableResponse
         from utils import start_server_thread
         from lancedb.listing import AsyncListing, Listing
        +from lancedb.index import FTS
         from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
         from lancedb.namespace import (
             _MAX_QUERY_K,
        @@ -25,7 +29,7 @@ from lancedb.namespace import (
             LanceNamespaceDBConnection,
             _query_to_namespace_request,
         )
        -from lancedb.query import Query
        +from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query
         from lancedb.table import AsyncTable, LanceTable
         
         
        @@ -34,6 +38,122 @@ PUSHDOWN_DATA = pa.table(
         )
         
         
        +class _RefreshNamespaceWithExpiringOptions(LanceNamespace):
        +    def __init__(self, root):
        +        self.root = root
        +
        +    def namespace_id(self):
        +        return f"refresh-test:{self.root}"
        +
        +    def describe_table(self, request):
        +        from pathlib import Path
        +
        +        return DescribeTableResponse(
        +            location=str(Path(self.root) / "t.lance"),
        +            storage_options={"vended": "fresh", "expires_at_millis": "1"},
        +        )
        +
        +
        +class _DeclaredNamespaceWithoutProperties(LanceNamespace):
        +    root = None
        +
        +    def __init__(self):
        +        from lance.namespace import DirectoryNamespace
        +
        +        self.client = DirectoryNamespace(root=self.root)
        +
        +    def namespace_id(self):
        +        return self.client.namespace_id()
        +
        +    def describe_table(self, request):
        +        return self.client.describe_table(request)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]])
        +async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
        +    class ExistenceNamespace(LanceNamespace):
        +        def namespace_id(self):
        +            return "existence-test"
        +
        +        def table_exists(self, request):
        +            if request.id == ["missing"]:
        +                raise TableNotFoundError("Table not found")
        +
        +        def describe_table(self, request):
        +            raise AssertionError("Custom existence checks must not open tables")
        +
        +    namespace = ExistenceNamespace()
        +    db = LanceNamespaceDBConnection(namespace)
        +    adb = lancedb.AsyncLanceNamespaceDBConnection(namespace)
        +    assert db.table_exists(table_id) is (table_id != ["missing"])
        +    assert await adb.table_exists(table_id) is (table_id != ["missing"])
        +
        +
        +def test_table_pickle_rejects_custom_namespace_connection(tmp_path):
        +    pytest.importorskip("lance")
        +    from lance.namespace import DirectoryNamespace
        +
        +    lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
        +        "t", [{"id": 1}]
        +    )
        +
        +    class UnserializableNamespace(LanceNamespace):
        +        def __init__(self, root):
        +            from threading import Lock
        +
        +            self.client = DirectoryNamespace(root=str(root))
        +            self.lock = Lock()
        +
        +        def namespace_id(self):
        +            return self.client.namespace_id()
        +
        +        def describe_table(self, request):
        +            return self.client.describe_table(request)
        +
        +    db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path))
        +    table = db.open_table("t")
        +
        +    with pytest.raises(TypeError, match="namespace"):
        +        pickle.dumps(table)
        +
        +
        +def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path):
        +    lancedb.connect(tmp_path).create_table("t", [{"id": 1}])
        +    db = lancedb.connect_namespace(
        +        f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)}
        +    )
        +    table = db.open_table("t", storage_options={"caller_only": "keep"})
        +
        +    restored = pickle.loads(pickle.dumps(table))
        +
        +    for current in (table, restored):
        +        options = current.latest_storage_options()
        +        assert options["caller_only"] == "keep"
        +        assert options["vended"] == "fresh"
        +
        +
        +def test_table_pickle_allows_declared_namespace_without_properties(tmp_path):
        +    pytest.importorskip("lance")
        +
        +    lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
        +        "t", [{"id": 1}]
        +    )
        +    _DeclaredNamespaceWithoutProperties.root = str(tmp_path)
        +    try:
        +        impl = f"{__name__}._DeclaredNamespaceWithoutProperties"
        +        db = LanceNamespaceDBConnection(
        +            _DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl
        +        )
        +        table = db.open_table("t")
        +
        +        restored = pickle.loads(pickle.dumps(table))
        +
        +        assert restored.to_arrow()["id"].to_pylist() == [1]
        +    finally:
        +        _DeclaredNamespaceWithoutProperties.root = None
        +
        +
         class TestNamespaceCreateTableOptions:
             @pytest.mark.parametrize("version", ["legacy", "stable"])
             @pytest.mark.parametrize("empty", [False, True])
        @@ -287,6 +407,328 @@ def paginated_rest_namespace():
                     thread.join()
         
         
        +def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path):
        +    from time import time
        +
        +    local = lancedb.connect(tmp_path)
        +    local.create_table("t", [{"id": 1}])
        +    location = str(tmp_path / "t.lance")
        +    ipc = _ipc_file(pa.table({"id": [42]}))
        +    seen = []
        +    current_options = {
        +        "block_size": "4096",
        +        "expires_at_millis": str(int(time() * 1000) + 30_000),
        +    }
        +
        +    class Handler(http.server.BaseHTTPRequestHandler):
        +        def do_POST(self):
        +            self.rfile.read(int(self.headers.get("Content-Length", "0")))
        +            path = urlparse(self.path).path
        +            seen.append(path)
        +            if path.endswith("/describe"):
        +                body = json.dumps(
        +                    {"location": location, "storage_options": current_options}
        +                ).encode()
        +                content_type = "application/json"
        +            elif path.endswith("/query"):
        +                body = ipc
        +                content_type = "application/vnd.apache.arrow.file"
        +            else:
        +                self.send_error(404)
        +                return
        +            self.send_response(200)
        +            self.send_header("Content-Type", content_type)
        +            self.send_header("Content-Length", str(len(body)))
        +            self.end_headers()
        +            self.wfile.write(body)
        +
        +        def log_message(self, *args):
        +            pass
        +
        +    with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
        +        thread = start_server_thread(server)
        +        try:
        +            db = lancedb.connect_namespace(
        +                "rest",
        +                {"uri": f"http://127.0.0.1:{server.server_port}"},
        +                namespace_client_pushdown_operations=["QueryTable"],
        +            )
        +            table = db.open_table("t")
        +            restored = pickle.loads(pickle.dumps(table))
        +
        +            seen.clear()
        +            assert restored.search().limit(1).to_list() == [{"id": 42}]
        +            assert seen == ["/v1/table/t/query"]
        +
        +            current_options = {
        +                "block_size": "8192",
        +                "expires_at_millis": str(int(time() * 1000) + 3_600_000),
        +            }
        +            assert table.latest_storage_options()["block_size"] == "8192"
        +            assert restored.latest_storage_options()["block_size"] == "8192"
        +        finally:
        +            server.shutdown()
        +            thread.join()
        +
        +
        +def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path):
        +    from time import time
        +
        +    location = str(tmp_path / "t.lance")
        +    current_options = {
        +        "vended_seed": "short-lived",
        +        "expires_at_millis": str(int(time() * 1000) + 30_000),
        +    }
        +
        +    class Handler(http.server.BaseHTTPRequestHandler):
        +        def do_POST(self):
        +            self.rfile.read(int(self.headers.get("Content-Length", "0")))
        +            path = urlparse(self.path).path
        +            if not (path.endswith("/declare") or path.endswith("/describe")):
        +                self.send_error(404)
        +                return
        +            body = json.dumps(
        +                {"location": location, "storage_options": current_options}
        +            ).encode()
        +            self.send_response(200)
        +            self.send_header("Content-Type", "application/json")
        +            self.send_header("Content-Length", str(len(body)))
        +            self.end_headers()
        +            self.wfile.write(body)
        +
        +        def log_message(self, *args):
        +            pass
        +
        +    with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
        +        thread = start_server_thread(server)
        +        try:
        +            db = lancedb.connect_namespace(
        +                "rest", {"uri": f"http://127.0.0.1:{server.server_port}"}
        +            )
        +            table = db.create_table("t", [{"id": 1}])
        +            payload = pickle.dumps(table)
        +            assert b"short-lived" not in payload
        +            restored = pickle.loads(payload)
        +
        +            current_options = {}
        +            assert table.latest_storage_options() == {}
        +            assert restored.latest_storage_options() == {}
        +        finally:
        +            server.shutdown()
        +            thread.join()
        +
        +
        +@pytest.mark.parametrize("entrypoint", ["create", "open"])
        +def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint):
        +    from time import time
        +
        +    location = str(tmp_path / "t.lance")
        +    caller_options = {"caller_option": "kept", "conflict": "caller"}
        +    vended_options = {
        +        "vended_1": "old",
        +        "conflict": "vended",
        +        "expires_at_millis": str(int(time() * 1000) + 30_000),
        +    }
        +
        +    class Handler(http.server.BaseHTTPRequestHandler):
        +        def do_POST(self):
        +            self.rfile.read(int(self.headers.get("Content-Length", "0")))
        +            path = urlparse(self.path).path
        +            if path.endswith("/declare") or path.endswith("/describe"):
        +                body = json.dumps(
        +                    {"location": location, "storage_options": vended_options}
        +                ).encode()
        +            else:
        +                self.send_error(404)
        +                return
        +            self.send_response(200)
        +            self.send_header("Content-Type", "application/json")
        +            self.send_header("Content-Length", str(len(body)))
        +            self.end_headers()
        +            self.wfile.write(body)
        +
        +        def log_message(self, *args):
        +            pass
        +
        +    with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
        +        thread = start_server_thread(server)
        +        try:
        +            db = lancedb.connect_namespace(
        +                "rest",
        +                {"uri": f"http://127.0.0.1:{server.server_port}"},
        +            )
        +            if entrypoint == "create":
        +                table = db.create_table(
        +                    "t", [{"id": 1}], storage_options=caller_options
        +                )
        +            else:
        +                db.create_table("t", [{"id": 1}])
        +                table = db.open_table("t", storage_options=caller_options)
        +            restored = pickle.loads(pickle.dumps(table))
        +
        +            for current in (table, restored):
        +                options = current.latest_storage_options()
        +                assert options["caller_option"] == "kept"
        +                assert options["conflict"] == "vended"
        +
        +            vended_options.update(
        +                {
        +                    "vended_2": "new",
        +                    "conflict": "vended-new",
        +                    "expires_at_millis": str(int(time() * 1000) + 3_600_000),
        +                }
        +            )
        +
        +            for current in (table, restored):
        +                options = current.latest_storage_options()
        +                assert options["caller_option"] == "kept"
        +                assert options["vended_2"] == "new"
        +                assert options["conflict"] == "vended-new"
        +        finally:
        +            server.shutdown()
        +            thread.join()
        +
        +
        +def test_namespace_open_uses_explicit_storage_options_provider(tmp_path):
        +    from time import time
        +
        +    from lancedb._lancedb import connect_namespace as connect_namespace_inner
        +    from lancedb.db import AsyncConnection
        +
        +    location = str(tmp_path / "t.lance")
        +    seed_options = {
        +        "vended_seed": "short-lived",
        +        "expires_at_millis": str(int(time() * 1000) + 30_000),
        +    }
        +
        +    class Handler(http.server.BaseHTTPRequestHandler):
        +        def do_POST(self):
        +            self.rfile.read(int(self.headers.get("Content-Length", "0")))
        +            path = urlparse(self.path).path
        +            if not (path.endswith("/declare") or path.endswith("/describe")):
        +                self.send_error(404)
        +                return
        +            result = {"location": location, "storage_options": seed_options}
        +            body = json.dumps(result).encode()
        +            self.send_response(200)
        +            self.send_header("Content-Type", "application/json")
        +            self.send_header("Content-Length", str(len(body)))
        +            self.end_headers()
        +            self.wfile.write(body)
        +
        +        def log_message(self, *args):
        +            pass
        +
        +    class ExplicitClient(LanceNamespace):
        +        calls = 0
        +
        +        def namespace_id(self):
        +            return "explicit-storage-options-provider"
        +
        +        def describe_table(self, request):
        +            self.calls += 1
        +            return DescribeTableResponse(
        +                location=location,
        +                storage_options={
        +                    "explicit_provider": "fresh",
        +                    "expires_at_millis": str(int(time() * 1000) + 3_600_000),
        +                },
        +            )
        +
        +    with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
        +        thread = start_server_thread(server)
        +        try:
        +            properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
        +            db = lancedb.connect_namespace("rest", properties)
        +            db.create_table("t", [{"id": 1}])
        +
        +            async def check():
        +                connection = AsyncConnection(
        +                    connect_namespace_inner("rest", properties)
        +                )
        +                client = ExplicitClient()
        +                table = await connection.open_table("t", namespace_client=client)
        +                options = await table.latest_storage_options()
        +                assert client.calls > 0
        +                assert options["explicit_provider"] == "fresh"
        +
        +            asyncio.run(check())
        +        finally:
        +            server.shutdown()
        +            thread.join()
        +
        +
        +def test_namespace_create_without_seed_uses_connection_provider(tmp_path):
        +    from time import time
        +
        +    from lancedb._lancedb import connect_namespace as connect_namespace_inner
        +    from lancedb.db import AsyncConnection
        +
        +    location = str(tmp_path / "t.lance")
        +    seed_options = {
        +        "vended_seed": "short-lived",
        +        "expires_at_millis": str(int(time() * 1000) + 30_000),
        +    }
        +
        +    class Handler(http.server.BaseHTTPRequestHandler):
        +        def do_POST(self):
        +            self.rfile.read(int(self.headers.get("Content-Length", "0")))
        +            path = urlparse(self.path).path
        +            result = {"location": location}
        +            if path.endswith("/describe"):
        +                result["storage_options"] = seed_options
        +            elif not path.endswith("/declare"):
        +                self.send_error(404)
        +                return
        +            body = json.dumps(result).encode()
        +            self.send_response(200)
        +            self.send_header("Content-Type", "application/json")
        +            self.send_header("Content-Length", str(len(body)))
        +            self.end_headers()
        +            self.wfile.write(body)
        +
        +        def log_message(self, *args):
        +            pass
        +
        +    class ExplicitClient(LanceNamespace):
        +        calls = 0
        +
        +        def namespace_id(self):
        +            return "explicit-storage-options-provider"
        +
        +        def describe_table(self, request):
        +            self.calls += 1
        +            return DescribeTableResponse(
        +                location=location,
        +                storage_options={
        +                    "explicit_provider": "fresh",
        +                    "expires_at_millis": str(int(time() * 1000) + 3_600_000),
        +                },
        +            )
        +
        +    with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
        +        thread = start_server_thread(server)
        +        try:
        +            properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
        +
        +            async def check():
        +                connection = AsyncConnection(
        +                    connect_namespace_inner("rest", properties)
        +                )
        +                client = ExplicitClient()
        +                table = await connection.create_table(
        +                    "t", [{"id": 1}], namespace_client=client
        +                )
        +                options = await table.latest_storage_options()
        +                assert client.calls == 0
        +                assert options["vended_seed"] == "short-lived"
        +
        +            asyncio.run(check())
        +        finally:
        +            server.shutdown()
        +            thread.join()
        +
        +
         @pytest.mark.asyncio
         @pytest.mark.parametrize("namespace_path", [[], ["n"]])
         async def test_rest_namespace_table_names_collects_pages(
        @@ -411,8 +853,16 @@ class TestNamespaceConnection:
                 assert "test_ns" in db.list_namespaces().namespaces
         
                 schema = pa.schema([pa.field("id", pa.int64())])
        +        db.create_table("root_table", schema=schema)
        +        assert db.table_exists(["root_table"]) is True
        +        assert "root_table" in db
        +        assert db.table_exists(["missing"]) is False
        +        assert "missing" not in db
                 table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"])
                 assert table.namespace == ["test_ns"]
        +        assert db.table_exists(["test_ns", "test_table"]) is True
        +        assert db.table_exists(["test_ns", "missing"]) is False
        +        assert "test_table" not in db
                 assert "test_table" in db.table_names(namespace_path=["test_ns"])
                 assert "test_table" in db.list_tables(namespace_path=["test_ns"]).tables
         
        @@ -420,7 +870,10 @@ class TestNamespaceConnection:
                 assert opened.namespace == ["test_ns"]
         
                 db.drop_table("test_table", namespace_path=["test_ns"])
        +        assert db.table_exists(["test_ns", "test_table"]) is False
                 assert db.list_tables(namespace_path=["test_ns"]).tables == []
        +        db.drop_table("root_table")
        +        assert "root_table" not in db
                 db.drop_namespace(["test_ns"])
                 assert "test_ns" not in db.list_namespaces().namespaces
         
        @@ -942,12 +1395,18 @@ class TestAsyncNamespaceConnection:
                 assert "test_ns" in (await db.list_namespaces()).namespaces
         
                 schema = pa.schema([pa.field("id", pa.int64())])
        +        await db.create_table("root_table", schema=schema)
        +        assert await db.table_exists(["root_table"]) is True
        +        assert await db.table_exists(["missing"]) is False
                 table = await db.create_table(
                     "test_table", schema=schema, namespace_path=["test_ns"]
                 )
                 assert table._namespace_path == ["test_ns"]
                 assert table._namespace_client is None
                 assert table._route_pushdown_to_rust is True
        +        assert await db.table_exists(["test_ns", "test_table"]) is True
        +        assert await db.table_exists(["test_ns", "missing"]) is False
        +        assert await db.table_exists(["test_table"]) is False
                 assert "test_table" in await db.table_names(namespace_path=["test_ns"])
                 assert "test_table" in (await db.list_tables(namespace_path=["test_ns"])).tables
         
        @@ -955,7 +1414,10 @@ class TestAsyncNamespaceConnection:
                 assert opened._namespace_path == ["test_ns"]
         
                 await db.drop_table("test_table", namespace_path=["test_ns"])
        +        assert await db.table_exists(["test_ns", "test_table"]) is False
                 assert (await db.list_tables(namespace_path=["test_ns"])).tables == []
        +        await db.drop_table("root_table")
        +        assert await db.table_exists(["root_table"]) is False
                 await db.drop_namespace(["test_ns"])
                 assert "test_ns" not in (await db.list_namespaces()).namespaces
         
        @@ -1310,6 +1772,48 @@ class TestPushdownOperations:
                 assert request.maximum_nprobes == 0
                 assert request.to_dict()["maximum_nprobes"] == 0
         
        +    def test_lance_table_order_by_is_not_pushed_down(self, tmp_path):
        +        namespace_client = _NamespaceClient()
        +        db = lancedb.connect(str(tmp_path / "db"))
        +        table = db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}])
        +        table._namespace_path = ["geneva"]
        +        table._namespace_client = namespace_client
        +        table._pushdown_operations = {"QueryTable"}
        +        table._route_pushdown_to_rust = False
        +
        +        result = table._execute_query(
        +            Query(limit=1, order_by=[ColumnOrdering(column_name="id")])
        +        ).read_all()
        +
        +        # Pushing this query down would drop order_by and return id 3.
        +        assert result.column("id").to_pylist() == [1]
        +        assert namespace_client.requests == []
        +
        +    def test_lance_table_scan_in_order_is_not_pushed_down(self, tmp_path):
        +        namespace_client = _NamespaceClient()
        +        db = lancedb.connect(str(tmp_path / "db"))
        +        table = db.create_table("hist", data=[{"id": 3}, {"id": 1}])
        +        table.add([{"id": 2}])
        +        table._namespace_path = ["geneva"]
        +        table._namespace_client = namespace_client
        +        table._pushdown_operations = {"QueryTable"}
        +        table._route_pushdown_to_rust = False
        +
        +        result = table._execute_query(
        +            Query(
        +                limit=2,
        +                filter="id >= 1",
        +                columns=["id"],
        +                scan_in_order=True,
        +            )
        +        ).read_all()
        +
        +        # The namespace request has no scan-order field. Local execution keeps
        +        # membership order, projection and limit; a dropped order or a sort
        +        # would return [1, 3] or [1, 2].
        +        assert result.column("id").to_pylist() == [3, 1]
        +        assert namespace_client.requests == []
        +
         
         @pytest.mark.asyncio
         class TestAsyncPushdownOperations:
        @@ -1372,6 +1876,47 @@ class TestAsyncPushdownOperations:
                 assert [request.k for request in namespace_client.requests] == [_MAX_QUERY_K]
                 assert all(r.k <= 2**31 - 1 for r in namespace_client.requests)
         
        +    async def test_async_table_order_by_is_not_pushed_down(self, tmp_path):
        +        namespace_client = _NamespaceClient()
        +        db = await lancedb.connect_async(str(tmp_path / "db"))
        +        table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}])
        +        table._namespace_path = ["geneva"]
        +        table._namespace_client = namespace_client
        +        table._pushdown_operations = {"QueryTable"}
        +        table._route_pushdown_to_rust = False
        +
        +        result = await table._execute_query(
        +            Query(limit=1, order_by=[ColumnOrdering(column_name="id")])
        +        )
        +
        +        # Pushing this query down would drop order_by and return id 3.
        +        batches = await result.read_all()
        +        assert pa.Table.from_batches(batches).column("id").to_pylist() == [1]
        +        assert namespace_client.requests == []
        +
        +    async def test_async_table_scan_in_order_is_not_pushed_down(self, tmp_path):
        +        namespace_client = _NamespaceClient()
        +        db = await lancedb.connect_async(str(tmp_path / "db"))
        +        table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}])
        +        await table.add([{"id": 2}])
        +        table._namespace_path = ["geneva"]
        +        table._namespace_client = namespace_client
        +        table._pushdown_operations = {"QueryTable"}
        +        table._route_pushdown_to_rust = False
        +
        +        result = await table._execute_query(
        +            Query(
        +                limit=2,
        +                filter="id >= 1",
        +                columns=["id"],
        +                scan_in_order=True,
        +            )
        +        )
        +
        +        batches = await result.read_all()
        +        assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1]
        +        assert namespace_client.requests == []
        +
             @pytest.mark.parametrize(
                 "query_kwargs",
                 [
        @@ -1483,3 +2028,42 @@ def test_python_namespace_attribute_access(tmp_path):
             # Missing dunder lookups still raise, so copy/hasattr probes work.
             assert not hasattr(request, "__missing_dunder__")
             assert copy.deepcopy(request) == request
        +
        +
        +@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]])
        +def test_namespace_fts_operator_is_preserved(columns):
        +    request = _query_to_namespace_request(
        +        ["matches"],
        +        Query(
        +            full_text_query=FullTextSearchQuery(
        +                query="gripper closed", columns=columns, operator="AND"
        +            )
        +        ),
        +    )
        +    structured = request.to_dict()["full_text_query"]["structured_query"]["query"]
        +    if columns and len(columns) > 1:
        +        assert all(
        +            query["operator"] == "And"
        +            for query in structured["multi_match"]["match_queries"]
        +        )
        +    else:
        +        assert structured["match"]["operator"] == "And"
        +        assert structured["match"].get("column") == (columns[0] if columns else None)
        +
        +
        +def test_namespace_fts_count_fast_search(tmp_path):
        +    properties = {"root": str(tmp_path)}
        +    db = lancedb.connect_namespace("dir", properties)
        +    table = db.create_table("matches", pa.table({"text": ["gripper"] * 15}))
        +    table.create_index("text", config=FTS())
        +    table.add(pa.table({"text": ["gripper"] * 5}))
        +    assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
        +    pushed = lancedb.connect_namespace(
        +        "dir", properties, namespace_client_pushdown_operations=["QueryTable"]
        +    ).open_table("matches")
        +    assert pushed.search("gripper", query_type="fts").count_rows() == 20
        +    query = pushed.search("gripper", query_type="fts").fast_search()
        +    assert query.use_rte(False).count_rows() == 15
        +    query = pushed.search("gripper", query_type="fts").fast_search()
        +    assert query.count_rows() == 15
        +    assert len(query.limit(100).to_list()) == 15
        diff --git a/python/python/tests/test_package_metadata.py b/python/python/tests/test_package_metadata.py
        index 1b4d3a711..afd5c5429 100644
        --- a/python/python/tests/test_package_metadata.py
        +++ b/python/python/tests/test_package_metadata.py
        @@ -68,8 +68,17 @@ def test_windows_wheel_tag_and_native_import():
             if not wheels:
                 pytest.skip("no wheel artifact is available in this development environment")
         
        +    # The wheel is tagged with the abi3 floor, which follows requires-python.
        +    minimum_python = re.search(
        +        r'^requires-python\s*=\s*">=(\d+)\.(\d+)"$',
        +        (project_dir / "pyproject.toml").read_text(),
        +        re.MULTILINE,
        +    )
        +    assert minimum_python is not None
        +    major, minor = minimum_python.groups()
        +
             assert len(wheels) == 1
        -    assert wheels[0].name.endswith("-cp310-abi3-win_amd64.whl")
        +    assert wheels[0].name.endswith(f"-cp{major}{minor}-abi3-win_amd64.whl")
         
             native_module = importlib.import_module("lancedb._lancedb")
             assert Path(native_module.__file__).suffix == ".pyd"
        diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py
        index 46d6493ed..add877582 100644
        --- a/python/python/tests/test_permutation.py
        +++ b/python/python/tests/test_permutation.py
        @@ -5,9 +5,15 @@ import pyarrow as pa
         import math
         import pytest
         
        -from lancedb import DBConnection, Table, connect
        +from lancedb import DBConnection, Session, Table, connect, connect_namespace
         from lancedb.background_loop import LOOP
        -from lancedb.permutation import Permutation, Permutations, permutation_builder
        +from lancedb.permutation import (
        +    DEFAULT_BATCH_SIZE,
        +    Permutation,
        +    Permutations,
        +    Transforms,
        +    permutation_builder,
        +)
         from utils import (
             MockPermutationServer,
             assert_server_safe_row_id_requests,
        @@ -15,6 +21,18 @@ from utils import (
         )
         
         
        +def _read_permutation_in_spawned_process(payload: bytes, output) -> None:
        +    import pickle
        +
        +    permutation = pickle.loads(payload)
        +    output.put(
        +        [
        +            row["id"]
        +            for row in permutation.__getitems__(list(range(permutation.num_rows)))
        +        ]
        +    )
        +
        +
         def test_split_random_ratios(mem_db):
             """Test random splitting with ratios."""
             tbl = mem_db.create_table(
        @@ -81,6 +99,368 @@ def test_pickled_permutation_reads_pinned_version(tmp_path):
             assert sorted(row["idx"] for row in rows) == list(range(20))
         
         
        +def test_persist_plan_create_overwrite_namespace_and_metadata(tmp_path):
        +    import pickle
        +
        +    db = connect(tmp_path)
        +    tbl = db.create_table("base", pa.table({"id": range(20)}))
        +    db.create_namespace(["plans"])
        +    namespace_path = ["plans"]
        +
        +    plan = (
        +        permutation_builder(tbl)
        +        .split_sequential(fixed=2, split_names=["train", "test"])
        +        .persist(db, "splits", namespace_path=namespace_path)
        +        .execute()
        +    )
        +    assert plan.count_rows() == 20
        +    assert plan.namespace == namespace_path
        +    assert pickle.loads(pickle.dumps(plan)).namespace == namespace_path
        +
        +    permutation = Permutation.from_tables(tbl, plan, split="train")
        +    assert permutation.base_version == tbl.version
        +    assert permutation.base_branch is None
        +    assert permutation.num_rows == 10
        +
        +    with pytest.raises((ValueError, RuntimeError), match="already exists"):
        +        (
        +            permutation_builder(tbl)
        +            .split_sequential(fixed=2)
        +            .persist(db, "splits", namespace_path=namespace_path)
        +            .execute()
        +        )
        +
        +    with pytest.raises(ValueError, match="Invalid mode"):
        +        permutation_builder(tbl).persist(db, "other", mode="replace")
        +
        +    class RemoteLike:
        +        uri = "db://example"
        +
        +    with pytest.raises(NotImplementedError, match="Enterprise"):
        +        permutation_builder(tbl).persist(RemoteLike(), "remote_splits")
        +
        +    tbl.add(pa.table({"id": range(20, 40)}))
        +    plan = (
        +        permutation_builder(tbl)
        +        .split_sequential(fixed=2)
        +        .persist(db, "splits", namespace_path=namespace_path, mode="overwrite")
        +        .execute()
        +    )
        +    assert plan.count_rows() == 40
        +    assert db.open_table("splits", namespace_path=namespace_path).count_rows() == 40
        +    # The earlier permutation still reads the plan and base snapshot it was built from.
        +    assert permutation.num_rows == 10
        +    assert [row["id"] for row in permutation.__getitems__([0, 1])] == [0, 1]
        +
        +
        +def test_persist_namespace_connection_direct_result_pickle(tmp_path):
        +    import pickle
        +
        +    db = connect_namespace("dir", {"root": str(tmp_path)})
        +    db.create_namespace(["plans"])
        +    tbl = db.create_table("base", pa.table({"id": range(20)}))
        +
        +    plan = (
        +        permutation_builder(tbl)
        +        .split_sequential(fixed=2, split_names=["train", "test"])
        +        .persist(db, "splits", namespace_path=["plans"])
        +        .execute()
        +    )
        +    assert plan.namespace == ["plans"]
        +    assert plan._conn is db
        +
        +    restored_plan = pickle.loads(pickle.dumps(plan))
        +    assert restored_plan.namespace == ["plans"]
        +    assert restored_plan.count_rows() == 20
        +
        +    permutation = Permutation.from_tables(tbl, plan, split="train")
        +    restored = pickle.loads(pickle.dumps(permutation))
        +    assert restored.num_rows == 10
        +    assert sorted(
        +        row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
        +    ) == list(range(10))
        +
        +
        +def test_persist_direct_result_keeps_session_pickle_error(tmp_path):
        +    import pickle
        +
        +    db = connect(tmp_path, session=Session())
        +    tbl = db.create_table("base", pa.table({"id": range(5)}))
        +    plan = permutation_builder(tbl).persist(db, "splits").execute()
        +
        +    with pytest.raises(TypeError, match="Session"):
        +        pickle.dumps(plan)
        +
        +    permutation = Permutation.from_tables(tbl, plan)
        +    with pytest.raises(TypeError, match="Session"):
        +        pickle.dumps(permutation)
        +
        +
        +def test_persist_direct_result_preserves_manifest_connection_state(tmp_path):
        +    import pickle
        +
        +    db = connect(tmp_path, manifest_enabled=True)
        +    tbl = db.create_table("base", pa.table({"id": range(5)}))
        +    plan = permutation_builder(tbl).persist(db, "splits").execute()
        +
        +    restored = pickle.loads(pickle.dumps(plan))
        +    assert restored._conn._manifest_enabled is True
        +    assert restored.count_rows() == 5
        +
        +
        +def test_base_branch_property_reads_plan_metadata(tmp_path):
        +    db = connect(tmp_path)
        +    tbl = db.create_table("base", pa.table({"id": range(10)}))
        +    branch = tbl.branches.create("exp")
        +    branch.add(pa.table({"id": range(10, 20)}))
        +
        +    plan = permutation_builder(branch).persist(db, "branch_splits").execute()
        +    permutation = Permutation.from_tables(branch, plan)
        +
        +    assert permutation.base_branch == "exp"
        +    assert permutation.base_version == branch.version
        +    assert permutation.num_rows == 20
        +
        +
        +def test_persist_embedded_plan_for_remote_base(tmp_path):
        +    from lancedb import deserialize_conn
        +
        +    server = MockPermutationServer(num_rows=8)
        +    db = connect(tmp_path)
        +
        +    with mock_remote_table(server) as remote:
        +        permutation_builder(remote).shuffle(seed=7).persist(db, "plan").execute()
        +        plan = db.open_table("plan")
        +        expected_ids = plan.to_arrow().to_pydict()["row_id"]
        +        assert expected_ids != list(range(8))
        +
        +        # Advance the mock's latest version. A fresh handle must see v2, while
        +        # the plan's recorded v1 still pins every read to the old snapshot.
        +        server.publish_version(2, list(range(100, 108)))
        +        fresh_remote = deserialize_conn(
        +            remote._serialized_connection_state()
        +        ).open_table(server.name)
        +        assert fresh_remote.version == 2
        +
        +        permutation = Permutation.from_tables(fresh_remote, plan)
        +        assert permutation.base_version == 1
        +        assert permutation.base_branch is None
        +        assert permutation._plan_version == 1
        +        assert permutation.permutation_table.version == 1
        +
        +        sequential_ids = [
        +            row["id"]
        +            for batch in permutation.iter(3, skip_last_batch=False)
        +            for row in batch
        +        ]
        +        assert sequential_ids == expected_ids
        +        assert [row["id"] for row in permutation.__getitems__([5, 1, 5, 3])] == [
        +            expected_ids[i] for i in [5, 1, 5, 3]
        +        ]
        +
        +        # The plan is local, but its build and gathers address the remote base
        +        # at the recorded main/v1 snapshot. Latest describes carry no version.
        +        assert server.scans
        +        assert server.takes
        +        for body in [*server.scans, *server.takes]:
        +            assert body.get("version") == 1
        +            assert body.get("branch") is None
        +        describe_versions = [body.get("version") for body in server.describe_bodies]
        +        assert None in describe_versions
        +        assert 1 in describe_versions
        +        assert all(body.get("branch") is None for body in server.describe_bodies)
        +
        +
        +def test_persisted_plan_pickle_reopens_same_snapshot_after_overwrite(tmp_path):
        +    from datetime import timedelta
        +    import pickle
        +
        +    db = connect(tmp_path, read_consistency_interval=timedelta(0))
        +    tbl = db.create_table("base", pa.table({"id": range(20)}))
        +    plan = permutation_builder(tbl).filter("id < 10").persist(db, "splits").execute()
        +    permutation = Permutation.from_tables(tbl, plan)
        +    old_base_version = permutation.base_version
        +    old_plan_version = permutation._plan_version
        +    state = permutation.__getstate__()
        +    assert "permutation_data" not in state
        +    assert (
        +        state["permutation_table_state"]["state"]["checkout_version"]
        +        == old_plan_version
        +    )
        +
        +    # Replace the plan with disjoint rows of the same cardinality.
        +    permutation_builder(tbl).filter("id >= 10").persist(
        +        db, "splits", mode="overwrite"
        +    ).execute()
        +    assert plan.version == old_plan_version + 1
        +    assert permutation.permutation_table.version == old_plan_version
        +
        +    live_ids = [
        +        row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows)))
        +    ]
        +    assert live_ids == list(range(10))
        +
        +    # A reader recreated after the overwrite must still use the pinned snapshot.
        +    permutation.reader = None
        +    permutation._pid = None
        +    recreated_ids = [
        +        row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows)))
        +    ]
        +    assert recreated_ids == list(range(10))
        +
        +    restored = pickle.loads(pickle.dumps(permutation))
        +    assert restored.base_version == old_base_version
        +    restored_ids = [
        +        row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
        +    ]
        +    assert restored_ids == list(range(10))
        +
        +    # A newly constructed permutation sees the overwritten plan.
        +    fresh = Permutation.from_tables(tbl, db.open_table("splits"))
        +    assert fresh.base_version == old_base_version
        +    fresh_ids = [row["id"] for row in fresh.__getitems__(list(range(fresh.num_rows)))]
        +    assert fresh_ids == list(range(10, 20))
        +
        +
        +def test_persisted_plan_pickle_uses_captured_main_branch(tmp_path):
        +    import pickle
        +
        +    db = connect(tmp_path)
        +    tbl = db.create_table("base", pa.table({"id": range(20)}))
        +    permutation_builder(tbl).persist(db, "splits").execute()
        +
        +    initial_plan = db.open_table("splits")
        +    initial_plan.branches.create("exp", from_version=1)
        +
        +    # Main plan version 2 still has all 20 rows.
        +    permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute()
        +    main_plan = db.open_table("splits")
        +    assert main_plan.version == 2
        +
        +    # Branch plan version 2 has different contents, so the numeric version alone
        +    # does not identify the snapshot.
        +    branch_plan = db.open_table("splits", branch="exp")
        +    branch_plan.add(
        +        pa.table(
        +            {
        +                "row_id": pa.array([0], type=pa.uint64()),
        +                "split_id": pa.array([0], type=pa.uint32()),
        +            }
        +        )
        +    )
        +    branch_plan = db.open_table("splits", branch="exp")
        +    assert branch_plan.version == 2
        +    assert branch_plan.count_rows() == 21
        +    branch_plan.tags.create("exp_v2", 2)
        +
        +    permutation = Permutation.from_tables(tbl, main_plan)
        +
        +    # Move the same passed-in plan handle to the other branch at the same
        +    # numeric version. Pickle must still reopen the captured main snapshot.
        +    main_plan.checkout("exp_v2")
        +    assert main_plan.current_branch() == "exp"
        +    assert main_plan.version == 2
        +    payload = pickle.dumps(permutation)
        +
        +    restored = pickle.loads(payload)
        +    assert restored.permutation_table.current_branch() is None
        +    assert restored.permutation_table.version == 2
        +    assert restored.num_rows == 20
        +
        +
        +def test_persisted_plan_pickle_reopens_in_spawned_process(tmp_path):
        +    import multiprocessing as mp
        +    import pickle
        +
        +    db = connect(tmp_path)
        +    tbl = db.create_table("base", pa.table({"id": range(12)}))
        +    plan = permutation_builder(tbl).persist(db, "splits").execute()
        +    payload = pickle.dumps(Permutation.from_tables(tbl, plan))
        +
        +    tbl.add(pa.table({"id": range(12, 24)}))
        +    permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute()
        +
        +    context = mp.get_context("spawn")
        +    output = context.Queue()
        +    process = context.Process(
        +        target=_read_permutation_in_spawned_process, args=(payload, output)
        +    )
        +    process.start()
        +    try:
        +        ids = output.get(timeout=60)
        +    finally:
        +        process.join(timeout=60)
        +
        +    assert process.exitcode == 0
        +    assert sorted(ids) == list(range(12))
        +
        +
        +def test_old_permutation_pickle_state_still_round_trips(tmp_path):
        +    db = connect(tmp_path)
        +    tbl = db.create_table("base", pa.table({"id": range(20)}))
        +    plan = permutation_builder(tbl).execute()
        +    state = {
        +        "base_table_name": tbl.name,
        +        "permutation_data": plan.to_arrow(),
        +        "split": 0,
        +        "selection": {"id": "id"},
        +        "batch_size": DEFAULT_BATCH_SIZE,
        +        "transform_fn": Transforms.arrow2python,
        +        "offset": None,
        +        "limit": None,
        +        "connection_factory": None,
        +        "base_table_uri": str(tmp_path),
        +        "base_table_storage_options": None,
        +        "base_table_namespace": [],
        +    }
        +
        +    restored = Permutation.__new__(Permutation)
        +    restored.__setstate__(state)
        +
        +    assert restored.base_version == tbl.version
        +    assert restored.base_branch is None
        +    assert sorted(
        +        row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
        +    ) == list(range(20))
        +
        +
        +def test_builder_copy_is_shallow_and_does_not_materialize(
        +    some_table: Table, some_perm_table: Table, monkeypatch
        +):
        +    """The with_* builders use copy.copy, which must stay a shallow copy.
        +
        +    Without ``Permutation.__copy__`` the copy falls back to the pickle path,
        +    which materializes the permutation table with ``to_arrow()`` before
        +    rebuilding the base table and reader. That is expensive for in-memory
        +    tables and fails for remote permutation tables.
        +    """
        +    permutation = Permutation.from_tables(some_table, some_perm_table)
        +
        +    def fail_materialize(*args, **kwargs):
        +        raise AssertionError("copy.copy must not materialize the permutation table")
        +
        +    def fail_getstate(_self):
        +        raise AssertionError("copy.copy must not pickle the permutation")
        +
        +    monkeypatch.setattr(permutation.permutation_table, "to_arrow", fail_materialize)
        +    monkeypatch.setattr(Permutation, "__getstate__", fail_getstate)
        +
        +    formatted = permutation.with_format("arrow")
        +    assert formatted is not permutation
        +    assert formatted.transform_fn is Transforms.arrow2arrow
        +    assert permutation.transform_fn is Transforms.arrow2python
        +    assert formatted.base_table is permutation.base_table
        +    assert formatted.permutation_table is permutation.permutation_table
        +    assert formatted.reader is permutation.reader
        +
        +    resized = permutation.with_batch_size(7)
        +    assert resized.batch_size == 7
        +    assert permutation.batch_size == DEFAULT_BATCH_SIZE
        +    assert resized.selection is permutation.selection
        +    resized.selection = {"id": "id"}
        +    assert permutation.selection is not resized.selection
        +
        +
         def test_split_random_counts(mem_db):
             """Test random splitting with absolute counts."""
             tbl = mem_db.create_table(
        @@ -275,6 +655,41 @@ def test_split_hash(mem_db):
             assert data["split_id"] == data2["split_id"]  # Should be identical
         
         
        +def test_split_hash_default_discard_weight_matches_zero(mem_db):
        +    """Omitting discard_weight must assign every row like discard_weight=0."""
        +    tbl = mem_db.create_table(
        +        "test_table",
        +        pa.table(
        +            {
        +                "id": range(100),
        +                "category": (["A", "B", "C"] * 34)[:100],
        +                "value": range(100),
        +            }
        +        ),
        +    )
        +
        +    default = (
        +        permutation_builder(tbl)
        +        .split_hash(["category"], [1, 1], split_names=["train", "test"])
        +        .execute()
        +    )
        +    explicit_zero = (
        +        permutation_builder(tbl)
        +        .split_hash(
        +            ["category"], [1, 1], discard_weight=0, split_names=["train", "test"]
        +        )
        +        .execute()
        +    )
        +
        +    default_data = default.search(None).to_arrow().to_pydict()
        +    explicit_data = explicit_zero.search(None).to_arrow().to_pydict()
        +    assert default.count_rows() == 100
        +    assert default.count_rows() == explicit_zero.count_rows()
        +    assert dict(zip(default_data["row_id"], default_data["split_id"])) == dict(
        +        zip(explicit_data["row_id"], explicit_data["split_id"])
        +    )
        +
        +
         def test_split_hash_with_discard(mem_db):
             """Test hash-based splitting with discard weight."""
             tbl = mem_db.create_table(
        @@ -1146,6 +1561,31 @@ def test_transform_fn_pandas(mem_db):
             assert isinstance(result, pd.DataFrame)
         
         
        +def test_numpy_format_mixed_columns_is_object_ndarray(mem_db):
        +    pytest.importorskip("pandas")
        +    import numpy as np
        +
        +    tbl = mem_db.create_table(
        +        "test_table",
        +        pa.table(
        +            {
        +                "id": range(3),
        +                "vector": pa.array(
        +                    [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
        +                    type=pa.list_(pa.float32(), 2),
        +                ),
        +            }
        +        ),
        +    )
        +    permutation = Permutation.identity(tbl).with_format("numpy")
        +    result = next(permutation.iter(2, skip_last_batch=False))
        +
        +    assert isinstance(result, np.ndarray)
        +    assert result.dtype == object
        +    assert result.shape == (2, 2)
        +    np.testing.assert_array_equal(result[0, 1], [1.0, 2.0])
        +
        +
         def test_custom_transform(mem_db):
             tbl = mem_db.create_table(
                 "test_table", pa.table({"id": range(10), "value": range(10)})
        @@ -1416,3 +1856,244 @@ def test_from_tables_split_without_permutation_table(mem_db):
         
             with pytest.raises(ValueError, match="permutation on split `train` because no"):
                 Permutation.from_tables(tbl, split="train")
        +
        +
        +def _double_value_row(row):
        +    return {"id": row["id"], "value": row["value"] * 2}
        +
        +
        +def _double_value_batch(batch):
        +    return {"id": batch["id"], "value": [value * 2 for value in batch["value"]]}
        +
        +
        +def test_map_row_by_row(some_permutation: Permutation):
        +    """Test .map() applies fn to each row individually."""
        +    mapped = some_permutation.map(_double_value_row)
        +    batches = list(mapped.iter(10, skip_last_batch=False))
        +    first_batch = batches[0]
        +    assert len(first_batch) == 10
        +    assert isinstance(first_batch[0], dict)
        +    for row in first_batch:
        +        assert row["value"] == row["id"] * 2
        +
        +
        +def test_map_batched(some_permutation: Permutation):
        +    """Test batched only changes what fn receives, not what is yielded."""
        +    seen = []
        +
        +    def double_value(batch):
        +        seen.append(batch)
        +        return _double_value_batch(batch)
        +
        +    mapped = some_permutation.map(double_value, batched=True)
        +    first_batch = next(mapped.iter(10, skip_last_batch=False))
        +    assert isinstance(seen[0], dict)
        +    assert len(seen[0]["id"]) == 10
        +    assert first_batch == next(
        +        some_permutation.map(_double_value_row).iter(10, skip_last_batch=False)
        +    )
        +
        +
        +def test_map_chain(some_permutation: Permutation):
        +    """Test chained maps run in order and each one replaces the whole row."""
        +
        +    def add_doubled(row):
        +        return {**row, "doubled": row["value"] * 2}
        +
        +    def to_total(batch):
        +        return {
        +            "total": [a + b for a, b in zip(batch["value"], batch["doubled"])],
        +        }
        +
        +    def add_label(row):
        +        return {**row, "label": str(row["total"])}
        +
        +    first = some_permutation.map(add_doubled)
        +    mapped = first.map(to_total, batched=True).map(add_label)
        +    expected = [
        +        {"total": row["value"] * 3, "label": str(row["value"] * 3)}
        +        for row in some_permutation.take_offsets([0, 1, 2])
        +    ]
        +    assert mapped.take_offsets([0, 1, 2]) == expected
        +    assert next(mapped.iter(3, skip_last_batch=False)) == expected
        +    # Extending a chain does not change the permutation it was derived from
        +    assert set(first.take_offsets([0])[0]) == {"id", "value", "doubled"}
        +
        +
        +@pytest.mark.parametrize(
        +    "explicit",
        +    [
        +        lambda permutation: permutation.with_format("python"),
        +        lambda permutation: permutation.with_format("arrow"),
        +        lambda permutation: permutation.with_transform(Transforms.arrow2arrow),
        +    ],
        +)
        +def test_map_rejects_format_and_transform(some_permutation: Permutation, explicit):
        +    """Test .map() cannot be mixed with with_format or with_transform."""
        +    with pytest.raises(ValueError, match="map cannot be combined"):
        +        explicit(some_permutation).map(_double_value_row)
        +    with pytest.raises(ValueError, match="map cannot be combined"):
        +        explicit(some_permutation.map(_double_value_row))
        +
        +
        +def test_map_rejects_format_without_optional_dependency(
        +    some_permutation: Permutation, monkeypatch
        +):
        +    """Test the map check runs before a format imports an optional dependency."""
        +    import sys
        +
        +    # Make polars fail to import, as it does on an install without extras
        +    monkeypatch.setitem(sys.modules, "polars", None)
        +    with pytest.raises(ValueError, match="map cannot be combined"):
        +        some_permutation.map(_double_value_row).with_format("polars")
        +
        +
        +def test_map_rejects_explicit_transform_from_old_pickle(
        +    some_permutation: Permutation,
        +):
        +    """Test pickles written before explicit_transform existed keep the guard."""
        +
        +    def restore_without_flag(permutation):
        +        state = permutation.__getstate__()
        +        del state["explicit_transform"]
        +        restored = Permutation.__new__(Permutation)
        +        restored.__setstate__(state)
        +        return restored
        +
        +    with pytest.raises(ValueError, match="map cannot be combined"):
        +        restore_without_flag(some_permutation.with_format("arrow")).map(
        +            _double_value_row
        +        )
        +    # The default transform is indistinguishable from an explicit "python" format
        +    mapped = restore_without_flag(some_permutation).map(_double_value_row)
        +    assert mapped.take_offsets([0]) == [
        +        _double_value_row(row) for row in some_permutation.take_offsets([0])
        +    ]
        +
        +
        +def test_map_rejects_transform_passed_to_constructor(some_table: Table):
        +    """Test a transform given to the constructor counts as explicit too."""
        +    permutation = Permutation(
        +        some_table,
        +        None,
        +        0,
        +        {"id": "id"},
        +        DEFAULT_BATCH_SIZE,
        +        Transforms.arrow2arrow,
        +    )
        +    with pytest.raises(ValueError, match="map cannot be combined"):
        +        permutation.map(_double_value_row)
        +
        +
        +def test_map_take_offsets(some_permutation: Permutation):
        +    """Test .map() keeps the positions and duplicates of the requested offsets."""
        +    calls = []
        +
        +    def record(batch):
        +        calls.append(batch)
        +        return batch
        +
        +    mapped = some_permutation.map(_double_value_row).map(record, batched=True)
        +    offsets = [5, 0, 5, 2]
        +    expected = [
        +        _double_value_row(row) for row in some_permutation.take_offsets(offsets)
        +    ]
        +    assert mapped.take_offsets(offsets) == expected
        +    assert mapped.__getitems__(offsets) == expected
        +
        +    calls.clear()
        +    assert mapped.take_offsets([]) == []
        +    assert calls == []
        +
        +
        +def test_map_validates_output(some_permutation: Permutation):
        +    """Test .map() rejects callback output that would break the batch shape."""
        +    with pytest.raises(ValueError, match="returned 1 values for column `id`"):
        +        some_permutation.map(
        +            lambda batch: {"id": batch["id"][:1]}, batched=True
        +        ).take_offsets([0, 1])
        +    with pytest.raises(TypeError, match="must return a dict of columns, got list"):
        +        some_permutation.map(
        +            lambda batch: list(batch.values()), batched=True
        +        ).take_offsets([0, 1])
        +    # A str has the right length here but is still not a column of values
        +    for value in (2, "ab"):
        +        with pytest.raises(TypeError, match="list of values for column `n`, got"):
        +            some_permutation.map(lambda batch: {"n": value}, batched=True).take_offsets(
        +                [0, 1]
        +            )
        +    with pytest.raises(
        +        TypeError, match="must return a dict for each row, got NoneType"
        +    ):
        +        some_permutation.map(lambda row: None).take_offsets([0, 1])
        +    with pytest.raises(ValueError, match="did not return the same keys for every row"):
        +        some_permutation.map(
        +            lambda row: row if row["id"] % 2 else {"id": row["id"]}
        +        ).map(lambda batch: batch, batched=True).take_offsets(list(range(10)))
        +
        +
        +def test_map_projection_and_schema(some_permutation: Permutation):
        +    """Test the selection and schema describe the read that feeds the callbacks."""
        +
        +    def to_str(row):
        +        return {name: str(value) for name, value in row.items()}
        +
        +    mapped = some_permutation.map(to_str)
        +    assert mapped.schema == some_permutation.schema
        +    assert mapped.column_names == ["id", "value"]
        +
        +    for projected in (
        +        some_permutation.select_columns(["id"]).map(to_str),
        +        mapped.select_columns(["id"]),
        +        mapped.remove_columns(["value"]),
        +    ):
        +        assert projected.schema == some_permutation.select_columns(["id"]).schema
        +        assert list(projected.take_offsets([0])[0]) == ["id"]
        +
        +    renamed = mapped.rename_column("value", "data")
        +    assert renamed.column_names == ["id", "data"]
        +    assert list(renamed.take_offsets([0])[0]) == ["id", "data"]
        +
        +
        +def test_map_is_lazy(some_permutation: Permutation):
        +    """Test .map() does not call fn until iteration."""
        +    call_count = [0]
        +
        +    def counting_fn(row):
        +        call_count[0] += 1
        +        return row
        +
        +    mapped = some_permutation.map(counting_fn)
        +    assert call_count[0] == 0
        +
        +    mapped.__getitems__([0])
        +    assert call_count[0] == 1
        +
        +
        +def test_map_non_callable(some_permutation: Permutation):
        +    """Test .map() raises TypeError for non-callable fn."""
        +    with pytest.raises(TypeError, match="fn must be callable"):
        +        some_permutation.map("not a function")
        +
        +
        +@pytest.mark.parametrize(
        +    "fn, batched", [(_double_value_row, False), (_double_value_batch, True)]
        +)
        +def test_map_pickle_round_trip(some_permutation: Permutation, fn, batched):
        +    """Test a mapped permutation reads the same data after a pickle round trip."""
        +    import pickle
        +
        +    mapped = some_permutation.map(fn, batched=batched)
        +    restored = pickle.loads(pickle.dumps(mapped))
        +
        +    offsets = [3, 1, 3]
        +    assert restored.take_offsets(offsets) == mapped.take_offsets(offsets)
        +    assert restored.take_offsets(offsets)[0]["value"] == (
        +        some_permutation.take_offsets(offsets)[0]["value"] * 2
        +    )
        +    # The restored permutation keeps enforcing the map / format constraint
        +    with pytest.raises(ValueError, match="map cannot be combined"):
        +        restored.with_format("arrow")
        +    explicit = pickle.loads(pickle.dumps(some_permutation.with_format("arrow")))
        +    with pytest.raises(ValueError, match="map cannot be combined"):
        +        explicit.map(fn, batched=batched)
        diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py
        index a4ac3851d..ed8e0d24f 100644
        --- a/python/python/tests/test_query.py
        +++ b/python/python/tests/test_query.py
        @@ -69,6 +69,36 @@ def _blob_query_data():
             )
         
         
        +def _fragment_query_data():
        +    return pa.table(
        +        {
        +            "id": pa.array([1, 2, 3, 4], pa.int64()),
        +            "text": pa.array(["one", "two", "three", "four"], pa.utf8()),
        +            "vector": pa.array(
        +                [[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]],
        +                type=pa.list_(pa.float32(), list_size=2),
        +            ),
        +        }
        +    )
        +
        +
        +def _fragment_query_table(db, name):
        +    data = _fragment_query_data()
        +    table = db.create_table(name, data.slice(0, 2))
        +    table.add(data.slice(2, 2))
        +    return table
        +
        +
        +def _apply_fragment_restriction(query, restriction, fragment):
        +    if restriction == "ids":
        +        return query.fragment_ids([fragment.fragment_id])
        +    if restriction == "empty":
        +        return query.fragment_ids([])
        +    if restriction == "fragments":
        +        return query.with_fragments([fragment])
        +    raise AssertionError(f"unknown restriction: {restriction}")
        +
        +
         def _create_blob_v2_query_table(db, name):
             schema = pa.schema(
                 [
        @@ -348,7 +378,7 @@ def test_plain_scan_query_to_pandas_blob_bytes_projection(tmp_db, blob_schema):
         
         
         @pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
        -def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
        +def test_plain_scan_query_to_pandas_blob_mode_uses_native_path(
             tmp_db, monkeypatch, blob_mode
         ):
             pytest.importorskip("lance")
        @@ -362,7 +392,8 @@ def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
             def fail_to_arrow(*args, **kwargs):
                 raise AssertionError("to_arrow should not be called before native pandas")
         
        -    monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
        +    if blob_mode == "descriptions":
        +        monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
         
             df = query.to_pandas(blob_mode=blob_mode)
         
        @@ -434,6 +465,207 @@ def test_plain_scan_query_to_pandas_scanner_state(tmp_db):
             )
             assert df_by_fragment["id"].tolist() == [1, 2]
         
        +    empty = (
        +        table.search()
        +        .select(["id", "blob"])
        +        .fragment_ids([])
        +        .to_pandas(blob_mode="descriptions")
        +    )
        +    assert empty.empty
        +    with pytest.raises(ValueError, match="fragment_ids not found in dataset: 999"):
        +        (
        +            table.search()
        +            .select(["id", "blob"])
        +            .fragment_ids([999])
        +            .to_pandas(blob_mode="descriptions")
        +        )
        +
        +
        +@pytest.mark.parametrize(
        +    "terminal",
        +    [
        +        "to_arrow",
        +        "to_batches",
        +        "to_pandas",
        +        "to_polars",
        +        "to_list",
        +        "explain_plan",
        +        "analyze_plan",
        +    ],
        +)
        +def test_fragment_constraints_fail_loud_on_unsupported_paths(tmp_db, terminal):
        +    pytest.importorskip("lance")
        +    table = _fragment_query_table(tmp_db, f"fragment_guard_{terminal}")
        +    fragment_id = table.to_lance().get_fragments()[0].fragment_id
        +    query = table.search().fragment_ids([fragment_id])
        +
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        getattr(query, terminal)()
        +
        +
        +def test_with_fragments_fails_loud_on_plain_and_vector_queries(tmp_db):
        +    pytest.importorskip("lance")
        +    table = _fragment_query_table(tmp_db, "fragment_guard_with_fragments")
        +    fragment = table.to_lance().get_fragments()[0]
        +
        +    for query in (
        +        table.search().with_fragments([fragment]),
        +        table.search([0.0, 0.0]).with_fragments([fragment]),
        +    ):
        +        with pytest.raises(NotImplementedError, match="fragment selection"):
        +            query.to_arrow()
        +
        +
        +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
        +def test_fts_count_rows_rejects_fragment_constraints(tmp_db, restriction):
        +    pytest.importorskip("lance")
        +    table = _fragment_query_table(tmp_db, f"fts_count_rows_{restriction}")
        +    table.create_index("text", config=FTS(with_position=False))
        +    fragment = table.to_lance().get_fragments()[1]
        +    query = _apply_fragment_restriction(
        +        table.search("one", query_type="fts"), restriction, fragment
        +    )
        +
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        query.count_rows()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize(
        +    "terminal",
        +    [
        +        "to_arrow",
        +        "to_batches",
        +        "to_pandas",
        +        "to_polars",
        +        "to_list",
        +        "explain_plan",
        +        "analyze_plan",
        +    ],
        +)
        +async def test_async_fragment_constraints_fail_loud_on_unsupported_paths(
        +    tmp_db_async, terminal
        +):
        +    pytest.importorskip("lance")
        +    data = _fragment_query_data()
        +    table = await tmp_db_async.create_table(
        +        f"async_fragment_guard_{terminal}", data.slice(0, 2)
        +    )
        +    await table.add(data.slice(2, 2))
        +    fragments = (await table.to_lance()).get_fragments()
        +    query = table.query().fragment_ids([fragments[0].fragment_id])
        +
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        await getattr(query, terminal)()
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_with_fragments_fails_loud_on_plain_and_vector_queries(
        +    tmp_db_async,
        +):
        +    pytest.importorskip("lance")
        +    data = _fragment_query_data()
        +    table = await tmp_db_async.create_table(
        +        "async_fragment_guard_with_fragments", data.slice(0, 2)
        +    )
        +    await table.add(data.slice(2, 2))
        +    fragments = (await table.to_lance()).get_fragments()
        +
        +    for query in (
        +        table.query().with_fragments([fragments[0]]),
        +        table.query().nearest_to([0.0, 0.0]).with_fragments([fragments[0]]),
        +    ):
        +        with pytest.raises(NotImplementedError, match="fragment selection"):
        +            await query.to_arrow()
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_plain_scan_fragment_constraints_preserved(tmp_db_async):
        +    pytest.importorskip("lance")
        +    data = _blob_query_data()
        +    table = await tmp_db_async.create_table(
        +        "async_fragment_supported",
        +        data.slice(0, 2),
        +        storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
        +    )
        +    await table.add(data.slice(2, 2))
        +    fragments = (await table.to_lance()).get_fragments()
        +
        +    df = await (
        +        table.query()
        +        .select(["id", "blob"])
        +        .fragment_ids([fragments[1].fragment_id])
        +        .to_pandas(blob_mode="descriptions")
        +    )
        +
        +    assert df["id"].tolist() == [3, 4]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
        +async def test_async_fts_count_rows_rejects_fragment_constraints(
        +    tmp_db_async, restriction
        +):
        +    pytest.importorskip("lance")
        +    data = _fragment_query_data()
        +    table = await tmp_db_async.create_table(
        +        f"async_fts_count_rows_{restriction}", data.slice(0, 2)
        +    )
        +    await table.add(data.slice(2, 2))
        +    await table.create_index("text", config=FTS(with_position=False))
        +    fragment = (await table.to_lance()).get_fragments()[1]
        +    query = _apply_fragment_restriction(
        +        table.query().nearest_to_text("one"), restriction, fragment
        +    )
        +
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        await query.count_rows()
        +
        +    transitioned = _apply_fragment_restriction(
        +        table.query(), restriction, fragment
        +    ).nearest_to_text("one")
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        await transitioned.count_rows()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
        +@pytest.mark.parametrize(
        +    "transition",
        +    ["query_to_vector", "query_to_fts", "fts_to_hybrid", "vector_to_hybrid"],
        +)
        +async def test_async_fragment_constraints_survive_query_transitions(
        +    tmp_db_async, transition, restriction
        +):
        +    pytest.importorskip("lance")
        +    data = _fragment_query_data()
        +    table = await tmp_db_async.create_table(
        +        f"async_transition_{transition}_{restriction}", data.slice(0, 2)
        +    )
        +    await table.add(data.slice(2, 2))
        +    await table.create_index("text", config=FTS(with_position=False))
        +    fragment = (await table.to_lance()).get_fragments()[1]
        +
        +    if transition == "query_to_vector":
        +        query = _apply_fragment_restriction(
        +            table.query(), restriction, fragment
        +        ).nearest_to([0.0, 0.0])
        +    elif transition == "query_to_fts":
        +        query = _apply_fragment_restriction(
        +            table.query(), restriction, fragment
        +        ).nearest_to_text("one")
        +    elif transition == "fts_to_hybrid":
        +        query = _apply_fragment_restriction(
        +            table.query().nearest_to_text("one"), restriction, fragment
        +        ).nearest_to([0.0, 0.0])
        +    else:
        +        query = _apply_fragment_restriction(
        +            table.query().nearest_to([0.0, 0.0]), restriction, fragment
        +        ).nearest_to_text("one")
        +
        +    with pytest.raises(NotImplementedError, match="fragment selection"):
        +        await query.to_arrow()
        +
         
         @pytest.mark.asyncio
         async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async):
        @@ -488,7 +720,7 @@ async def test_async_plain_scan_query_to_pandas_blob_bytes_projection(
         
         @pytest.mark.asyncio
         @pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
        -async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
        +async def test_async_plain_scan_query_to_pandas_blob_mode_uses_native_path(
             tmp_db_async, monkeypatch, blob_mode
         ):
             pytest.importorskip("lance")
        @@ -502,7 +734,8 @@ async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow
             async def fail_to_arrow(*args, **kwargs):
                 raise AssertionError("to_arrow should not be called before native pandas")
         
        -    monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
        +    if blob_mode == "descriptions":
        +        monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
         
             df = await query.to_pandas(blob_mode=blob_mode)
         
        @@ -541,12 +774,14 @@ def test_vector_query_to_pandas_legacy_blob_descriptions_and_bytes(tmp_db):
             df = query.to_pandas(blob_mode="descriptions")
             assert df["blob"].tolist() == [{"position": 0, "size": 3}]
         
        -    with pytest.raises(ValueError, match="legacy blob columns"):
        +    with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
                 query.to_pandas(blob_mode="bytes")
        -    with pytest.raises(ValueError, match="legacy blob columns"):
        +    with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
                 query.to_arrow(blob_mode="bytes")
        -    with pytest.raises(ValueError, match="legacy blob columns"):
        -        table.to_arrow(blob_mode="bytes")
        +    table_arrow = table.to_arrow(blob_mode="bytes")
        +    assert table_arrow.schema.field("blob").type == pa.large_binary()
        +    assert "_rowid" not in table_arrow.column_names
        +    assert table_arrow["blob"].to_pylist() == [b"one", b"two", b"three", b"four"]
             assert table.to_pandas(blob_mode="bytes")["blob"].tolist() == [
                 b"one",
                 b"two",
        @@ -740,6 +975,10 @@ async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async):
         
             df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes")
             assert set(df["blob"]) == {b"two", b"three"}
        +    ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas(
        +        blob_mode="bytes"
        +    )
        +    assert ordered["blob"].tolist() == [b"three", b"two"]
         
         
         def test_order_by_plain_query(mem_db):
        @@ -807,6 +1046,308 @@ async def test_order_by_async_query(mem_db_async: AsyncConnection):
             ]
         
         
        +def test_order_by_accepts_strings_tuples_and_dicts(mem_db):
        +    table = mem_db.create_table(
        +        "test_order_by_forms",
        +        pa.table(
        +            {
        +                "group": [1, 1, 1, 2],
        +                "score": [None, 1.0, 1.0, 0.5],
        +                "name": ["z", "b", "a", "c"],
        +            }
        +        ),
        +    )
        +
        +    rows = (
        +        table.search()
        +        .order_by(
        +            [
        +                "group",
        +                ("score", "desc"),
        +                {"column_name": "name", "ascending": True},
        +            ]
        +        )
        +        .select(["name"])
        +        .to_list()
        +    )
        +    assert rows == [{"name": "a"}, {"name": "b"}, {"name": "z"}, {"name": "c"}]
        +
        +    # A bare tuple is one direction pair; a list holds separate orderings.
        +    assert table.search().order_by("name").select(["name"]).to_list() == [
        +        {"name": "a"},
        +        {"name": "b"},
        +        {"name": "c"},
        +        {"name": "z"},
        +    ]
        +    assert table.search().order_by(("name", "desc")).select(["name"]).to_list() == [
        +        {"name": "z"},
        +        {"name": "c"},
        +        {"name": "b"},
        +        {"name": "a"},
        +    ]
        +    assert table.search().order_by(["group", "name"]).select(["name"]).to_list() == [
        +        {"name": "a"},
        +        {"name": "b"},
        +        {"name": "z"},
        +        {"name": "c"},
        +    ]
        +
        +
        +def test_order_by_clears_with_none_and_empty_list(mem_db):
        +    table = mem_db.create_table("test_order_by_clear", [{"name": "a"}])
        +
        +    query = table.search().order_by("name")
        +    assert query.to_query_object().order_by is not None
        +    assert query.order_by(None).to_query_object().order_by is None
        +    assert query.order_by([]).to_query_object().order_by is None
        +
        +
        +def test_scan_in_order_plain_query(tmp_db):
        +    table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]}))
        +    table.add(pa.table({"id": [2, 3]}))
        +    table.add(pa.table({"id": [4, 5]}))
        +
        +    fragments = table.to_lance().get_fragments()
        +    assert len(fragments) == 3, "the test needs real multi-fragment data"
        +
        +    version = table.version
        +    table.checkout(version)
        +
        +    default = table.search().select(["id"]).to_arrow()["id"].to_pylist()
        +    assert default == [0, 1, 2, 3, 4, 5]
        +    assert table.search().to_query_object().scan_in_order is None
        +
        +    ordered = table.search().scan_in_order().select(["id"]).to_arrow()
        +    assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
        +    repeated = table.search().scan_in_order(True).select(["id"]).to_arrow()
        +    assert repeated.equals(ordered)
        +
        +    unordered = (
        +        table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist()
        +    )
        +    assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
        +
        +    sorted_desc = (
        +        table.search()
        +        .scan_in_order(False)
        +        .order_by(("id", "desc"))
        +        .select(["id"])
        +        .to_arrow()["id"]
        +        .to_pylist()
        +    )
        +    assert sorted_desc == [5, 4, 3, 2, 1, 0]
        +
        +    with pytest.raises(ValueError, match="nonempty order_by"):
        +        table.search().scan_in_order().order_by("id").to_arrow()
        +
        +
        +@pytest.mark.asyncio
        +async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection):
        +    table = await tmp_db_async.create_table(
        +        "scan_in_order_async", pa.table({"id": [0, 1]})
        +    )
        +    await table.add(pa.table({"id": [2, 3]}))
        +    await table.add(pa.table({"id": [4, 5]}))
        +
        +    assert len((await table.to_lance()).get_fragments()) == 3
        +    version = await table.version()
        +    await table.checkout(version)
        +
        +    ordered = await table.query().scan_in_order().select(["id"]).to_arrow()
        +    assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
        +    assert table.query().to_query_object().scan_in_order is None
        +
        +    unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[
        +        "id"
        +    ].to_pylist()
        +    assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
        +
        +    with pytest.raises(ValueError, match="nonempty order_by"):
        +        await table.query().scan_in_order().order_by("id").to_arrow()
        +    with pytest.raises(ValueError, match="ranked results"):
        +        await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow()
        +
        +
        +@pytest.mark.parametrize("ordered", [False, True])
        +def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered):
        +    pytest.importorskip("lance")
        +    data = _blob_query_data()
        +    table = tmp_db.create_table(
        +        f"scan_in_order_scanner_{ordered}",
        +        data.slice(0, 2),
        +        storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
        +    )
        +    table.add(data.slice(2, 2))
        +
        +    query = table.search().select(["id", "blob"]).scan_in_order(ordered)
        +
        +    def fail_to_arrow(*args, **kwargs):
        +        raise AssertionError("scanner-backed pandas must not collect through to_arrow")
        +
        +    monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
        +
        +    dataset = table.to_lance()
        +    dataset_cls = type(dataset)
        +    real_scanner = dataset_cls.scanner
        +    captured = {}
        +
        +    def capture_scanner(self, **kwargs):
        +        captured.update(kwargs)
        +        return real_scanner(self, **kwargs)
        +
        +    monkeypatch.setattr(dataset_cls, "scanner", capture_scanner)
        +
        +    df = query.to_pandas(blob_mode="descriptions", flatten=True)
        +
        +    assert captured["scan_in_order"] is ordered
        +    assert captured.get("use_scalar_index") is (False if ordered else None)
        +    assert sorted(df["id"].tolist()) == [1, 2, 3, 4]
        +
        +
        +@pytest.mark.parametrize("storage_version", ["legacy", "stable"])
        +def test_scan_in_order_indexed_filter_preserves_manifest_order(
        +    tmp_path, storage_version
        +):
        +    lance = pytest.importorskip("lance")
        +    data = pa.table({"id": list(range(20)), "value": list(range(20))})
        +    dataset = lance.write_dataset(
        +        data,
        +        tmp_path / "t.lance",
        +        data_storage_version=storage_version,
        +        max_rows_per_file=10,
        +    )
        +    dataset.create_scalar_index("value", "BTREE")
        +    version_before_update = dataset.version
        +    dataset.update({"value": "100"}, where="id = 0")
        +
        +    table = lancedb.connect(str(tmp_path)).open_table("t")
        +    for version in (version_before_update, dataset.version):
        +        table.checkout(version)
        +        base = table.search().scan_in_order(True).select(["id"]).limit(100)
        +        expected = base.to_arrow()["id"].to_pylist()
        +        actual = base.where("value < 1000").to_arrow()["id"].to_pylist()
        +        assert actual == expected
        +
        +
        +def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db):
        +    pytest.importorskip("lance")
        +    data = _blob_query_data()
        +    table = tmp_db.create_table(
        +        "scan_in_order_fragments",
        +        data.slice(0, 2),
        +        storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
        +    )
        +    table.add(data.slice(2, 2))
        +    table.checkout(table.version)
        +
        +    fragments = table.to_lance().get_fragments()
        +    reversed_fragments = fragments[::-1]
        +    with pytest.raises(ValueError, match="use fragment_ids"):
        +        (
        +            table.search()
        +            .scan_in_order()
        +            .select(["id", "blob"])
        +            .with_fragments(reversed_fragments)
        +            .to_pandas(blob_mode="descriptions", flatten=True)
        +        )
        +
        +    # fragment_ids is already resolved from the manifest and stays ordered.
        +    df_by_id = (
        +        table.search()
        +        .scan_in_order()
        +        .select(["id", "blob"])
        +        .fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
        +        .to_pandas(blob_mode="descriptions", flatten=True)
        +    )
        +    assert df_by_id["id"].tolist() == [1, 2, 3, 4]
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(
        +    tmp_db_async,
        +):
        +    pytest.importorskip("lance")
        +    data = _blob_query_data()
        +    table = await tmp_db_async.create_table(
        +        "scan_in_order_fragments_async",
        +        data.slice(0, 2),
        +        storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
        +    )
        +    await table.add(data.slice(2, 2))
        +    await table.checkout(await table.version())
        +
        +    fragments = (await table.to_lance()).get_fragments()
        +    reversed_fragments = fragments[::-1]
        +    with pytest.raises(ValueError, match="use fragment_ids"):
        +        await (
        +            table.query()
        +            .scan_in_order()
        +            .with_fragments(fragments[::-1])
        +            .select(["id", "blob"])
        +            .to_pandas(blob_mode="descriptions", flatten=True)
        +        )
        +
        +    df_by_id = await (
        +        table.query()
        +        .scan_in_order()
        +        .fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
        +        .select(["id", "blob"])
        +        .to_pandas(blob_mode="descriptions", flatten=True)
        +    )
        +    assert df_by_id["id"].tolist() == [1, 2, 3, 4]
        +
        +
        +def test_order_by_rejects_invalid_input_early(mem_db):
        +    table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}])
        +
        +    with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
        +        table.search().order_by([{"column": "name", "ascending": True}])
        +    with pytest.raises(ValueError, match="missing 'column_name'"):
        +        table.search().order_by({"ascending": True})
        +    with pytest.raises(ValueError, match="invalid direction"):
        +        table.search().order_by([("name", "sideways")])
        +    with pytest.raises(TypeError, match="must be a column name"):
        +        table.search().order_by([42])
        +
        +
        +@pytest.mark.asyncio
        +async def test_order_by_async_accepts_dicts_and_clears(mem_db_async: AsyncConnection):
        +    table = await mem_db_async.create_table(
        +        "test_order_by_async_forms",
        +        pa.table({"name": ["z", "b", "a", "c"]}),
        +    )
        +
        +    rows = await (
        +        table.query().order_by([{"column_name": "name", "ascending": False}]).to_arrow()
        +    )
        +    assert rows["name"].to_pylist() == ["z", "c", "b", "a"]
        +
        +    query = table.query().order_by("name")
        +    assert query.to_query_object().order_by is not None
        +    assert query.order_by(None).to_query_object().order_by is None
        +    assert query.order_by([]).to_query_object().order_by is None
        +
        +    with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
        +        table.query().order_by([{"column": "name"}])
        +
        +
        +def test_column_ordering_is_exported_at_top_level():
        +    assert lancedb.ColumnOrdering is ColumnOrdering
        +
        +
        +def test_order_by_hybrid_sync_is_explicitly_unsupported(table):
        +    query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("a")
        +
        +    with pytest.raises(NotImplementedError, match="order_by is not supported"):
        +        query.order_by(["id"])
        +
        +    # Clearing is still allowed, and invalid input still fails on its own terms.
        +    query.order_by(None)
        +    query.order_by([])
        +    with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
        +        query.order_by([{"column": "id"}])
        +
        +
         def test_query_builder(table):
             rs = (
                 LanceVectorQueryBuilder(table, [0, 0], "vector")
        @@ -1397,18 +1938,16 @@ def test_query_builder_with_different_vector_column():
             ds = mock.Mock()
             table.to_lance.return_value = ds
             builder.to_arrow()
        -    table._execute_query.assert_called_once_with(
        -        Query(
        -            vector=query,
        -            filter="b < 10",
        -            limit=2,
        -            distance_type="cosine",
        -            columns=["b"],
        -            vector_column="foo_vector",
        -        ),
        -        batch_size=None,
        -        timeout=None,
        +    expected = Query(
        +        vector=query,
        +        filter="b < 10",
        +        limit=2,
        +        distance_type="cosine",
        +        columns=["b"],
        +        vector_column="foo_vector",
             )
        +    expected._blob_row_id_prepared = True
        +    table._execute_arrow.assert_called_once_with(expected, timeout=None)
         
         
         def cosine_distance(vec1, vec2):
        @@ -2316,6 +2855,61 @@ def test_query_schema(tmp_path):
             )
         
         
        +def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table(
        +        "test",
        +        pa.table(
        +            {
        +                "id": [1, 2, 3],
        +                "vector": pa.array(
        +                    [[1, 2], [3, 4], [5, 6]],
        +                    pa.list_(pa.float32(), list_size=2),
        +                ),
        +            }
        +        ),
        +    )
        +
        +    calls = 0
        +    original = AsyncTable._schema_sync
        +
        +    def counted(self):
        +        nonlocal calls
        +        calls += 1
        +        return original(self)
        +
        +    monkeypatch.setattr(AsyncTable, "_schema_sync", counted)
        +
        +    table.search().where("id = 1").select(["id"]).to_arrow()
        +    assert calls <= 1
        +
        +    calls = 0
        +    table.search([1, 2], vector_column_name="vector").limit(1).to_arrow()
        +    assert calls <= 1
        +
        +    calls = 0
        +    table.search([1, 2]).limit(1).to_arrow()
        +    # At most one lookup infers the vector column, one prepares execution.
        +    assert calls <= 2
        +
        +    calls = 0
        +    table.search().where("id = 1").select(["id"]).to_batches().read_all()
        +    assert calls <= 1
        +
        +    builder = table.search().where("id = 1")
        +    before = builder.to_arrow()
        +    assert "extra" not in before.column_names
        +    assert "image" not in before.column_names
        +
        +    table.add_columns(pa.schema([pa.field("extra", pa.int64()), lancedb.blob("image")]))
        +    calls = 0
        +    after = builder.to_arrow()
        +    assert calls <= 1
        +    assert after["extra"].to_pylist() == [None]
        +    assert "_lance_row_id" in str(after.schema)
        +    assert "_rowid" not in after.column_names
        +
        +
         @pytest.mark.asyncio
         async def test_query_schema_async(tmp_path):
             db = await lancedb.connect_async(tmp_path)
        @@ -2417,13 +3011,116 @@ def test_take_queries(tmp_path):
             assert sorted(converted["idx"].to_pylist()) == [2, 5, 5, 17]
         
             # Take by row id
        -    assert list(
        -        sorted(table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list())
        -    ) == [
        -        2,
        -        5,
        -        17,
        -    ]
        +    assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17]
        +
        +
        +def test_take_offsets_preserve_order_sync(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("test", pa.table({"idx": range(4)}))
        +    table.add(pa.table({"idx": range(4, 8)}))
        +    table.delete("idx IN (1, 6)")
        +    requested = [5, 0, 5, 2, 99, 4, 0]
        +    expected = [7, 0, 7, 3, 5, 0]
        +
        +    actual = (
        +        table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow()
        +    )
        +    assert actual.column_names == ["idx"]
        +    assert actual["idx"].to_pylist() == expected
        +
        +    batches = list(
        +        table.take_offsets(requested, preserve_order=True)
        +        .select(["idx"])
        +        .to_batches(max_batch_length=1)
        +    )
        +    assert all(batch.num_rows <= 1 for batch in batches)
        +    assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
        +
        +    # The default path keeps its unspecified-order behavior.
        +    default = table.take_offsets(requested).select(["idx"]).to_arrow()
        +    assert sorted(default["idx"].to_pylist()) == sorted(expected)
        +
        +    assert table.take_offsets(requested).to_query_object().preserve_order is None
        +    query = (
        +        table.take_offsets(requested, preserve_order=True)
        +        .select(["idx"])
        +        .to_query_object()
        +    )
        +    assert query.preserve_order is True
        +    assert table._execute_query(query).read_all()["idx"].to_pylist() == expected
        +
        +    empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow()
        +    assert empty.num_rows == 0
        +    assert empty.column_names == ["idx"]
        +
        +    query.order_by = [ColumnOrdering(column_name="idx")]
        +    with pytest.raises(
        +        ValueError, match="preserve_order cannot be combined with an explicit order_by"
        +    ):
        +        table._execute_query(query)
        +
        +
        +@pytest.mark.asyncio
        +async def test_take_offsets_preserve_order_async(tmp_path):
        +    db = await lancedb.connect_async(tmp_path)
        +    table = await db.create_table("test", pa.table({"idx": range(4)}))
        +    await table.add(pa.table({"idx": range(4, 8)}))
        +    await table.delete("idx IN (1, 6)")
        +    requested = [5, 0, 5, 2, 99, 4, 0]
        +    expected = [7, 0, 7, 3, 5, 0]
        +
        +    actual = (
        +        await table.take_offsets(requested, preserve_order=True)
        +        .select(["idx"])
        +        .to_arrow()
        +    )
        +    assert actual.column_names == ["idx"]
        +    assert actual["idx"].to_pylist() == expected
        +
        +    reader = (
        +        await table.take_offsets(requested, preserve_order=True)
        +        .select(["idx"])
        +        .to_batches(max_batch_length=1)
        +    )
        +    batches = [batch async for batch in reader]
        +    assert all(batch.num_rows <= 1 for batch in batches)
        +    assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
        +
        +    query = (
        +        table.take_offsets(requested, preserve_order=True)
        +        .select(["idx"])
        +        .to_query_object()
        +    )
        +    assert query.preserve_order is True
        +
        +
        +@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}])
        +@pytest.mark.parametrize("empty", [False, True])
        +def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty):
        +    table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": [0, 1]}))
        +    table.add(pa.table({"idx": [2, 3]}))
        +    rows = table.search().with_row_id(True).to_arrow().to_pylist()
        +    row_ids = {row["idx"]: row["_rowid"] for row in rows}
        +    table.delete("idx = 1")
        +    requested = (
        +        [] if empty else [row_ids[3], row_ids[1], row_ids[3], 2**64 - 1, row_ids[0]]
        +    )
        +    take = table.take_row_ids(requested)
        +    if selection is not None:
        +        take = take.select(selection)
        +    actual = take.to_arrow()
        +    assert actual.num_rows == (0 if empty else 3)
        +    if selection == {"_rowid": "100 - idx"}:
        +        assert actual.column_names == ["_rowid"]
        +        assert actual["_rowid"].to_pylist() == ([] if empty else [97, 97, 100])
        +    elif selection == []:
        +        assert actual.num_columns == 0
        +    else:
        +        assert actual.column_names == ["idx"]
        +        assert actual["idx"].to_pylist() == ([] if empty else [3, 3, 0])
        +    query = take.to_query_object()
        +    assert query.take_row_ids == requested
        +    assert table._execute_query(query).read_all() == actual
         
         
         def test_take_queries_with_row_id(tmp_path):
        @@ -2432,6 +3129,7 @@ def test_take_queries_with_row_id(tmp_path):
         
             by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
             assert "_rowid" in by_row_id.column_names
        +    assert by_row_id["_rowid"].to_pylist() == [5, 2, 17]
             by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
             assert "_rowid" in by_offset.column_names
         
        @@ -2446,6 +3144,7 @@ async def test_take_queries_with_row_id_async(tmp_path):
         
             by_row_id = await table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
             assert "_rowid" in by_row_id.column_names
        +    assert by_row_id["_rowid"].to_pylist() == [5, 2, 17]
             by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
             assert "_rowid" in by_offset.column_names
         
        @@ -2472,16 +3171,12 @@ def test_take_queries_to_batches(tmp_path):
             rs = list(table.take_row_ids([5, 2, 17]).to_batches())
             assert all(isinstance(b, pa.RecordBatch) for b in rs)
             assert sum(b.num_rows for b in rs) == 3
        -    assert sorted(v for b in rs for v in b.column("idx").to_pylist()) == [2, 5, 17]
        +    assert [v for b in rs for v in b.column("idx").to_pylist()] == [5, 2, 17]
         
             # Take with select projection → to_batches preserves the projection
             rs = list(table.take_row_ids([5, 2, 17]).select(["label"]).to_batches())
             assert all(b.schema.names == ["label"] for b in rs)
        -    assert sorted(v for b in rs for v in b.column("label").to_pylist()) == [
        -        "17",
        -        "2",
        -        "5",
        -    ]
        +    assert [v for b in rs for v in b.column("label").to_pylist()] == ["5", "2", "17"]
         
         
         def test_getitems(tmp_path):
        @@ -2505,6 +3200,13 @@ def test_getitems(tmp_path):
             assert table.__getitems__(offsets) == pa.table({"idx": offsets})
         
         
        +def test_getitems_rejects_missing_offsets(tmp_path):
        +    table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)}))
        +
        +    with pytest.raises(pa.ArrowIndexError, match="out of bounds"):
        +        table.__getitems__([0, 99])
        +
        +
         @pytest.mark.asyncio
         async def test_query_timeout_async(tmp_path):
             db = await lancedb.connect_async(tmp_path)
        @@ -2637,17 +3339,24 @@ def test_blob_v2_to_batches_row_id(tmp_db):
             assert [blobs[i].as_py() for i in range(len(blobs))] == [b"one", b"two"]
         
         
        -@pytest.mark.parametrize("metric", ["l2", "cosine", "dot"])
         @pytest.mark.parametrize(
        -    "effort,probes", [(None, 4), (0, 1), (0.25, 2), (0.5, 4), (0.75, 8), (1, 16)]
        +    "metric,probes80,probes90", [("l2", 2, 3), ("cosine", 1, 2), ("dot", 1, 2)]
         )
        -def test_search_effort_probe_budget(tmp_path, monkeypatch, metric, effort, probes):
        +@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1])
        +def test_search_effort_probe_budget(
        +    tmp_path, monkeypatch, metric, effort, probes80, probes90
        +):
             import re
             from lancedb.index import IvfFlat
         
             monkeypatch.setenv("LANCE_AUTO_PROBE_MARGIN", "0")
             monkeypatch.setenv("LANCE_AUTO_MIN_INITIAL_NPROBES", "4")
             monkeypatch.setenv("LANCE_AUTO_MAX_INITIAL_NPROBES", "4")
        +    # The lower tiers use metric/k calibration; Auto and the upper tiers retain
        +    # their existing budgets. Keep exact execution counts and precedence checks.
        +    probes = {None: 4, 0: 1, 0.1: probes80, 0.25: probes90, 0.5: 4, 0.75: 8, 1: 16}[
        +        effort
        +    ]
             rng = np.random.default_rng(42)
             vectors = np.repeat(np.eye(16, dtype=np.float32), 32, axis=0)
             vectors += rng.normal(0, 0.001, vectors.shape).astype(np.float32)
        @@ -2731,7 +3440,7 @@ def test_search_effort_invalid_sync(table, effort):
         
         @pytest.mark.asyncio
         @pytest.mark.parametrize("hybrid", [False, True])
        -@pytest.mark.parametrize("effort", [None, 0, 0.25, 0.5, 0.75, 1])
        +@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1])
         async def test_search_effort_async_roundtrip(table_async, hybrid, effort):
             query = table_async.vector_search([0, 0])
             if hybrid:
        diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py
        index 1ee6d464b..5aae68a1c 100644
        --- a/python/python/tests/test_remote_db.py
        +++ b/python/python/tests/test_remote_db.py
        @@ -1,5 +1,6 @@
         # SPDX-License-Identifier: Apache-2.0
         # SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +import asyncio
         from concurrent.futures import ThreadPoolExecutor
         import contextlib
         import copy
        @@ -10,6 +11,7 @@ import io
         import inspect
         import json
         import multiprocessing as mp
        +from pathlib import Path
         import pickle
         import re
         import socket
        @@ -20,7 +22,9 @@ import threading
         import time
         from urllib.parse import parse_qs, urlparse
         from unittest.mock import MagicMock, patch
        +from types import SimpleNamespace
         import uuid
        +import warnings
         from packaging.version import Version
         from lance_namespace.errors import TableNotFoundError
         
        @@ -36,17 +40,21 @@ from lancedb.graph import (
             PropertyGraph,
             PropertyGraphDescription,
         )
        +from lancedb.functions import FunctionApplication, function
         from lancedb.query import (
             AsyncQuery,
             ColumnOrdering,
             LanceVectorQueryBuilder,
             MatchQuery,
         )
        +from lancedb.index import BTree
         from lancedb.remote import ClientConfig
         from lancedb.remote.errors import (
             AlreadyExistsError,
        +    ConflictError,
             HttpError,
             NamespaceNotFoundError,
        +    ResponseInterruptedError,
             RetryError,
         )
         import pytest
        @@ -54,20 +62,124 @@ import pyarrow as pa
         from utils import start_server_thread
         
         
        -def make_mock_http_handler(handler):
        +def make_mock_http_handler(handler, *, buffer_body=True):
             class MockLanceDBHandler(http.server.BaseHTTPRequestHandler):
                 def do_GET(self):
                     handler(self)
         
                 def do_POST(self):
        -            handler(self)
        +            if not buffer_body:
        +                handler(self)
        +                return
         
        -        def do_PUT(self):
        -            handler(self)
        +            # HTTP/1.0 closes after the response. Leaving a streamed upload unread
        +            # can reset the connection while the client is still writing its body.
        +            # Keep the original framing so handlers can inspect the actual request.
        +            source = self.rfile
        +            body = bytearray()
        +            if self.headers.get("Transfer-Encoding") == "chunked":
        +                while True:
        +                    line = source.readline()
        +                    assert line.endswith(b"\r\n")
        +                    body.extend(line)
        +                    size = int(line.split(b";")[0], 16)
        +                    if size == 0:
        +                        while True:
        +                            line = source.readline()
        +                            assert line.endswith(b"\r\n")
        +                            body.extend(line)
        +                            if line == b"\r\n":
        +                                break
        +                        break
        +                    chunk = source.read(size + 2)
        +                    assert len(chunk) == size + 2 and chunk[-2:] == b"\r\n"
        +                    body.extend(chunk)
        +            else:
        +                size = int(self.headers.get("Content-Length", 0))
        +                body.extend(source.read(size))
        +                assert len(body) == size
        +            self.rfile = io.BytesIO(body)
        +            try:
        +                handler(self)
        +            finally:
        +                self.rfile.close()
        +                self.rfile = source
        +
        +        do_PUT = do_POST
         
             return MockLanceDBHandler
         
         
        +@pytest.mark.parametrize("chunked", [False, True])
        +@pytest.mark.parametrize("read_body", [False, True])
        +def test_mock_http_handler_waits_for_body(chunked, read_body):
        +    body = (
        +        b"7;ext=value\r\npayload\r\n0\r\nX-Trailer: value\r\n\r\n"
        +        if chunked
        +        else b"payload"
        +    )
        +    received = []
        +
        +    def handler(request):
        +        if read_body:
        +            assert (request.headers.get("Transfer-Encoding") == "chunked") == chunked
        +            received.append(request.rfile.read(len(body)))
        +        request.send_response(200)
        +        request.end_headers()
        +
        +    with http.server.HTTPServer(
        +        ("127.0.0.1", 0), make_mock_http_handler(handler)
        +    ) as server:
        +        thread = start_server_thread(server)
        +        try:
        +            with socket.create_connection(server.server_address, timeout=2) as client:
        +                framing = (
        +                    "Transfer-Encoding: chunked" if chunked else "Content-Length: 7"
        +                )
        +                client.sendall(
        +                    f"POST / HTTP/1.0\r\nHost: localhost\r\n{framing}\r\n\r\n".encode()
        +                )
        +                client.settimeout(0.1)
        +                with pytest.raises(TimeoutError):
        +                    client.recv(1024)
        +                client.settimeout(2)
        +                client.sendall(body)
        +                assert client.recv(1024).startswith(b"HTTP/1.0 200")
        +        finally:
        +            server.shutdown()
        +            thread.join()
        +    assert received == ([body] if read_body else [])
        +
        +
        +@pytest.mark.parametrize("disconnect", [False, True])
        +def test_mock_http_handler_allows_early_failure(disconnect):
        +    def handler(request):
        +        if disconnect:
        +            request.connection.shutdown(socket.SHUT_RDWR)
        +            request.close_connection = True
        +        else:
        +            request.send_response(413)
        +            request.end_headers()
        +
        +    with http.server.HTTPServer(
        +        ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=False)
        +    ) as server:
        +        thread = start_server_thread(server)
        +        try:
        +            with socket.create_connection(server.server_address, timeout=2) as client:
        +                client.sendall(
        +                    b"POST / HTTP/1.0\r\nHost: localhost\r\nContent-Length: 7\r\n\r\n"
        +                )
        +                response = client.recv(1024)
        +                if disconnect:
        +                    assert response == b""
        +                else:
        +                    assert response.startswith(b"HTTP/1.0 413")
        +        finally:
        +            server.shutdown()
        +            thread.join()
        +
        +
         @pytest.mark.parametrize("db_name", ["a" * 64, "invalid..database"])
         def test_connect_rejects_invalid_cloud_dns_hostname(db_name):
             with pytest.raises(ValueError, match="DNS labels must contain 1 to 63 bytes"):
        @@ -75,9 +187,9 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name):
         
         
         @contextlib.contextmanager
        -def mock_lancedb_connection(handler, **client_config):
        +def mock_lancedb_connection(handler, *, buffer_body=True, **client_config):
             with http.server.ThreadingHTTPServer(
        -        ("127.0.0.1", 0), make_mock_http_handler(handler)
        +        ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body)
             ) as server:
                 port = server.server_address[1]
                 handle = start_server_thread(server)
        @@ -103,9 +215,9 @@ def mock_lancedb_connection(handler, **client_config):
         
         
         @contextlib.asynccontextmanager
        -async def mock_lancedb_connection_async(handler, **client_config):
        +async def mock_lancedb_connection_async(handler, *, buffer_body=True, **client_config):
             with http.server.HTTPServer(
        -        ("127.0.0.1", 0), make_mock_http_handler(handler)
        +        ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body)
             ) as server:
                 port = server.server_address[1]
                 handle = start_server_thread(server)
        @@ -130,6 +242,234 @@ async def mock_lancedb_connection_async(handler, **client_config):
                     handle.join()
         
         
        +@pytest.mark.parametrize("sync_api", [False, True])
        +@pytest.mark.parametrize("retries", [None, 0])
        +@pytest.mark.parametrize("status", [429, 504])
        +@pytest.mark.asyncio
        +async def test_add_retry_override(sync_api, retries, status):
        +    attempts = 0
        +
        +    def handler(request):
        +        nonlocal attempts
        +        if request.path.endswith("/describe/"):
        +            payload = {
        +                "version": 1,
        +                "schema": {
        +                    "fields": [
        +                        {"name": "id", "type": {"type": "int64"}, "nullable": True}
        +                    ]
        +                },
        +            }
        +            request.send_response(200)
        +            request.end_headers()
        +            request.wfile.write(json.dumps(payload).encode())
        +            return
        +        assert request.path.endswith("/insert/")
        +        body = bytearray()
        +        if request.headers.get("Transfer-Encoding") == "chunked":
        +            while True:
        +                size = int(request.rfile.readline().strip(), 16)
        +                if size == 0:
        +                    request.rfile.readline()
        +                    break
        +                body.extend(request.rfile.read(size))
        +                request.rfile.read(2)
        +        else:
        +            body.extend(
        +                request.rfile.read(int(request.headers.get("Content-Length", 0)))
        +            )
        +        assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}]
        +        attempts += 1
        +        request.send_response(status if attempts == 1 else 200)
        +        request.end_headers()
        +        request.wfile.write(b'{"version": 2}')
        +
        +    config = {
        +        "retry_config": {
        +            "retries": 3,
        +            "statuses": [429, 504],
        +            "backoff_factor": 0,
        +            "backoff_jitter": 0,
        +        }
        +    }
        +    expected_success = status == 429 and retries is None
        +    if sync_api:
        +        with mock_lancedb_connection(handler, **config) as db:
        +            table = db.open_table("test")
        +            if expected_success:
        +                assert table.add([{"id": 1}], retries=retries).version == 2
        +            else:
        +                with pytest.raises((HttpError, RetryError)):
        +                    table.add([{"id": 1}], retries=retries)
        +    else:
        +        async with mock_lancedb_connection_async(handler, **config) as db:
        +            table = await db.open_table("test")
        +            if expected_success:
        +                assert (await table.add([{"id": 1}], retries=retries)).version == 2
        +            else:
        +                with pytest.raises((HttpError, RetryError)):
        +                    await table.add([{"id": 1}], retries=retries)
        +    assert attempts == (2 if expected_success else 1)
        +
        +
        +@pytest.mark.parametrize("sync_api", [False, True])
        +@pytest.mark.parametrize("namespace_path", [[], ["analytics", "features"]])
        +@pytest.mark.parametrize("retries", [None, 0, 2])
        +@pytest.mark.parametrize("status", [409, 429, 502, 503, 504])
        +@pytest.mark.asyncio
        +async def test_merge_retry_override(sync_api, namespace_path, retries, status, capfd):
        +    attempts = 0
        +    identifier = "$".join(namespace_path + ["test"])
        +
        +    def handler(request):
        +        nonlocal attempts
        +        if request.path == f"/v1/table/{identifier}/describe/":
        +            send_json(
        +                request,
        +                {
        +                    "version": 1,
        +                    "schema": {
        +                        "fields": [
        +                            {"name": "id", "type": {"type": "int64"}, "nullable": True}
        +                        ]
        +                    },
        +                },
        +            )
        +            return
        +        assert urlparse(request.path).path == f"/v1/table/{identifier}/merge_insert/"
        +        query = parse_qs(urlparse(request.path).query)
        +        assert query["use_index"] == ["false"]
        +        assert request.headers["x-request-timeout-ms"] == "10000"
        +        body = bytearray()
        +        if request.headers.get("Transfer-Encoding") == "chunked":
        +            while True:
        +                size = int(request.rfile.readline().strip(), 16)
        +                if size == 0:
        +                    request.rfile.readline()
        +                    break
        +                body.extend(request.rfile.read(size))
        +                request.rfile.read(2)
        +        else:
        +            body.extend(
        +                request.rfile.read(int(request.headers.get("Content-Length", 0)))
        +            )
        +        assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}]
        +        attempts += 1
        +        send_json(request, {"version": 2}, status if attempts == 1 else 200)
        +
        +    config = {
        +        "retry_config": {
        +            "retries": 3,
        +            "statuses": [409, 429, 502, 503, 504],
        +            "backoff_factor": 0,
        +            "backoff_jitter": 0,
        +        }
        +    }
        +    expected_success = status in (409, 429) and retries != 0
        +
        +    async def check(table):
        +        merge = table.merge_insert("id").when_not_matched_insert_all().use_index(False)
        +        options = {"timeout": timedelta(seconds=10)}
        +        if retries is not None:
        +            options["retries"] = retries
        +        if expected_success:
        +            result = merge.execute([{"id": 1}], **options)
        +            if not sync_api:
        +                result = await result
        +            assert result.version == 2
        +        else:
        +            with pytest.raises((HttpError, RetryError)):
        +                result = merge.execute([{"id": 1}], **options)
        +                if not sync_api:
        +                    await result
        +
        +    if sync_api:
        +        with mock_lancedb_connection(handler, **config) as db:
        +            await check(db.open_table("test", namespace_path=namespace_path))
        +    else:
        +        async with mock_lancedb_connection_async(handler, **config) as db:
        +            await check(await db.open_table("test", namespace_path=namespace_path))
        +    assert attempts == (2 if expected_success else 1)
        +    warnings = [
        +        line
        +        for line in capfd.readouterr().err.splitlines()
        +        if "Retrying merge insert" in line
        +    ]
        +    assert len(warnings) == (1 if expected_success else 0)
        +    if expected_success:
        +        assert "WARN" in warnings[0]
        +        assert f"status Some({status}); attempt 2" in warnings[0]
        +
        +
        +@pytest.mark.parametrize("sync_api", [False, True])
        +@pytest.mark.asyncio
        +async def test_merge_retry_override_isolation(sync_api):
        +    attempts = 0
        +    read_attempts = 0
        +
        +    def handler(request):
        +        nonlocal attempts, read_attempts
        +        if request.path.endswith("/describe/"):
        +            send_json(
        +                request,
        +                {
        +                    "version": 1,
        +                    "schema": {
        +                        "fields": [
        +                            {"name": "id", "type": {"type": "int64"}, "nullable": True}
        +                        ]
        +                    },
        +                },
        +            )
        +        elif request.path.endswith("/count_rows/"):
        +            read_attempts += 1
        +            send_json(request, 1, 429 if read_attempts % 2 else 200)
        +        else:
        +            assert urlparse(request.path).path.endswith("/merge_insert/")
        +            attempts += 1
        +            send_json(request, {"version": 2}, 429 if attempts in (1, 2, 4, 6) else 200)
        +
        +    async def check(table):
        +        merge = table.merge_insert("id").when_not_matched_insert_all()
        +        for retries in [-1, 256, 1.5, "1"]:
        +            with pytest.raises((OverflowError, TypeError, ValueError)):
        +                result = merge.execute([{"id": 1}], retries=retries)
        +                if not sync_api:
        +                    await result
        +        assert attempts == 0
        +        with pytest.raises((HttpError, RetryError)):
        +            result = merge.execute([{"id": 1}], retries=0)
        +            if not sync_api:
        +                await result
        +        assert attempts == 1
        +        for options in ({}, {"retries": 255}):
        +            result = merge.execute([{"id": 1}], **options)
        +            if not sync_api:
        +                result = await result
        +            assert result.version == 2
        +        assert attempts == 5
        +        result = table.count_rows()
        +        if not sync_api:
        +            result = await result
        +        assert result == 1
        +        assert read_attempts == 2
        +        result = (
        +            table.merge_insert("id").when_not_matched_insert_all().execute([{"id": 1}])
        +        )
        +        if not sync_api:
        +            result = await result
        +        assert result.version == 2
        +        assert attempts == 7
        +
        +    config = {"retry_config": {"retries": 3, "backoff_factor": 0, "backoff_jitter": 0}}
        +    if sync_api:
        +        with mock_lancedb_connection(handler, **config) as db:
        +            await check(db.open_table("test"))
        +    else:
        +        async with mock_lancedb_connection_async(handler, **config) as db:
        +            await check(await db.open_table("test"))
        +
        +
         @pytest.fixture
         def missing_table_handler(cached, namespace_path):
             request_ids = []
        @@ -457,6 +797,31 @@ def test_remote_table_exists_rechecks_cached_table():
             assert requests == ["/v1/table/ns$table/describe/"] * 2
         
         
        +@pytest.mark.parametrize("status", [200, 404, 403])
        +def test_remote_membership_uses_direct_lookup(status):
        +    requests = []
        +
        +    def handler(request):
        +        requests.append(request.path)
        +        assert request.command == "POST"
        +        assert request.path == "/v1/table/t129/describe/"
        +        request.send_response(status)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(b"{}" if status == 200 else b"lookup failed")
        +
        +    with mock_lancedb_connection(handler) as db:
        +        with warnings.catch_warnings():
        +            warnings.simplefilter("error", DeprecationWarning)
        +            if status in (200, 404):
        +                assert ("t129" in db) is (status == 200)
        +            else:
        +                with pytest.raises(HttpError) as exc_info:
        +                    "t129" in db
        +                assert exc_info.value.status_code == status
        +    assert requests == ["/v1/table/t129/describe/"]
        +
        +
         def paginated_table_listing_handler(request):
             url = urlparse(request.path)
             assert url.path in {
        @@ -733,6 +1098,43 @@ def test_remote_table_branches_sync():
                 table.branches.delete("exp")
         
         
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("json_response", [False, True])
        +async def test_remote_branch_delete_conflict_is_not_retried(use_async, json_response):
        +    request_ids = []
        +    reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files"
        +
        +    def handler(request):
        +        if request.path == "/v1/table/test/describe/":
        +            _branch_open_handler(request)
        +            return
        +
        +        assert request.path == "/v1/table/test/branches/delete/"
        +        content_len = int(request.headers["Content-Length"])
        +        assert json.loads(request.rfile.read(content_len)) == {"name": "exp"}
        +        request_ids.append(request.headers["x-request-id"])
        +        request.send_response(409)
        +        request.end_headers()
        +        body = json.dumps({"code": 14, "error": reason}) if json_response else reason
        +        request.wfile.write(body.encode())
        +
        +    if use_async:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            table = await db.open_table("test")
        +            with pytest.raises(ConflictError, match=re.escape(reason)) as exc_info:
        +                await table.branches.delete("exp")
        +    else:
        +        with mock_lancedb_connection(handler) as db:
        +            table = db.open_table("test")
        +            with pytest.raises(ConflictError, match=re.escape(reason)) as exc_info:
        +                table.branches.delete("exp")
        +
        +    assert request_ids == [exc_info.value.request_id]
        +    assert exc_info.value.status_code == 409
        +    assert isinstance(exc_info.value, HttpError)
        +
        +
         def test_remote_table_cherry_pick_defaults_to_execute():
             cherry_pick_bodies = []
             diff = {
        @@ -1003,6 +1405,12 @@ def test_remote_permutation_is_picklable():
                     {"a": 2},
                     {"a": 4},
                 ]
        +        assert table.take_offsets([0, 2, 0, 4], preserve_order=True).to_list() == [
        +            {"a": 0},
        +            {"a": 2},
        +            {"a": 0},
        +            {"a": 4},
        +        ]
         
                 permutation = Permutation.identity(table)
                 restored = pickle.loads(pickle.dumps(permutation))
        @@ -1129,6 +1537,126 @@ def test_create_table_positional_parameters_match_base_contract():
             assert actual == expected
         
         
        +def _unconsumed_create_input():
        +    raise AssertionError("create_table consumed input before rejecting the option")
        +    yield  # pragma: no cover
        +
        +
        +def _assert_enterprise_rejection(error):
        +    message = str(error)
        +    assert "not supported for table creation in LanceDB Enterprise" in message
        +    assert "Embedded" not in message
        +    assert "add(" not in message
        +
        +
        +def test_create_table_rejects_blob_base_options_before_request():
        +    def handler(request):
        +        raise AssertionError(f"unexpected request: {request.path}")
        +
        +    schema = pa.schema([pa.field("id", pa.int64())])
        +    with mock_lancedb_connection(handler) as db:
        +        with pytest.raises(NotImplementedError, match="initial_bases") as error:
        +            db.create_table(
        +                "test",
        +                data=_unconsumed_create_input(),
        +                initial_bases=[{"path": "s3://bucket/prefix"}],
        +            )
        +        _assert_enterprise_rejection(error.value)
        +        with pytest.raises(
        +            NotImplementedError, match="allow_external_blob_outside_bases"
        +        ) as error:
        +            db.create_table(
        +                "test",
        +                data=_unconsumed_create_input(),
        +                allow_external_blob_outside_bases=True,
        +            )
        +        _assert_enterprise_rejection(error.value)
        +        with pytest.raises(
        +            NotImplementedError, match="allow_external_blob_outside_bases"
        +        ) as error:
        +            db.create_table(
        +                "test",
        +                schema=schema,
        +                allow_external_blob_outside_bases=True,
        +            )
        +        _assert_enterprise_rejection(error.value)
        +
        +
        +def test_create_table_accepts_empty_blob_base_options():
        +    def handler(request):
        +        assert request.path == "/v1/table/test/create/?mode=create"
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(b"{}")
        +
        +    schema = pa.schema([pa.field("id", pa.int64())])
        +    with mock_lancedb_connection(handler) as db:
        +        table = db.create_table(
        +            "test",
        +            schema=schema,
        +            initial_bases=[],
        +            allow_external_blob_outside_bases=False,
        +        )
        +        assert table is not None
        +
        +
        +@pytest.mark.asyncio
        +async def test_create_table_rejects_blob_base_options_before_request_async():
        +    def handler(request):
        +        raise AssertionError(f"unexpected request: {request.path}")
        +
        +    def reader():
        +        schema = pa.schema([pa.field("id", pa.int64())])
        +        return pa.RecordBatchReader.from_batches(schema, [])
        +
        +    schema = pa.schema([pa.field("id", pa.int64())])
        +    async with mock_lancedb_connection_async(handler) as db:
        +        with pytest.raises(NotImplementedError, match="initial_bases") as error:
        +            await db.create_table(
        +                "test",
        +                data=_unconsumed_create_input(),
        +                initial_bases=[{"path": "s3://bucket/prefix"}],
        +            )
        +        _assert_enterprise_rejection(error.value)
        +        with pytest.raises(
        +            NotImplementedError, match="allow_external_blob_outside_bases"
        +        ) as error:
        +            await db.create_table(
        +                "test",
        +                data=_unconsumed_create_input(),
        +                allow_external_blob_outside_bases=True,
        +            )
        +        _assert_enterprise_rejection(error.value)
        +        with pytest.raises(
        +            NotImplementedError, match="allow_external_blob_outside_bases"
        +        ) as error:
        +            await db.create_table(
        +                "test",
        +                schema=schema,
        +                allow_external_blob_outside_bases=True,
        +            )
        +        _assert_enterprise_rejection(error.value)
        +        # The lower-layer guard still maps Error::NotSupported for direct native
        +        # calls that bypass the Python entrypoint.
        +        with pytest.raises(NotImplementedError, match="initial_bases"):
        +            await db._inner.create_table(
        +                "test",
        +                "create",
        +                reader(),
        +                initial_bases=[{"path": "s3://bucket/prefix"}],
        +            )
        +        with pytest.raises(
        +            NotImplementedError, match="allow_external_blob_outside_bases"
        +        ):
        +            await db._inner.create_table(
        +                "test",
        +                "create",
        +                reader(),
        +                allow_external_blob_outside_bases=True,
        +            )
        +
        +
         def test_create_table_exist_ok():
             def handler(request):
                 if request.path == "/v1/table/test/create/?mode=exist_ok":
        @@ -1181,7 +1709,7 @@ async def test_create_table_timeout_is_actionable(timeout_config):
                 request.close_connection = True
         
             async with mock_lancedb_connection_async(
        -        handler, timeout_config=timeout_config
        +        handler, buffer_body=False, timeout_config=timeout_config
             ) as db:
                 batch = pa.record_batch({"id": [1, 2]})
                 reader = pa.RecordBatchReader.from_batches(batch.schema, [batch])
        @@ -1422,7 +1950,26 @@ def test_table_to_pandas_not_supported():
         
         
         def test_table_add_in_threadpool():
        +    received = []
        +
             def handler(request):
        +        # Consume uploads before responding: closing with unread bytes can reset
        +        # the connection while the client is still reading the response.
        +        if request.headers.get("Transfer-Encoding") == "chunked":
        +            body = bytearray()
        +            while size := int(request.rfile.readline().split(b";")[0], 16):
        +                body.extend(request.rfile.read(size))
        +                assert request.rfile.read(2) == b"\r\n"
        +            assert request.rfile.read(2) == b"\r\n"
        +        else:
        +            body = request.rfile.read(int(request.headers.get("Content-Length", 0)))
        +        if request.path in (
        +            "/v1/table/test/create/?mode=create",
        +            "/v1/table/test/insert/",
        +        ):
        +            received.append(
        +                (request.path, pa.ipc.open_stream(body).read_all().to_pylist())
        +            )
                 if request.path == "/v1/table/test/insert/":
                     request.send_response(200)
                     request.end_headers()
        @@ -1461,6 +2008,9 @@ def test_table_add_in_threadpool():
                     for future in futures:
                         future.result()
         
        +    assert [rows for path, rows in received if "/create/" in path] == [[{"id": 1}]]
        +    assert [rows for path, rows in received if "/insert/" in path] == [[{"id": 1}]] * 10
        +
         
         def test_table_create_indices():
             # Track received index creation requests to validate name parameter
        @@ -1782,7 +2332,7 @@ def test_remote_create_index_async_returns_job():
             with mock_lancedb_connection(handler) as db:
                 table = db.create_table("test", [{"id": 1}])
                 job = table.create_index_async("id", config=BTree())
        -        assert job.id == "job-1"
        +        assert job.id() == "job-1"
                 observed = []
                 assert job.wait(timeout=timedelta(seconds=30), progress=observed.append) is None
                 assert len(describe_calls) == 2
        @@ -1802,7 +2352,48 @@ def test_remote_create_index_async_returns_job():
                 {"batch_size": None},
                 {"batch_size": 1},
                 {"batch_size": 8},
        -        {"gpu_class": "a10g", "gpu_count": 2},
        +        {"max_concurrency": 3},
        +        {"publication_interval_rows": 60},
        +        {"total_cpu_millis": 2000, "total_memory_bytes": 4 * 1024**3},
        +        {
        +            "total_cpu_millis": 8000,
        +            "total_memory_bytes": 16 * 1024**3,
        +            "total_gpu_count": 2,
        +        },
        +        {
        +            "supervisor_resources": {
        +                "cpu_millis": 2000,
        +                "memory_bytes": 4 * 1024**3,
        +                "ephemeral_storage_bytes": 10 * 1024**3,
        +            },
        +            "planning_workers": {
        +                "resources": {
        +                    "cpu_millis": 1000,
        +                    "memory_bytes": 2 * 1024**3,
        +                    "ephemeral_storage_bytes": 5 * 1024**3,
        +                },
        +                "max_workers": 4,
        +                "rows_per_worker": 100_000,
        +                "fragments_per_worker": 8,
        +            },
        +        },
        +        {"gpu_class": "a10g", "total_gpu_count": 2},
        +        {
        +            "retry_policy": {"transient": True, "max_attempts": 3},
        +            "error_policy": "skip",
        +        },
        +        {"retry_policy": {"max_attempts": 1}, "error_policy": "fail"},
        +        {
        +            "where": "id % 2 = 0",
        +            "error_policy": "skip",
        +            "max_failed_fraction": 0.01,
        +            "max_failed_rows": 50,
        +            "row_timeout_seconds": 30,
        +            "init_timeout_seconds": 120,
        +            "num_workers": 4,
        +            "max_job_attempts": 4,
        +            "max_executor_processes_per_worker": 2,
        +        },
             ],
         )
         async def test_remote_refresh_async_returns_typed_terminal_result(
        @@ -1825,8 +2416,34 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
                         expected["batch_size"] = refresh_kwargs["batch_size"]
                     if refresh_kwargs.get("gpu_class") is not None:
                         expected["gpu_class"] = refresh_kwargs["gpu_class"]
        -            if refresh_kwargs.get("gpu_count") is not None:
        -                expected["gpu_count"] = refresh_kwargs["gpu_count"]
        +            if refresh_kwargs.get("total_gpu_count") is not None:
        +                expected["total_gpu_count"] = refresh_kwargs["total_gpu_count"]
        +            for key in ("total_cpu_millis", "total_memory_bytes"):
        +                if refresh_kwargs.get(key) is not None:
        +                    expected[key] = refresh_kwargs[key]
        +            for key in ("supervisor_resources", "planning_workers"):
        +                if refresh_kwargs.get(key) is not None:
        +                    expected[key] = refresh_kwargs[key]
        +            if refresh_kwargs.get("retry_policy") is not None:
        +                expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate(
        +                    refresh_kwargs["retry_policy"]
        +                ).model_dump(mode="json")
        +            if refresh_kwargs.get("error_policy") is not None:
        +                expected["error_policy"] = refresh_kwargs["error_policy"]
        +            for key in (
        +                "where",
        +                "max_concurrency",
        +                "publication_interval_rows",
        +                "max_failed_fraction",
        +                "max_failed_rows",
        +                "row_timeout_seconds",
        +                "init_timeout_seconds",
        +                "num_workers",
        +                "max_job_attempts",
        +                "max_executor_processes_per_worker",
        +            ):
        +                if refresh_kwargs.get(key) is not None:
        +                    expected[key] = refresh_kwargs[key]
                     assert json.loads(body) == expected
                     request.send_response(202)
                     request.send_header("Content-Type", "application/json")
        @@ -1880,21 +2497,71 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
                 async with mock_lancedb_connection_async(handler) as db:
                     table = await db.create_table("test", [{"id": 1}])
                     job = await table.refresh_column_async("derived", **refresh_kwargs)
        -            assert job.id == "refresh-1"
        +            assert job.id() == "refresh-1"
                     result = await job.wait(timeout=timedelta(seconds=30))
             else:
                 with mock_lancedb_connection(handler) as db:
                     table = db.create_table("test", [{"id": 1}])
                     job = table.refresh_column_async("derived", **refresh_kwargs)
        -            assert job.id == "refresh-1"
        +            assert job.id() == "refresh-1"
                     result = job.wait(timeout=timedelta(seconds=30))
         
             assert isinstance(result, lancedb.RefreshColumnResult)
        -    assert result.model_dump() == terminal_result
        +    assert result.model_dump(exclude_defaults=True) == terminal_result
             assert result.rows_filled == 12
             assert result.version == 8
         
         
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("async_table", [True, False])
        +async def test_resume_refresh_returns_typed_successor(async_table):
        +    terminal = {
        +        "rows_assigned": 12,
        +        "rows_failed": 0,
        +        "rows_remaining": 0,
        +        "source_version": 7,
        +        "published_version": 8,
        +    }
        +
        +    def handler(request):
        +        length = int(request.headers.get("Content-Length", 0))
        +        body = json.loads(request.rfile.read(length)) if length else {}
        +        if request.path == "/v1/table/test/describe/":
        +            response = {"version": 1, "schema": {"fields": []}}
        +        elif request.path == "/v1/table/test/resume_refresh":
        +            assert body == {"job_id": "failed"}
        +            response = {"job_id": "successor"}
        +        elif request.path == "/v1/jobs/describe":
        +            assert body["job_id"] == "successor"
        +            response = {
        +                "job_id": "successor",
        +                "job_type": "function_refresh",
        +                "job_state": "DONE",
        +                "result": terminal,
        +            }
        +        else:
        +            raise AssertionError(f"Unexpected request: {request.path}")
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(response).encode())
        +
        +    if async_table:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            table = await db.open_table("test")
        +            job = await table.resume_refresh("failed")
        +            result = await job.wait(timeout=timedelta(seconds=30))
        +    else:
        +        with mock_lancedb_connection(handler) as db:
        +            table = db.open_table("test")
        +            job = table.resume_refresh("failed")
        +            result = job.wait(timeout=timedelta(seconds=30))
        +
        +    assert job.id() == "successor"
        +    assert isinstance(result, lancedb.RefreshColumnResult)
        +    assert result.model_dump(exclude_defaults=True) == terminal
        +
        +
         def test_remote_refresh_async_forwards_progress_from_submitted_handle():
             terminal_result = {
                 "rows_assigned": 12,
        @@ -1986,12 +2653,68 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle():
                 ({"gpu_class": "H100"}, "gpu_class"),
                 ({"gpu_class": "-a10g"}, "gpu_class"),
                 ({"gpu_class": "a_b"}, "gpu_class"),
        -        ({"gpu_count": 0}, "gpu_count"),
        -        ({"gpu_count": -1}, "gpu_count"),
        +        ({"total_gpu_count": -1}, "total_gpu_count"),
        +        ({"retry_policy": {"transient": True, "max_attempts": 0}}, "retry_policy"),
        +        ({"error_policy": "retry"}, "error_policy"),
        +        ({"where": "  "}, "where"),
        +        ({"max_failed_fraction": 1.5}, "max_failed_fraction"),
        +        ({"max_failed_rows": -1}, "max_failed_rows"),
        +        ({"row_timeout_seconds": 0}, "row_timeout_seconds"),
        +        ({"init_timeout_seconds": -5}, "init_timeout_seconds"),
        +        ({"publication_interval_rows": 0}, "publication_interval_rows"),
        +        ({"publication_interval_rows": -1}, "publication_interval_rows"),
        +        ({"max_concurrency": True}, "max_concurrency"),
        +        ({"max_concurrency": 1.5}, "max_concurrency"),
        +        ({"max_concurrency": 0}, "max_concurrency"),
        +        ({"max_concurrency": -1}, "max_concurrency"),
        +        ({"max_concurrency": 2**32}, "max_concurrency"),
        +        ({"num_workers": 0}, "num_workers"),
        +        (
        +            {"total_cpu_millis": 0, "total_memory_bytes": 1},
        +            "total_cpu_millis",
        +        ),
        +        (
        +            {
        +                "supervisor_resources": {
        +                    "cpu_millis": 0,
        +                    "memory_bytes": 1,
        +                    "ephemeral_storage_bytes": 1,
        +                }
        +            },
        +            "supervisor_resources.cpu_millis",
        +        ),
        +        (
        +            {
        +                "supervisor_resources": {
        +                    "cpu_millis": 1,
        +                    "memory_bytes": 1,
        +                }
        +            },
        +            "supervisor_resources.ephemeral_storage_bytes",
        +        ),
        +        (
        +            {
        +                "planning_workers": {
        +                    "resources": {
        +                        "cpu_millis": 1,
        +                        "memory_bytes": 1,
        +                        "ephemeral_storage_bytes": 1,
        +                    },
        +                    "max_workers": 0,
        +                    "rows_per_worker": 1,
        +                    "fragments_per_worker": 1,
        +                }
        +            },
        +            "planning_workers.max_workers",
        +        ),
        +        (
        +            {"max_executor_processes_per_worker": -2},
        +            "max_executor_processes_per_worker",
        +        ),
             ],
         )
         @pytest.mark.asyncio
        -async def test_remote_refresh_rejects_invalid_gpu_options_before_request(
        +async def test_remote_refresh_rejects_invalid_options_before_request(
             refresh_kwargs, message
         ):
             backfill_requests = []
        @@ -2040,13 +2763,15 @@ async def test_remote_refresh_rejects_invalid_gpu_options_before_request(
             assert backfill_requests == []
         
         
        -def test_remote_function_errors_lists_the_rows_a_refresh_skipped():
        +@pytest.mark.parametrize("attempts", [None, 3])
        +def test_remote_function_errors_lists_the_rows_a_refresh_skipped(attempts):
             listing = {
                 "records": [
                     {
                         "job_id": "j-7",
                         "fragment_id": 3,
                         "row_offset": 9,
        +                "row_id": 42,
                         "row_address": 12884901897,
                         "column": "embedding",
                         "function": "embed",
        @@ -2054,6 +2779,10 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped():
                         "table_version": 11,
                         "error_type": "ValueError",
                         "error_message": "bad input 'x'",
        +                "attempts": attempts,
        +                "traceback": (
        +                    "Traceback (most recent call last):\nValueError: bad input 'x'"
        +                ),
                         "created_at_millis": 1700000000000,
                     }
                 ],
        @@ -2098,8 +2827,13 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped():
             assert errors.truncated is True
             assert [r.error_message for r in errors.records] == ["bad input 'x'"]
             assert errors.records[0].row_offset == 9
        +    assert errors.records[0].row_id == 42
             assert errors.records[0].row_address == 12884901897
             assert errors.records[0].function_version == "2"
        +    assert errors.records[0].attempts == attempts
        +    assert errors.records[0].traceback == (
        +        "Traceback (most recent call last):\nValueError: bad input 'x'"
        +    )
             assert repr(errors.records[0]) == (
                 'FunctionErrorRecord(job_id="j-7", fragment_id=3, row_offset=9, '
                 'row_address=12884901897, column="embedding", '
        @@ -2112,6 +2846,164 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped():
             assert everything.truncated is True
         
         
        +def test_remote_function_column_status_passes_pinned_version():
        +    queries = []
        +    status = {
        +        "column": "embedding",
        +        "binding_id": "fb_01",
        +        "function": {
        +            "name": "embed",
        +            "object_id": "embed",
        +            "location": "objects/embed",
        +            "version": "7",
        +            "manifest_digest": "sha256:abc",
        +        },
        +        "table_version": 42,
        +        "rows": 4,
        +        "fresh": 2,
        +        "stale": 2,
        +        "never_computed": 0,
        +        "failed": 0,
        +        "last_refresh_job": {
        +            "job_id": "job-cancelled",
        +            "state": "cancelled",
        +            "automatic": True,
        +            "completed_at_millis": 1790000002000,
        +        },
        +        "last_failure_job": {
        +            "job_id": "job-failed",
        +            "state": "failed",
        +            "automatic": True,
        +            "completed_at_millis": 1790000001000,
        +            "failure": {
        +                "phase": "finalize",
        +                "message": "worker timed out",
        +                "traceback": "Traceback: timeout",
        +                "retryable": True,
        +                "sql_job_id": "sql-job-7",
        +            },
        +        },
        +        "auto_refresh": {
        +            "enabled": True,
        +            "interval_seconds": 60,
        +            "active_job_id": "job-queued",
        +            "state": "queued",
        +            "failure_streak": 1,
        +            "next_run_at_millis": None,
        +            "next_run_at_reason": "job_queued_not_started",
        +        },
        +    }
        +
        +    def handler(request):
        +        parsed = urlparse(request.path)
        +        if parsed.path == "/v1/table/test/describe/":
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.end_headers()
        +            request.wfile.write(
        +                json.dumps({"version": 42, "schema": {"fields": []}}).encode()
        +            )
        +        elif parsed.path == "/v1/table/test/function_columns/status":
        +            queries.append(parse_qs(parsed.query))
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.end_headers()
        +            request.wfile.write(json.dumps([status]).encode())
        +        else:
        +            request.send_response(404)
        +            request.end_headers()
        +
        +    with mock_lancedb_connection(handler) as db:
        +        table = db.open_table("test")
        +        table.checkout(42)
        +        result = table.column_status("embedding")
        +
        +    assert queries == [{"column": ["embedding"], "version": ["42"]}]
        +    assert result.table_version == 42
        +    assert (result.fresh, result.stale, result.never_computed, result.failed) == (
        +        2,
        +        2,
        +        0,
        +        0,
        +    )
        +    assert result.auto_refresh.state == "queued"
        +    assert result.auto_refresh.active_job_id == "job-queued"
        +    assert result.auto_refresh.failure_streak == 1
        +    assert result.auto_refresh.next_run_at_reason == "job_queued_not_started"
        +    assert result.last_refresh_job.state == "cancelled"
        +    assert result.last_refresh_job.failure is None
        +    assert result.last_failure_job.job_id == "job-failed"
        +    failure = result.last_failure_job.failure
        +    assert failure.phase == "finalize"
        +    assert failure.message == "worker timed out"
        +    assert failure.traceback == "Traceback: timeout"
        +    assert failure.retryable is True
        +    assert failure.sql_job_id == "sql-job-7"
        +
        +
        +def test_remote_wait_fresh_retries_only_typed_finalization_pending():
        +    calls = 0
        +    status = {
        +        "column": "embedding",
        +        "binding_id": "fb_01",
        +        "function": {
        +            "name": "embed",
        +            "object_id": "embed",
        +            "location": "objects/embed",
        +            "version": "7",
        +            "manifest_digest": "sha256:abc",
        +        },
        +        "table_version": 42,
        +        "rows": 1,
        +        "fresh": 1,
        +        "stale": 0,
        +        "never_computed": 0,
        +        "failed": 0,
        +        "auto_refresh": {
        +            "enabled": False,
        +            "state": "disabled",
        +            "failure_streak": 0,
        +            "next_run_at_millis": None,
        +        },
        +    }
        +
        +    def handler(request):
        +        nonlocal calls
        +        parsed = urlparse(request.path)
        +        if parsed.path == "/v1/table/test/describe/":
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.end_headers()
        +            request.wfile.write(
        +                json.dumps({"version": 42, "schema": {"fields": []}}).encode()
        +            )
        +        elif parsed.path == "/v1/table/test/function_columns/status":
        +            calls += 1
        +            if calls == 1:
        +                request.send_response(503)
        +                request.send_header(
        +                    "x-lancedb-error-code",
        +                    "function_column_status_finalization_pending",
        +                )
        +                request.end_headers()
        +                request.wfile.write(b"finalization pending")
        +            else:
        +                request.send_response(200)
        +                request.send_header("Content-Type", "application/json")
        +                request.end_headers()
        +                request.wfile.write(json.dumps([status]).encode())
        +        else:
        +            request.send_response(404)
        +            request.end_headers()
        +
        +    with mock_lancedb_connection(handler) as db:
        +        table = db.open_table("test")
        +        result = table.wait_fresh("embedding", timeout=timedelta(seconds=2))
        +
        +    assert calls == 2
        +    assert result.fresh == result.rows == 1
        +
        +
         @pytest.mark.asyncio
         @pytest.mark.parametrize("sync", [False, True])
         @pytest.mark.parametrize("failure", ["send", "read"])
        @@ -2147,12 +3039,12 @@ async def test_remote_job_wait_recovers_from_disconnection(sync, failure):
                 with mock_lancedb_connection(handler, **config) as db:
                     job = db.open_job("job-1")
                     assert job.wait(timeout=timedelta(seconds=5)) is None
        -            assert job.state == "finished"
        +            assert job.state() == "finished"
             else:
                 async with mock_lancedb_connection_async(handler, **config) as db:
                     job = await db.open_job("job-1")
                     assert await job.wait(timeout=timedelta(seconds=5)) is None
        -            assert job.state == "finished"
        +            assert job.state() == "finished"
             assert polls == 5
         
         
        @@ -2197,6 +3089,188 @@ async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync):
             assert exc.value.__cause__.is_transport_error is True
         
         
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_remote_job_stats_returns_native_optional_report(sync):
        +    report = "Function job: finished\nWorker utilization: unavailable\n"
        +    paths = []
        +
        +    def handler(request):
        +        payload = json.loads(request.rfile.read(int(request.headers["Content-Length"])))
        +        assert payload == {"job_id": "refresh-1"}
        +        paths.append(request.path)
        +        if request.path == "/v1/jobs/describe":
        +            response = {
        +                "job_id": "refresh-1",
        +                "job_type": "function_refresh",
        +                "job_state": "IN_PROGRESS",
        +                "creation_ms": 1000,
        +            }
        +        elif request.path == "/v1/jobs/stats":
        +            available = paths.count("/v1/jobs/stats") > 1
        +            response = {
        +                "job_id": "refresh-1",
        +                "profile": {"future_field": True} if available else None,
        +                "report": report if available else None,
        +            }
        +        else:
        +            raise AssertionError(f"unexpected request: {request.path}")
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(response).encode())
        +
        +    if sync:
        +        with mock_lancedb_connection(handler) as db:
        +            job = db.open_job("refresh-1")
        +            assert job.stats() is None
        +            assert job.stats() == report
        +    else:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            job = await db.open_job("refresh-1")
        +            assert await job.stats() is None
        +            assert await job.stats() == report
        +    assert paths == ["/v1/jobs/describe", "/v1/jobs/stats", "/v1/jobs/stats"]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +@pytest.mark.parametrize(
        +    "job_type", ["function_refresh", "computed_refresh", "refresh_column"]
        +)
        +@pytest.mark.parametrize("running", [False, True])
        +@pytest.mark.parametrize("rows_failed", [0, 8])
        +async def test_reopened_refresh_job_wait_returns_typed_result(
        +    sync, job_type, running, rows_failed
        +):
        +    terminal_result = {
        +        "rows_assigned": 400 - rows_failed,
        +        "rows_failed": rows_failed,
        +        "rows_remaining": 0,
        +        "source_version": 7,
        +        "published_version": 8,
        +        "summary": {"future_field": True},
        +    }
        +    polls = 0
        +
        +    def handler(request):
        +        nonlocal polls
        +        assert request.path == "/v1/jobs/describe"
        +        payload = json.loads(request.rfile.read(int(request.headers["Content-Length"])))
        +        assert payload == {"job_id": "refresh-1"}
        +        polls += 1
        +        in_progress = running and polls <= 2
        +        response = {
        +            "job_id": "refresh-1",
        +            "job_type": job_type,
        +            "job_state": "IN_PROGRESS" if in_progress else "DONE",
        +            "creation_ms": 1000,
        +            "spec": {"column": "derived"},
        +        }
        +        if not in_progress:
        +            response["result"] = terminal_result
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(response).encode())
        +
        +    observed = []
        +    if sync:
        +        with mock_lancedb_connection(handler) as db:
        +            job = db.open_job("refresh-1")
        +            assert job.id() == "refresh-1"
        +            assert job.spec() == {"column": "derived"}
        +            result = job.wait(timeout=timedelta(seconds=5), progress=observed.append)
        +            assert job.wait() == result
        +            job.refresh()
        +            assert job.result() == terminal_result
        +    else:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            job = await db.open_job("refresh-1")
        +            assert job.id() == "refresh-1"
        +            assert job.spec() == {"column": "derived"}
        +            result = await job.wait(
        +                timeout=timedelta(seconds=5), progress=observed.append
        +            )
        +            assert await job.wait() == result
        +            await job.refresh()
        +            assert job.result() == terminal_result
        +
        +    assert isinstance(result, lancedb.RefreshColumnResult)
        +    assert result == lancedb.RefreshColumnResult.model_validate(terminal_result)
        +    assert result.rows_failed == rows_failed
        +    assert observed[-1]["state"] == "finished"
        +    if running:
        +        assert observed[0]["state"] == "running"
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +@pytest.mark.parametrize("terminal_result", [None, {}])
        +async def test_reopened_refresh_job_rejects_missing_or_invalid_result(
        +    sync, terminal_result
        +):
        +    def handler(request):
        +        assert request.path == "/v1/jobs/describe"
        +        request.rfile.read(int(request.headers["Content-Length"]))
        +        request.send_response(200)
        +        request.end_headers()
        +        request.wfile.write(
        +            json.dumps(
        +                {
        +                    "job_id": "refresh-1",
        +                    "job_type": "function_refresh",
        +                    "job_state": "DONE",
        +                    "result": terminal_result,
        +                }
        +            ).encode()
        +        )
        +
        +    if sync:
        +        with mock_lancedb_connection(handler) as db:
        +            job = db.open_job("refresh-1")
        +            with pytest.raises(HttpError, match="typed job"):
        +                job.wait()
        +    else:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            job = await db.open_job("refresh-1")
        +            with pytest.raises(HttpError, match="typed job"):
        +                await job.wait()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [False, True])
        +async def test_reopened_unit_job_ignores_additive_result_payload(sync):
        +    terminal_result = {"future_field": True}
        +
        +    def handler(request):
        +        assert request.path == "/v1/jobs/describe"
        +        request.rfile.read(int(request.headers["Content-Length"]))
        +        request.send_response(200)
        +        request.end_headers()
        +        request.wfile.write(
        +            json.dumps(
        +                {
        +                    "job_id": "index-1",
        +                    "job_type": "create_index",
        +                    "job_state": "DONE",
        +                    "result": terminal_result,
        +                }
        +            ).encode()
        +        )
        +
        +    if sync:
        +        with mock_lancedb_connection(handler) as db:
        +            job = db.open_job("index-1")
        +            assert job.wait() is None
        +            assert job.result() == terminal_result
        +    else:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            job = await db.open_job("index-1")
        +            assert await job.wait() is None
        +            assert job.result() == terminal_result
        +
        +
         @pytest.mark.parametrize("payload", [b"{", b"{}"])
         def test_remote_job_wait_does_not_retry_malformed_description(payload):
             polls = 0
        @@ -2274,6 +3348,69 @@ def test_remote_job_wait_raises_on_failure():
                 assert exc_info.value.sql_job_id is None
         
         
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync", [True, False])
        +@pytest.mark.parametrize("with_terminal_server", [True, False])
        +async def test_remote_job_wait_preserves_terminal_build(sync, with_terminal_server):
        +    from lancedb.exceptions import JobFailedError
        +
        +    message = "ValueError: corrupt frame at frame_index=207"
        +    server = {
        +        "release": "1.13.0-beta.0",
        +        "git_sha": "2a7874ecd589",
        +        "build_date": "2026-11-12T22:45:43Z",
        +    }
        +    result = {"terminal_server": server} if with_terminal_server else None
        +
        +    def handler(request):
        +        assert request.path == "/v1/jobs/describe"
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.send_header(
        +            "x-lancedb-server-build",
        +            json.dumps({"release": "2.0.0", "git_sha": "new-query-node"}),
        +        )
        +        request.end_headers()
        +        request.wfile.write(
        +            json.dumps(
        +                {
        +                    "job_id": "job-provenance",
        +                    "job_state": "FAILED",
        +                    "failure": {
        +                        "phase": "function_refresh_attempt_failed",
        +                        "message": message,
        +                        "traceback": "Traceback: original user code",
        +                        "retryable": False,
        +                    },
        +                    "result": result,
        +                }
        +            ).encode()
        +        )
        +
        +    if sync:
        +        with mock_lancedb_connection(handler) as db:
        +            job = db.open_job("job-provenance")
        +            with pytest.raises(JobFailedError) as caught:
        +                job.wait()
        +    else:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            job = await db.open_job("job-provenance")
        +            with pytest.raises(JobFailedError) as caught:
        +                await job.wait()
        +
        +    expected = f"Job job-provenance failed: {message}"
        +    if with_terminal_server:
        +        expected += (
        +            " [server: 1.13.0-beta.0 (git 2a7874ecd589, built 2026-11-12T22:45:43Z)]"
        +        )
        +    expected += " (in function_refresh_attempt_failed)"
        +    assert str(caught.value) == expected
        +    assert caught.value.job_id == "job-provenance"
        +    assert job.failure().message == message
        +    assert job.failure().traceback == "Traceback: original user code"
        +    assert job.result() == result
        +
        +
         @pytest.mark.parametrize("server_version", ["0.2.0", "0.6.0"])
         def test_remote_json_fts_config(server_version):
             from lancedb.index import FTS
        @@ -2340,6 +3477,123 @@ def test_remote_json_fts_config(server_version):
             assert request["block_size"] == 256
         
         
        +def test_remote_create_rtree_index():
        +    from lancedb.index import RTree
        +
        +    received_requests = []
        +
        +    def handler(request):
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        if request.path == "/v1/table/test/describe/":
        +            point = {
        +                "name": "geom",
        +                "type": {
        +                    "type": "struct",
        +                    "fields": [
        +                        {"name": "x", "type": {"type": "double"}, "nullable": False},
        +                        {"name": "y", "type": {"type": "double"}, "nullable": False},
        +                    ],
        +                },
        +                "nullable": True,
        +                "metadata": {"ARROW:extension:name": "geoarrow.point"},
        +            }
        +            request.wfile.write(
        +                json.dumps({"version": 1, "schema": {"fields": [point]}}).encode()
        +            )
        +        elif request.path == "/v1/table/test/create_index/":
        +            received_requests.append(read_json_body(request))
        +            request.wfile.write(b"{}")
        +        else:
        +            raise AssertionError(f"Unexpected request: {request.path}")
        +
        +    with mock_lancedb_connection(handler) as db:
        +        table = db.open_table("test")
        +        table.create_index("geom", config=RTree())
        +        table.create_index("geom", config=RTree(page_size=1024), name="geom_rtree")
        +        with pytest.raises(ValueError, match="page_size must be at least 2"):
        +            table.create_index("geom", config=RTree(page_size=1))
        +
        +    assert received_requests == [
        +        {"column": "geom", "index_type": "RTREE"},
        +        {
        +            "column": "geom",
        +            "index_type": "RTREE",
        +            "name": "geom_rtree",
        +            "page_size": 1024,
        +        },
        +    ]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_remote_scalar_plugin_nests_params(use_async):
        +    from lancedb.index import ScalarPlugin
        +
        +    received_requests = []
        +
        +    def handler(request):
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        if request.path == "/v1/table/test/describe/":
        +            fields = [{"name": "id", "type": {"type": "int32"}, "nullable": False}]
        +            request.wfile.write(
        +                json.dumps({"version": 1, "schema": {"fields": fields}}).encode()
        +            )
        +        elif request.path == "/v1/table/test/create_index/":
        +            received_requests.append(read_json_body(request))
        +            request.wfile.write(b"{}")
        +        else:
        +            raise AssertionError(f"Unexpected request: {request.path}")
        +
        +    cases = [
        +        (ScalarPlugin(" ZoneMap "), {}),
        +        (
        +            ScalarPlugin("bloomfilter", {"number_of_items": 4096, "column": "not_id"}),
        +            {"name": "id_bloom", "replace": False},
        +        ),
        +        (ScalarPlugin("bloomfilter", '{"probability": 0.01}'), {}),
        +        (ScalarPlugin("zonemap", {}), {}),
        +    ]
        +
        +    if use_async:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            table = await db.open_table("test")
        +            for config, options in cases:
        +                await table.create_index("id", config=config, **options)
        +    else:
        +        with mock_lancedb_connection(handler) as db:
        +            table = db.open_table("test")
        +            for config, options in cases:
        +                table.create_index("id", config=config, **options)
        +
        +    assert received_requests == [
        +        {"column": "id", "index_type": "PLUGIN", "plugin_type": "ZONEMAP"},
        +        {
        +            "column": "id",
        +            "index_type": "PLUGIN",
        +            "plugin_type": "BLOOMFILTER",
        +            "name": "id_bloom",
        +            "replace": False,
        +            "params": {"number_of_items": 4096, "column": "not_id"},
        +        },
        +        {
        +            "column": "id",
        +            "index_type": "PLUGIN",
        +            "plugin_type": "BLOOMFILTER",
        +            "params": {"probability": 0.01},
        +        },
        +        {
        +            "column": "id",
        +            "index_type": "PLUGIN",
        +            "plugin_type": "ZONEMAP",
        +            "params": {},
        +        },
        +    ]
        +
        +
         @pytest.mark.parametrize(
             "rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}]
         )
        @@ -2558,13 +3812,16 @@ def test_remote_python_only_messages():
                         f"{method}() is not supported in LanceDB Enterprise. "
                         f"Use table.search().{method}() instead."
                     )
        -        for method in ["compact_files", "cleanup_old_versions"]:
        +        for method, expected in {
        +            "compact_files": "compact_files() is a no-op in LanceDB Enterprise.",
        +            "cleanup_old_versions": (
        +                "cleanup_old_versions() is a no-op in LanceDB Enterprise. "
        +                "Use cleanup_async() to submit durable cleanup explicitly."
        +            ),
        +        }.items():
                     with pytest.warns(UserWarning) as warning:
        -                getattr(table, method)()
        -            assert (
        -                str(warning[0].message)
        -                == f"{method}() is a no-op in LanceDB Enterprise."
        -            )
        +                assert getattr(table, method)() is None
        +            assert str(warning[0].message) == expected
         
         
         def test_remote_embedding_config_does_not_warn_or_drop_metadata(caplog):
        @@ -3012,6 +4269,23 @@ def test_update_table_overrides_sync_remote_table_merges_existing_fields():
             assert calls == ["GET", "PUT"]
         
         
        +@pytest.mark.parametrize("current", [{}, {"custom": {"keep": True}}])
        +def test_empty_update_table_overrides_only_reads(current):
        +    calls = []
        +
        +    def overrides_handler(request, parsed):
        +        calls.append(request.command)
        +        assert request.command == "GET"
        +        assert parsed.path == "/admin/table/overrides"
        +        assert_table_overrides_query(parsed)
        +        send_json(request, current)
        +
        +    with table_overrides_test_table(overrides_handler) as table:
        +        assert table.update_table_overrides() == current
        +
        +    assert calls == ["GET"]
        +
        +
         def test_reset_table_overrides_sync_remote_table():
             def overrides_handler(request, parsed):
                 assert request.command == "POST"
        @@ -3093,6 +4367,36 @@ def query_test_table(
                 yield table
         
         
        +def test_remote_fragment_constraints_fail_before_query():
        +    query_calls = 0
        +
        +    def query_handler(body):
        +        nonlocal query_calls
        +        query_calls += 1
        +        return pa.table({"text": ["unexpected"]})
        +
        +    with query_test_table(query_handler) as table:
        +        with pytest.raises(NotImplementedError, match="fragment selection"):
        +            table.search().fragment_ids([0]).to_arrow()
        +
        +    assert query_calls == 0
        +
        +
        +def test_remote_fts_count_rows_rejects_fragment_constraints():
        +    query_calls = 0
        +
        +    def query_handler(body):
        +        nonlocal query_calls
        +        query_calls += 1
        +        return pa.table({"text": ["unexpected"]})
        +
        +    with query_test_table(query_handler) as table:
        +        with pytest.raises(NotImplementedError, match="fragment selection"):
        +            table.search("hello", query_type="fts").fragment_ids([0]).count_rows()
        +
        +    assert query_calls == 0
        +
        +
         @pytest.mark.parametrize(
             "query,search_kwargs,expected_column",
             [
        @@ -3224,8 +4528,41 @@ def test_remote_take_row_ids_with_row_id():
             assert bodies[-1]["with_row_id"] is True
         
             with query_test_table(handler) as table:
        -        table.take_row_ids([0, 1]).to_arrow()
        -    assert "with_row_id" not in bodies[-1]
        +        result = table.take_row_ids([0, 1]).to_arrow()
        +        assert result.column_names == ["id"]
        +    assert bodies[-1]["with_row_id"] is True
        +
        +
        +@pytest.mark.parametrize("with_row_id", [False, True])
        +@pytest.mark.parametrize("selection", [None, [], ["id"], ["_rowid", "id"]])
        +def test_remote_take_row_ids_order_and_roundtrip(with_row_id, selection):
        +    def handler(body):
        +        assert body["with_row_id"] is True
        +        assert "_rowid IN" in body["filter"]
        +        assert "take_row_ids" not in body
        +        assert "_rowid" not in body.get("columns", [])
        +        data = pa.table(
        +            {
        +                "id": pa.chunked_array([[1, 5], [17]]),
        +                "_rowid": pa.chunked_array([[1, 5], [17]], type=pa.uint64()),
        +            }
        +        )
        +        return data.select(body.get("columns", ["id"]) + ["_rowid"])
        +
        +    with query_test_table(handler) as table:
        +        take = table.take_row_ids([17, 5, 2**64 - 1, 17, 1], with_row_id=with_row_id)
        +        if selection is not None:
        +            take = take.select(selection)
        +        result = take.to_batches(max_batch_length=1).read_all()
        +        assert result.num_rows == 4
        +        expected_columns = ["id"] if selection is None else list(selection)
        +        if with_row_id:
        +            expected_columns = [name for name in expected_columns if name != "_rowid"]
        +            expected_columns.append("_rowid")
        +        assert result.column_names == expected_columns
        +        for column in expected_columns:
        +            assert result[column].to_pylist() == [17, 5, 17, 1]
        +        assert table._execute_query(take.to_query_object()).read_all() == result
         
         
         def test_query_sync_minimal():
        @@ -3250,6 +4587,100 @@ def test_query_sync_minimal():
                 assert data == expected
         
         
        +def _arrow_stream(batches):
        +    sink = pa.BufferOutputStream()
        +    with pa.ipc.new_stream(sink, batches[0].schema) as writer:
        +        for batch in batches:
        +            writer.write_batch(batch)
        +    return sink.getvalue().to_pybytes()
        +
        +
        +@contextlib.contextmanager
        +def streamed_query_table(write_body):
        +    """Yield a remote table and the headers of each query request it sends.
        +
        +    Queries get a 200 response with stream framing, whose body ``write_body``
        +    writes after the other headers.
        +    """
        +    queries = []
        +
        +    def handler(request):
        +        if request.path == "/v1/table/test/describe/":
        +            id_field = {"name": "id", "type": {"type": "int32"}, "nullable": True}
        +            schema = {"fields": [id_field]}
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.end_headers()
        +            request.wfile.write(json.dumps({"version": 7, "schema": schema}).encode())
        +        elif request.path == "/v1/table/test/query/":
        +            queries.append(request.headers)
        +            request.rfile.read(int(request.headers["Content-Length"]))
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
        +            request.send_header("x-lancedb-version", "7")
        +            write_body(request)
        +        else:
        +            request.send_response(404)
        +            request.end_headers()
        +
        +    with mock_lancedb_connection(handler) as db:
        +        yield db.open_table("test"), queries
        +
        +
        +def test_query_sync_to_batches_yields_before_the_body_is_complete():
        +    batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)]
        +    body = _arrow_stream(batches)
        +    # The schema and first batch, without the 8-byte end-of-stream marker.
        +    head = _arrow_stream(batches[:1])[:-8]
        +    first_batch_read = threading.Event()
        +    waited_for_client = []
        +
        +    def write_body(request):
        +        request.end_headers()
        +        request.wfile.write(head)
        +        waited_for_client.append(first_batch_read.wait(10))
        +        request.wfile.write(body[len(head) :])
        +
        +    with streamed_query_table(write_body) as (table, queries):
        +        reader = table.search().to_batches()
        +        assert reader.read_next_batch()["id"].to_pylist() == [0]
        +        first_batch_read.set()
        +        assert reader.read_all()["id"].to_pylist() == [1, 2]
        +
        +    # The wait times out if the client needs the whole body for the first batch.
        +    assert waited_for_client == [True]
        +    assert queries[0]["Accept"] == (
        +        "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9"
        +    )
        +
        +
        +@pytest.mark.parametrize("abort", [False, True], ids=["clean_end", "abort"])
        +def test_query_sync_interrupted_response_raises(abort):
        +    batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)]
        +    head = _arrow_stream(batches[:1])[:-8]
        +
        +    def write_body(request):
        +        if abort:
        +            # Closing before the promised length is a transport error. Otherwise
        +            # the body ends cleanly, but without the end-of-stream marker.
        +            request.send_header("Content-Length", str(len(head) + 100))
        +        request.end_headers()
        +        request.wfile.write(head)
        +
        +    with streamed_query_table(write_body) as (table, queries):
        +        reader = table.search().to_batches()
        +        assert reader.read_next_batch()["id"].to_pylist() == [0]
        +        with pytest.raises(ResponseInterruptedError) as exc_info:
        +            reader.read_next_batch()
        +
        +    error = exc_info.value
        +    assert isinstance(error, HttpError)
        +    assert (error.batches, error.rows, error.table_version) == (1, 1, 7)
        +    assert error.request_id == queries[0]["x-request-id"]
        +    assert error.is_transport_error is abort
        +    assert len(queries) == 1
        +
        +
         @pytest.mark.parametrize("query_type", ["auto", "vector", "hybrid"])
         @pytest.mark.parametrize("vector_column_name", [None, "embedding"])
         def test_query_sync_text_embedding(query_type, vector_column_name):
        @@ -4143,12 +5574,10 @@ def test_background_loop_cancellation(exception):
             mock_future = MagicMock()
             mock_future.result.side_effect = exception()
         
        -    with (
        -        patch.object(BackgroundEventLoop, "__init__", return_value=None),
        -        patch("asyncio.run_coroutine_threadsafe", return_value=mock_future),
        -    ):
        +    with patch("asyncio.run_coroutine_threadsafe", return_value=mock_future):
                 loop = BackgroundEventLoop()
                 loop.loop = MagicMock()
        +        loop.thread = MagicMock()
                 with pytest.raises(exception):
                     loop.run(None)
                 mock_future.cancel.assert_called_once()
        @@ -4451,10 +5880,14 @@ def test_remote_schema_restores_blob_extensions(use_async, with_pylance, nested)
         
         @pytest.mark.asyncio
         @pytest.mark.parametrize("use_async", [False, True])
        -@pytest.mark.parametrize("mode", ["merge", "overwrite"])
        +@pytest.mark.parametrize(
        +    "mode,part_status",
        +    [("merge", 200), ("overwrite", 200), ("overwrite", 503)],
        +    ids=["merge", "overwrite", "overwrite-retry"],
        +)
         @pytest.mark.parametrize("target_with_ranges", [False, True])
         async def test_remote_writes_normalize_blob_layouts(
        -    use_async, mode, target_with_ranges
        +    use_async, mode, part_status, target_with_ranges, mem_db
         ):
             description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE))
             if target_with_ranges:
        @@ -4463,29 +5896,77 @@ async def test_remote_writes_normalize_blob_layouts(
                     for name in ("position", "size")
                 )
             received = []
        +    paths = []
        +    staged = {}
        +    part_attempts = []
        +    published = mem_db.create_table(
        +        "published",
        +        [{"id": 0, "image": b"before"}],
        +        schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]),
        +    )
         
             def handler(request):
        -        if request.path == "/v1/table/test/describe/":
        +        path = urlparse(request.path).path
        +        query = parse_qs(urlparse(request.path).query)
        +        status = 200
        +        if path == "/v1/table/test/describe/":
                     response = description
                 else:
        -            expected = "merge_insert" if mode == "merge" else "insert"
        -            assert urlparse(request.path).path == f"/v1/table/test/{expected}/"
        -            if request.headers.get("Transfer-Encoding") == "chunked":
        -                body = bytearray()
        -                while size := int(request.rfile.readline().split(b";")[0], 16):
        -                    body.extend(request.rfile.read(size))
        -                    assert request.rfile.read(2) == b"\r\n"
        -                assert request.rfile.read(2) == b"\r\n"
        +            paths.append(path.removeprefix("/v1/table/test/"))
        +            body = request.rfile.read()
        +            if path == "/v1/table/test/multipart_write/create":
        +                assert mode == "overwrite"
        +                assert paths == ["multipart_write/create"]
        +                assert not query and not body
        +                response = {"upload_id": "blob-overwrite"}
        +            elif path == "/v1/table/test/insert/":
        +                assert mode == "overwrite"
        +                assert query["mode"] == ["overwrite"]
        +                assert query["upload_id"] == ["blob-overwrite"]
        +                part_id = query["upload_part_id"][0]
        +                assert str(uuid.UUID(part_id)) == part_id
        +                part_attempts.append((part_id, body))
        +                assert published.version == 1
        +                assert published.search().select(["id"]).to_list() == [{"id": 0}]
        +                if staged:
        +                    assert staged == {part_id: body}
        +                else:
        +                    staged[part_id] = body
        +                    assert body[-8:] == b"\xff\xff\xff\xff\x00\x00\x00\x00"
        +                    received.append(pa.ipc.open_stream(body).read_all())
        +                status = part_status if len(part_attempts) == 1 else 200
        +                response = {}
        +            elif path == "/v1/table/test/multipart_write/complete":
        +                assert mode == "overwrite"
        +                assert query == {"upload_id": ["blob-overwrite"]} and not body
        +                expected_attempts = 2 if part_status == 503 else 1
        +                assert paths == ["multipart_write/create"] + [
        +                    "insert/"
        +                ] * expected_attempts + ["multipart_write/complete"]
        +                assert len(staged) == len(received) == 1
        +                assert part_attempts == [part_attempts[0]] * expected_attempts
        +                assert published.version == 1
        +                published.add(received[0], mode="overwrite")
        +                response = {"version": published.version}
                     else:
        -                body = request.rfile.read(int(request.headers["Content-Length"]))
        -            received.append(pa.ipc.open_stream(body).read_all())
        -            response = {
        -                "version": 2,
        -                "num_updated_rows": 0,
        -                "num_inserted_rows": 2,
        -                "num_deleted_rows": 0,
        -            }
        -        request.send_response(200)
        +                assert mode == "merge"
        +                assert path == "/v1/table/test/merge_insert/"
        +                # merge_insert still streams a chunked body; preserve its framing.
        +                if request.headers.get("Transfer-Encoding") == "chunked":
        +                    stream = io.BytesIO(body)
        +                    body = bytearray()
        +                    while size := int(stream.readline().split(b";")[0], 16):
        +                        body.extend(stream.read(size))
        +                        assert stream.read(2) == b"\r\n"
        +                    assert stream.read(2) == b"\r\n"
        +                received.append(pa.ipc.open_stream(body).read_all())
        +                response = {
        +                    "version": 2,
        +                    "num_updated_rows": 0,
        +                    "num_inserted_rows": 2,
        +                    "num_deleted_rows": 0,
        +                }
        +        request.send_response(status)
                 request.send_header("Content-Type", "application/json")
                 request.send_header("phalanx-version", "0.5.0")
                 request.end_headers()
        @@ -4518,7 +5999,23 @@ async def test_remote_writes_normalize_blob_layouts(
                 else:
                     result = table.add(data, mode="overwrite")
                 if use_async:
        -            await result
        +            result = await result
        +        assert result.version == 2
        +
        +    if mode == "overwrite":
        +        assert published.version == 2
        +        hits = published.search().select(["id"]).with_row_id(True).to_arrow()
        +        by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist()))
        +        assert set(by_id) == {1, 2}
        +        row_ids = [by_id[1], by_id[2]]
        +        assert published.fetch_blobs("image", row_ids).to_pylist() == [b"payload", None]
        +        payload, null = published.fetch_blob_files("image", row_ids)
        +        assert null is None
        +        with payload:
        +            assert payload.read_range(1, 3) == b"ayl"
        +            assert payload.read() == b"payload"
        +    else:
        +        assert paths == ["merge_insert/"]
         
             assert len(received) == 1
             images = received[0]["image"].combine_chunks()
        @@ -4594,15 +6091,42 @@ def blob_descriptor_take_table():
             )
         
         
        +_DEFAULT_DESCRIPTOR_IDENTITY = object()
        +
        +
         @contextlib.contextmanager
        -def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
        +def blob_remote_table(
        +    *,
        +    server_version=Version("0.5.0"),
        +    location=None,
        +    range_capability=None,
        +    version_header="1",
        +    framing="file",
        +    requests=None,
        +    state=None,
        +    empty=False,
        +    schema_version=None,
        +    search_scores=False,
        +    snapshot_supported=True,
        +    identity_header="v1:" + "a" * 64,
        +    descriptor_identity_header=_DEFAULT_DESCRIPTOR_IDENTITY,
        +    verify_identity=True,
        +):
        +    if state is None:
        +        state = {"version": 1}
        +
             def handler(request):
                 if request.path == "/v1/table/test/describe/":
        +            content_len = int(request.headers.get("Content-Length", 0))
        +            body = json.loads(request.rfile.read(content_len)) if content_len else {}
                     request.send_response(200)
                     request.send_header("Content-Type", "application/json")
                     request.send_header("phalanx-version", str(server_version))
        +            if range_capability is not None:
        +                request.send_header("x-lancedb-blob-ranges", range_capability)
                     request.end_headers()
                     response = dict(BLOB_DESCRIBE_RESPONSE)
        +            response["version"] = body.get("version") or state["version"]
                     if location is not None:
                         response["location"] = str(location)
                     request.wfile.write(json.dumps(response).encode())
        @@ -4630,14 +6154,44 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
                     request.send_header(
                         "x-lancedb-version", str(BLOB_DESCRIBE_RESPONSE["version"])
                     )
        +            if verify_identity and request.headers.get("x-lancedb-query-snapshot"):
        +                request.send_header(
        +                    "x-lancedb-query-snapshot",
        +                    request.headers["x-lancedb-query-snapshot"],
        +                )
                     request.end_headers()
                     request.wfile.write(chunk)
                 elif request.path == "/v1/table/test/query/":
                     content_len = int(request.headers.get("Content-Length", 0))
                     body = json.loads(request.rfile.read(content_len))
        +            if requests is not None:
        +                requests.append(("query", body))
                     columns = body.get("columns")
        -            assert columns in (None, ["id", "image"], ["id"], ["image"])
        -            if columns == ["id"]:
        +            take_offsets_query = isinstance(columns, list) and "_rowoffset" in columns
        +            assert take_offsets_query or columns in (
        +                None,
        +                ["id", "image"],
        +                ["id"],
        +                ["image"],
        +                {"payload": "image"},
        +            )
        +            if take_offsets_query:
        +                response_table = blob_query_response_table().append_column(
        +                    "_rowoffset", pa.array(range(3), type=pa.uint64())
        +                )
        +                response_table = response_table.select(
        +                    [name for name in columns if name != "_rowid"]
        +                )
        +                if body.get("with_row_id", False):
        +                    response_table = response_table.append_column(
        +                        "_rowid", blob_query_response_table()["_rowid"]
        +                    )
        +            elif isinstance(columns, dict):
        +                response_table = blob_query_response_table().select(["image", "_rowid"])
        +                response_table = response_table.rename_columns(["payload", "_rowid"])
        +                if not body.get("with_row_id", False):
        +                    response_table = response_table.drop(["_rowid"])
        +            elif columns == ["id"]:
                         response_table = blob_query_response_table().select(["id"])
                     else:
                         if columns == ["image"]:
        @@ -4654,25 +6208,131 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
                             response_table = blob_query_response_table()
                         if not body.get("with_row_id", False):
                             response_table = response_table.drop(["_rowid"])
        +            if search_scores and not body.get("filter", "").startswith("_rowid IN"):
        +                if body.get("vector"):
        +                    response_table = response_table.append_column(
        +                        "_distance", pa.array([0.1, 0.2, 0.3], type=pa.float32())
        +                    )
        +                elif body.get("full_text_query"):
        +                    response_table = response_table.append_column(
        +                        "_score", pa.array([3.0, 2.0, 1.0], type=pa.float32())
        +                    )
        +            if empty:
        +                response_table = response_table.slice(0, 0)
        +            if schema_version is not None:
        +                response_table = response_table.replace_schema_metadata(
        +                    {
        +                        b"lancedb:query_version": schema_version.encode(),
        +                        b"lancedb:query_snapshot": ("v1:" + "f" * 64).encode(),
        +                    }
        +                )
                     request.send_response(200)
        -            request.send_header("Content-Type", "application/vnd.apache.arrow.file")
        -            request.send_header("x-lancedb-version", "1")
        +            request.send_header(
        +                "Content-Type", f"application/vnd.apache.arrow.{framing}"
        +            )
        +            header = (
        +                version_header(body) if callable(version_header) else version_header
        +            )
        +            if header is not None:
        +                request.send_header("x-lancedb-version", header)
        +                if snapshot_supported:
        +                    request.send_header("x-lancedb-query-version", header)
        +                    descriptor_query = body.get("filter", "").startswith("_rowid IN")
        +                    use_descriptor_identity = (
        +                        descriptor_query
        +                        and descriptor_identity_header
        +                        is not _DEFAULT_DESCRIPTOR_IDENTITY
        +                    )
        +                    if use_descriptor_identity:
        +                        identity = descriptor_identity_header
        +                    else:
        +                        identity = (
        +                            identity_header(body)
        +                            if callable(identity_header)
        +                            else identity_header
        +                        )
        +                    if identity is not None:
        +                        request.send_header("x-lancedb-query-snapshot", identity)
                     request.end_headers()
        -            with pa.ipc.new_file(request.wfile, response_table.schema) as writer:
        +            writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream
        +            with writer_factory(request.wfile, response_table.schema) as writer:
        +                writer.write_table(response_table, max_chunksize=1)
        +        elif (
        +            range_capability == "1"
        +            and request.path == "/v1/table/test/fetch_blob_ranges/"
        +        ):
        +            size = int(request.headers["Content-Length"])
        +            body = json.loads(request.rfile.read(size))
        +            payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""}
        +            values = []
        +            for item in body["ranges"]:
        +                row, offset, length = (
        +                    item[key] for key in ("row_id", "offset", "length")
        +                )
        +                error = None
        +                if row not in payloads:
        +                    error = "only 1 exist"
        +                elif payloads[row] is not None and offset + length > len(payloads[row]):
        +                    error = "range exceeds blob size"
        +                if error:
        +                    request.send_response(400)
        +                    request.end_headers()
        +                    request.wfile.write(error.encode())
        +                    return
        +                payload = payloads[row]
        +                values.append(
        +                    None if payload is None else payload[offset : offset + length]
        +                )
        +            response_table = pa.table(
        +                {"value": pa.array(values, type=pa.large_binary())}
        +            )
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
        +            request.send_header("x-lancedb-version", "1")
        +            request.send_header("x-lancedb-query-snapshot", "v1:" + "a" * 64)
        +            request.end_headers()
        +            with pa.ipc.new_stream(request.wfile, response_table.schema) as writer:
                         writer.write_table(response_table)
                 elif request.path == "/v1/table/test/fetch_blobs/":
                     content_len = int(request.headers.get("Content-Length", 0))
                     body = json.loads(request.rfile.read(content_len))
                     assert body["column"] == "image"
        -            assert body["row_ids"] == [10, 20, 30]
        +            if requests is not None:
        +                requests.append(("fetch_blobs", body))
        +            payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""}
        +            if state["version"] > 1 and body.get("version") != 1:
        +                payloads = {row: b"new-version" for row in payloads}
                     response_table = pa.table(
        -                {"image": pa.array([b"alpha", None, b"gamma"], type=pa.large_binary())}
        +                {
        +                    "image": pa.array(
        +                        [payloads[row] for row in body["row_ids"]],
        +                        type=pa.large_binary(),
        +                    )
        +                }
                     )
                     request.send_response(200)
                     request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
        +            if verify_identity and request.headers.get("x-lancedb-query-snapshot"):
        +                request.send_header(
        +                    "x-lancedb-query-snapshot",
        +                    request.headers["x-lancedb-query-snapshot"],
        +                )
                     request.end_headers()
                     with pa.ipc.new_stream(request.wfile, response_table.schema) as writer:
                         writer.write_table(response_table)
        +        elif request.path == "/v1/table/test/insert/":
        +            if request.headers.get("Transfer-Encoding") == "chunked":
        +                while size := int(request.rfile.readline().split(b";")[0], 16):
        +                    request.rfile.read(size)
        +                    assert request.rfile.read(2) == b"\r\n"
        +                assert request.rfile.read(2) == b"\r\n"
        +            else:
        +                request.rfile.read(int(request.headers.get("Content-Length", 0)))
        +            state["version"] += 1
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.end_headers()
        +            request.wfile.write(json.dumps({"version": state["version"]}).encode())
                 else:
                     request.send_response(404)
                     request.end_headers()
        @@ -4681,6 +6341,222 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
                 yield db.open_table("test")
         
         
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("framing", ["file", "stream"])
        +@pytest.mark.parametrize("method", ["to_arrow", "to_list", "to_pandas", "to_batches"])
        +async def test_remote_blob_bytes_conversion(use_async, framing, method):
        +    if method == "to_pandas":
        +        pytest.importorskip("pandas")
        +    requests = []
        +    with blob_remote_table(framing=framing, requests=requests) as remote_table:
        +        table = remote_table._table if use_async else remote_table
        +        query = table.query() if use_async else table.search()
        +        query = query.select(["id", "image"])
        +        if method == "to_batches":
        +            kwargs = {"max_batch_length" if use_async else "batch_size": 1}
        +            reader = query.to_batches(blob_mode="bytes", **kwargs)
        +            if use_async:
        +                reader = await reader
        +                batches = [batch async for batch in reader]
        +            else:
        +                batches = list(reader)
        +            assert all(batch.num_rows == 1 for batch in batches)
        +            result = pa.Table.from_batches(batches, schema=reader.schema).to_pylist()
        +        else:
        +            result = getattr(query, method)(blob_mode="bytes")
        +            if use_async:
        +                result = await result
        +            if method == "to_arrow":
        +                assert result.schema.field("image").type == pa.large_binary()
        +                result = result.to_pylist()
        +            elif method == "to_pandas":
        +                result = result.to_dict("records")
        +        assert result == [
        +            {"id": 1, "image": b"alpha"},
        +            {"id": 2, "image": None},
        +            {"id": 3, "image": b"gamma"},
        +        ]
        +        fetches = [body for path, body in requests if path == "fetch_blobs"]
        +        assert fetches
        +        assert all(body["version"] == 1 for body in fetches)
        +        assert [row for body in fetches for row in body["row_ids"]] == [10, 20, 30]
        +        descriptor_queries = [
        +            body
        +            for path, body in requests
        +            if path == "query" and body.get("filter", "").startswith("_rowid IN")
        +        ]
        +        assert all(body["version"] == 1 for body in descriptor_queries)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("framing", ["file", "stream"])
        +async def test_remote_blob_bytes_keeps_query_snapshot_during_writes(use_async, framing):
        +    requests = []
        +    state = {"version": 1}
        +    with blob_remote_table(
        +        framing=framing, requests=requests, state=state
        +    ) as remote_table:
        +        table = remote_table._table if use_async else remote_table
        +        query = table.query() if use_async else table.search()
        +        kwargs = {"max_batch_length" if use_async else "batch_size": 1}
        +        reader = query.select(["id", "image"]).to_batches(blob_mode="bytes", **kwargs)
        +        if use_async:
        +            reader = await reader
        +        # The query has selected v1; commit v2 before consuming any payloads.
        +        write = table.add([{"id": 4, "image": b"new-version"}])
        +        if use_async:
        +            await write
        +        version = await table.version() if use_async else table.version
        +        assert version == 2
        +        if use_async:
        +            rows = [row async for batch in reader for row in batch.to_pylist()]
        +        else:
        +            rows = [row for batch in reader for row in batch.to_pylist()]
        +        assert [row["image"] for row in rows] == [b"alpha", None, b"gamma"]
        +        fetches = [body for path, body in requests if path == "fetch_blobs"]
        +        assert all(body["version"] == 1 for body in fetches)
        +        # Snapshot fetches must not check out the caller's live handle.
        +        version = await table.version() if use_async else table.version
        +        assert version == 2
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("version_header", [None, "invalid", "0", "-1", str(2**64)])
        +async def test_remote_blob_bytes_invalid_snapshot(use_async, version_header):
        +    requests = []
        +    with blob_remote_table(
        +        version_header=version_header, requests=requests, schema_version="1"
        +    ) as remote_table:
        +        table = remote_table._table if use_async else remote_table
        +        query = table.query() if use_async else table.search()
        +        with pytest.raises(NotImplementedError, match="x-lancedb-query-version"):
        +            result = query.to_arrow(blob_mode="bytes")
        +            if use_async:
        +                await result
        +    assert not any(path == "fetch_blobs" for path, _ in requests)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("framing", ["file", "stream"])
        +async def test_remote_blob_bytes_empty_results(use_async, framing):
        +    requests = []
        +    with blob_remote_table(
        +        empty=True, framing=framing, requests=requests
        +    ) as remote_table:
        +        table = remote_table._table if use_async else remote_table
        +        query = table.query() if use_async else table.search()
        +        result = query.to_arrow(blob_mode="bytes")
        +        if use_async:
        +            result = await result
        +        assert result.num_rows == 0
        +        assert result.schema.field("image").type == pa.large_binary()
        +        assert result.column_names == ["id", "image"]
        +    assert not any(path == "fetch_blobs" for path, _ in requests)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("kind", ["vector", "fts", "hybrid"])
        +@pytest.mark.parametrize("rerank", [False, True])
        +async def test_remote_blob_bytes_search_queries(use_async, kind, rerank):
        +    with blob_remote_table(search_scores=True) as remote_table:
        +        if use_async:
        +            query = remote_table._table.query()
        +            if kind in ("vector", "hybrid"):
        +                query = query.nearest_to([1.0, 2.0])
        +            if kind in ("fts", "hybrid"):
        +                query = query.nearest_to_text("hello")
        +        elif kind == "vector":
        +            query = remote_table.search([1.0, 2.0], vector_column_name="vector")
        +        elif kind == "fts":
        +            query = remote_table.search("hello", query_type="fts")
        +        else:
        +            query = (
        +                remote_table.search(query_type="hybrid", vector_column_name="vector")
        +                .vector([1.0, 2.0])
        +                .text("hello")
        +            )
        +        if rerank:
        +            from lancedb.rerankers import RRFReranker
        +
        +            class StripMetadataReranker(RRFReranker):
        +                def rerank_vector(self, query, vector_results):
        +                    return vector_results.append_column(
        +                        "_relevance_score", pa.array([3.0, 2.0, 1.0])
        +                    ).replace_schema_metadata(None)
        +
        +                def rerank_fts(self, query, fts_results):
        +                    return self.rerank_vector(query, fts_results)
        +
        +                def rerank_hybrid(self, query, vector_results, fts_results):
        +                    return (
        +                        super()
        +                        .rerank_hybrid(query, vector_results, fts_results)
        +                        .replace_schema_metadata(None)
        +                    )
        +
        +            kwargs = {"query_string": "hello"} if kind == "vector" else {}
        +            query = query.rerank(StripMetadataReranker(), **kwargs)
        +        result = query.select(["id", "image"]).to_arrow(blob_mode="bytes")
        +        if use_async:
        +            result = await result
        +        assert result["image"].to_pylist() == [b"alpha", None, b"gamma"]
        +        assert "_rowid" not in result.column_names
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_remote_blob_bytes_hybrid_rejects_different_snapshots(use_async):
        +    def header(body):
        +        return "2" if body.get("full_text_query") else "1"
        +
        +    requests = []
        +    with blob_remote_table(
        +        search_scores=True, version_header=header, requests=requests
        +    ) as remote_table:
        +        if use_async:
        +            query = (
        +                remote_table._table.query()
        +                .nearest_to([1.0, 2.0])
        +                .nearest_to_text("hello")
        +            )
        +        else:
        +            query = (
        +                remote_table.search(query_type="hybrid", vector_column_name="vector")
        +                .vector([1.0, 2.0])
        +                .text("hello")
        +            )
        +        with pytest.raises(
        +            NotImplementedError, match="inconsistent x-lancedb-query-version"
        +        ):
        +            result = query.select(["id", "image"]).to_arrow(blob_mode="bytes")
        +            if use_async:
        +                await result
        +    assert not any(path == "fetch_blobs" for path, _ in requests)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("with_row_id", [False, True])
        +async def test_remote_blob_bytes_alias_and_explicit_row_ids(use_async, with_row_id):
        +    with blob_remote_table() as remote_table:
        +        query = remote_table._table.query() if use_async else remote_table.search()
        +        query = query.select({"payload": "image"})
        +        if with_row_id:
        +            query = query.with_row_id() if use_async else query.with_row_id(True)
        +        result = query.to_arrow(blob_mode="bytes")
        +        if use_async:
        +            result = await result
        +        assert result["payload"].to_pylist() == [b"alpha", None, b"gamma"]
        +        assert ("_rowid" in result.column_names) == with_row_id
        +        if with_row_id:
        +            assert result["_rowid"].to_pylist() == [10, 20, 30]
        +
        +
         def test_remote_blob_columns_and_fetch():
             with blob_remote_table() as table:
                 assert table.blob_columns() == ["image"]
        @@ -4702,7 +6578,7 @@ def test_sync_remote_blob_pandas_avoids_storage_access(
                 raise AssertionError("remote storage must not be opened")
         
             monkeypatch.setattr(lance, "dataset", fail_dataset)
        -    with blob_remote_table(location=location) as table:
        +    with blob_remote_table(location=location, version_header=None) as table:
                 monkeypatch.setattr(table, "to_lance", fail_dataset)
                 query = table.search().select(["id", "image"])
                 if blob_mode == "descriptions":
        @@ -4711,14 +6587,24 @@ def test_sync_remote_blob_pandas_avoids_storage_access(
                     assert "_rowid" not in df.columns
                     assert df["image"][0]["size"] == 5
                 else:
        -            with pytest.raises(NotImplementedError, match="stable table snapshot"):
        +            with pytest.raises(
        +                NotImplementedError, match="stable table snapshot"
        +            ) as exc:
                         query.to_pandas(blob_mode=blob_mode)
        +            if blob_mode == "bytes":
        +                assert "x-lancedb-query-version" in str(exc.value)
        +            else:
        +                assert "fetch_blobs(column, row_ids)" in str(exc.value)
        +                assert "with_row_id(True)" in str(exc.value)
         
         
         @pytest.mark.asyncio
         @pytest.mark.parametrize("use_async", [False, True])
        -async def test_remote_fetch_blob_ranges(use_async):
        -    with blob_remote_table() as remote_table:
        +@pytest.mark.parametrize("range_capability", [None, "0", "2", "1"])
        +async def test_remote_fetch_blob_ranges(use_async, range_capability):
        +    with blob_remote_table(
        +        server_version="1.13.0-beta.0", range_capability=range_capability
        +    ) as remote_table:
                 table = remote_table._table if use_async else remote_table
                 requests = [
                     (30, 2, 3),
        @@ -4796,7 +6682,7 @@ async def test_async_remote_blob_descriptions_to_pandas_uses_server(monkeypatch)
         @pytest.mark.asyncio
         @pytest.mark.parametrize("blob_mode", ["bytes", "lazy"])
         async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode):
        -    with blob_remote_table() as remote_table:
        +    with blob_remote_table(version_header=None) as remote_table:
                 table = remote_table._table
         
                 async def fail_uri():
        @@ -4821,8 +6707,8 @@ async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob
         
         
         @pytest.mark.parametrize("method", ["to_arrow", "to_list"])
        -def test_remote_search_bytes_refused_before_query(monkeypatch, method):
        -    with blob_remote_table() as table:
        +def test_remote_search_bytes_requires_response_version(method):
        +    with blob_remote_table(version_header=None) as table:
                 query = table.search().select(["id", "image"])
                 descriptions = getattr(query, method)(blob_mode="descriptions")
                 images = (
        @@ -4832,19 +6718,15 @@ def test_remote_search_bytes_refused_before_query(monkeypatch, method):
                 )
                 assert "_lance_row_id" not in images[0]
         
        -        def fail_query(*args, **kwargs):
        -            raise AssertionError("bytes must be refused before the query runs")
        -
        -        monkeypatch.setattr(table, "_execute_query", fail_query)
        -        with pytest.raises(NotImplementedError, match="stable table snapshot"):
        +        with pytest.raises(NotImplementedError, match="x-lancedb-query-version"):
                     getattr(query, method)(blob_mode="bytes")
                 with pytest.raises(ValueError, match="blob_mode must be one of"):
                     table.to_pandas(blob_mode="handles")
         
         
         @pytest.mark.asyncio
        -async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch):
        -    with blob_remote_table() as remote_table:
        +async def test_async_remote_to_arrow_bytes_requires_response_version(monkeypatch):
        +    with blob_remote_table(version_header=None) as remote_table:
                 table = remote_table._table
         
                 async def fail_fetch(*args, **kwargs):
        @@ -4852,8 +6734,7 @@ async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch):
         
                 monkeypatch.setattr(table, "fetch_blobs", fail_fetch)
                 query = table.query().select(["id", "image"])
        -        monkeypatch.setattr(query, "to_batches", fail_fetch)
        -        with pytest.raises(NotImplementedError, match="stable table snapshot"):
        +        with pytest.raises(NotImplementedError, match="x-lancedb-query-version"):
                     await query.to_arrow(blob_mode="bytes")
                 with pytest.raises(NotImplementedError, match="stable table snapshot"):
                     await table.to_arrow(blob_mode="bytes")
        @@ -4917,13 +6798,114 @@ def test_remote_blob_file_matches_file_error_and_range_contract():
                     handle.read(1)
         
         
        -def test_remote_blob_fetch_accepts_query_table():
        +@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
        +def test_remote_blob_fetch_accepts_metadata_free_query_table(api):
             hits = pa.table({"_rowid": pa.array([10, 20, 30], type=pa.uint64())})
         
        -    with blob_remote_table() as table:
        -        blobs = table.fetch_blobs("image", hits)
        +    with blob_remote_table(descriptor_identity_header=None) as table:
        +        if api == "fetch_blobs":
        +            assert table.fetch_blobs("image", hits).to_pylist() == [
        +                b"alpha",
        +                None,
        +                b"gamma",
        +            ]
        +        else:
        +            handles = table.fetch_blob_files("image", hits)
        +            try:
        +                assert [
        +                    handle.read() if handle is not None else None for handle in handles
        +                ] == [b"alpha", None, b"gamma"]
        +            finally:
        +                for handle in handles:
        +                    if handle is not None:
        +                        handle.close()
         
        -    assert blobs.to_pylist() == [b"alpha", None, b"gamma"]
        +
        +def test_remote_take_offsets_preserve_order_with_blob_bytes():
        +    with blob_remote_table() as table:
        +        hits = (
        +            table.take_offsets([2, 0, 2], preserve_order=True)
        +            .select(["id", "image"])
        +            .to_arrow(blob_mode="bytes")
        +        )
        +
        +    assert hits["id"].to_pylist() == [3, 1, 3]
        +    assert hits["image"].to_pylist() == [b"gamma", b"alpha", b"gamma"]
        +
        +
        +@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
        +def test_remote_blob_fetch_from_query_result_keeps_query_snapshot(api):
        +    requests = []
        +    state = {"version": 1}
        +    with blob_remote_table(requests=requests, state=state) as table:
        +        hits = table.search().select(["id", "image"]).limit(3).to_arrow()
        +        assert hits.schema.metadata[b"lancedb:query_version"] == b"1"
        +        table.add([{"id": 4, "image": b"new-version"}])
        +        assert table.version == 2
        +
        +        if api == "fetch_blobs":
        +            assert table.fetch_blobs("image", hits).to_pylist() == [
        +                b"alpha",
        +                None,
        +                b"gamma",
        +            ]
        +            fetches = [body for path, body in requests if path == "fetch_blobs"]
        +            assert fetches
        +            assert all(body["version"] == 1 for body in fetches)
        +        else:
        +            handles = table.fetch_blob_files("image", hits)
        +            try:
        +                assert [
        +                    handle.read() if handle is not None else None for handle in handles
        +                ] == [b"alpha", None, b"gamma"]
        +            finally:
        +                for handle in handles:
        +                    if handle is not None:
        +                        handle.close()
        +            descriptor_queries = [
        +                body
        +                for path, body in requests
        +                if path == "query" and body.get("filter", "").startswith("_rowid IN")
        +            ]
        +            assert descriptor_queries
        +            assert all(body["version"] == 1 for body in descriptor_queries)
        +
        +
        +@pytest.mark.parametrize("descriptor_identity", [None, "v1:" + "b" * 64])
        +def test_remote_blob_files_reject_unverified_descriptor_identity(descriptor_identity):
        +    requested = "v1:" + "a" * 64
        +    hits = pa.table(
        +        {"_rowid": pa.array([20, 40], type=pa.uint64())}
        +    ).replace_schema_metadata(
        +        {
        +            b"lancedb:query_version": b"1",
        +            b"lancedb:query_snapshot": requested.encode(),
        +        }
        +    )
        +    requests = []
        +
        +    with blob_remote_table(
        +        requests=requests, descriptor_identity_header=descriptor_identity
        +    ) as table:
        +        with pytest.raises(
        +            NotImplementedError, match="did not verify the query snapshot identity"
        +        ):
        +            table.fetch_blob_files("image", hits)
        +
        +    assert not any(path.startswith("/v1/table/test/blob/") for path, _ in requests)
        +    assert not any(path == "/v1/table/test/fetch_blobs/" for path, _ in requests)
        +
        +
        +@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
        +def test_remote_blob_fetch_rejects_incomplete_query_snapshot(api):
        +    requests = []
        +    hits = pa.table(
        +        {"_rowid": pa.array([10], type=pa.uint64())}
        +    ).replace_schema_metadata({b"lancedb:query_version": b"1"})
        +    with blob_remote_table(requests=requests) as table:
        +        with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"):
        +            getattr(table, api)("image", hits)
        +    assert not any(path == "fetch_blobs" for path, _ in requests)
         
         
         def test_remote_blob_query_stashes_row_ids_for_fetch():
        @@ -4950,7 +6932,7 @@ def test_remote_blob_query_to_pandas():
         
         @pytest.mark.parametrize("blob_mode", ["default", "lazy", "bytes"])
         def test_remote_blob_query_to_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode):
        -    with blob_remote_table() as table:
        +    with blob_remote_table(version_header=None) as table:
         
                 def fail_fetch(*args, **kwargs):
                     raise AssertionError("blob fetch must not use an unpinned remote table")
        @@ -5076,10 +7058,29 @@ def test_remote_connection_jobs_surface():
                                 dict(
                                     job_id="job-2",
                                     table="t2",
        -                            job_type="create_index",
        +                            job_type="function_refresh",
                                     state="succeeded",
                                     created_at_millis=2000,
        -                        )
        +                            completed_at_millis=2000,
        +                            duration_millis=0,
        +                            columns=["embedding"],
        +                            function_name="features$embed",
        +                            function_version="7",
        +                        ),
        +                        dict(
        +                            job_id="job-3",
        +                            table="t2",
        +                            job_type="function_refresh",
        +                            state="failed",
        +                            created_at_millis=3000,
        +                            completed_at_millis=3200,
        +                            duration_millis=200,
        +                            failure=dict(
        +                                phase="execute",
        +                                message="worker failed",
        +                                retryable=False,
        +                            ),
        +                        ),
                             ]
                         )
                     request.send_response(200)
        @@ -5126,6 +7127,10 @@ def test_remote_connection_jobs_surface():
                                 failure=dict(
                                     phase="execute",
                                     message="worker died",
        +                            traceback=(
        +                                "Traceback (most recent call last):\n"
        +                                "RuntimeError: worker died"
        +                            ),
                                     retryable=True,
                                     sql_job_id="sql-job-1",
                                 ),
        @@ -5173,7 +7178,7 @@ def test_remote_connection_jobs_surface():
         
             with mock_lancedb_connection(handler) as db:
                 jobs = list(db.list_jobs())
        -        assert [job.job_id for job in jobs] == ["job-1", "job-2"]
        +        assert [job.job_id for job in jobs] == ["job-1", "job-2", "job-3"]
                 assert jobs[0].state == "running"
                 assert jobs[0].table == "t1"
                 assert jobs[0].progress == {
        @@ -5187,6 +7192,24 @@ def test_remote_connection_jobs_surface():
                 }
                 assert jobs[0].paused is True
                 assert jobs[1].state == "finished"
        +        assert jobs[0].completed_at_millis is None
        +        assert jobs[0].duration_millis is None
        +        assert jobs[0].columns == []
        +        assert jobs[0].function_name is None
        +        assert jobs[0].function_version is None
        +        assert jobs[0].failure is None
        +        assert jobs[1].completed_at_millis == 2000
        +        assert jobs[1].duration_millis == 0
        +        assert jobs[1].columns == ["embedding"]
        +        assert jobs[1].function_name == "features$embed"
        +        assert jobs[1].function_version == "7"
        +        assert jobs[1].failure is None
        +        assert jobs[2].state == "failed"
        +        assert jobs[2].duration_millis == 200
        +        assert jobs[2].failure.phase == "execute"
        +        assert jobs[2].failure.message == "worker failed"
        +        assert jobs[2].failure.retryable is False
        +        assert jobs[2].failure.traceback is None
         
                 assert db.cancel_job("job-1") is True
                 assert db.cancel_job("missing") is False
        @@ -5198,14 +7221,14 @@ def test_remote_connection_jobs_surface():
                 with pytest.raises(JobNotFoundError, match="missing"):
                     db.open_job("missing")
                 finished = db.open_job("job-2")
        -        assert finished.state == "finished"
        -        assert finished.result == {"rows_assigned": 1000000, "rows_failed": 0}
        +        assert finished.state() == "finished"
        +        assert finished.result() == {"rows_assigned": 1000000, "rows_failed": 0}
         
                 job = db.open_job("job-1")
        -        assert job.id == "job-1"
        +        assert job.id() == "job-1"
                 # Opening already populated the handle.
        -        assert job.state == "failed"
        -        assert job.spec == {"column": "vec"}
        +        assert job.state() == "failed"
        +        assert job.spec() == {"column": "vec"}
                 progress = job.progress()
                 assert progress["state"] == "failed"
                 assert progress["rows_computed"] == 4
        @@ -5214,9 +7237,12 @@ def test_remote_connection_jobs_surface():
                 assert progress["queue_reason"] == "waiting for capacity"
                 assert progress["waiting_for_job_id"] == "job-maintenance"
                 assert progress["paused_at_millis"] == 1200
        -        assert job.failure.message == "worker died"
        -        assert job.failure.sql_job_id == "sql-job-1"
        -        assert repr(job.failure) == (
        +        assert job.failure().message == "worker died"
        +        assert job.failure().traceback == (
        +            "Traceback (most recent call last):\nRuntimeError: worker died"
        +        )
        +        assert job.failure().sql_job_id == "sql-job-1"
        +        assert repr(job.failure()) == (
                     'JobFailureInfo(phase="execute", message="worker died", retryable=True, '
                     'sql_job_id="sql-job-1")'
                 )
        @@ -5231,7 +7257,13 @@ def test_remote_connection_jobs_surface():
                 assert finished.progress()["paused"] is False
         
         
        -def test_remote_job_handle_reports_its_own_detail():
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("is_async", [False, True])
        +@pytest.mark.parametrize("refresh_method", ["checkout_latest", "refresh"])
        +@pytest.mark.parametrize("terminal_state", ["DONE", "FAILED"])
        +async def test_remote_job_handle_reports_its_own_detail(
        +    is_async, refresh_method, terminal_state
        +):
             schema = pa.schema([("state", pa.string())])
             batch = pa.record_batch([pa.array(["claim_complete"])], schema=schema)
             sink = pa.BufferOutputStream()
        @@ -5239,27 +7271,25 @@ def test_remote_job_handle_reports_its_own_detail():
                 writer.write_batch(batch)
             events_body = sink.getvalue().to_pybytes()
             event_payloads = []
        +    descriptions = []
        +    description = dict(
        +        job_id="job-1",
        +        job_type="refresh_column",
        +        job_state="IN_PROGRESS",
        +        creation_ms=2000,
        +        spec=dict(column="vec"),
        +    )
         
             def handler(request):
                 content_len = int(request.headers.get("Content-Length", 0))
                 body = request.rfile.read(content_len) if content_len > 0 else b""
                 payload = json.loads(body) if body else {}
                 if request.path == "/v1/jobs/describe":
        +            descriptions.append(payload)
                     request.send_response(200)
                     request.send_header("Content-Type", "application/json")
                     request.end_headers()
        -            request.wfile.write(
        -                json.dumps(
        -                    dict(
        -                        job_id="job-1",
        -                        job_type="refresh_column",
        -                        job_state="DONE",
        -                        creation_ms=2000,
        -                        spec=dict(column="vec"),
        -                        result=dict(rows_assigned=1000000),
        -                    )
        -                ).encode()
        -            )
        +            request.wfile.write(json.dumps(description).encode())
                 elif request.path == "/v1/jobs/query_events":
                     event_payloads.append(payload)
                     request.send_response(200)
        @@ -5270,46 +7300,75 @@ def test_remote_job_handle_reports_its_own_detail():
                     request.send_response(404)
                     request.end_headers()
         
        -    with mock_lancedb_connection(handler) as db:
        -        job = db.open_job("job-1")
        +    async def check_job(db):
        +        job = (
        +            await db.open_job("job-1")
        +            if is_async
        +            else await asyncio.to_thread(db.open_job, "job-1")
        +        )
         
                 # Opening populates the handle in the same round trip.
        -        assert job.state == "finished"
        -        job.refresh()
        -        assert job.job_type == "refresh_column"
        -        assert job.creation_ms == 2000
        -        assert job.spec == {"column": "vec"}
        -        assert job.result == {"rows_assigned": 1000000}
        -        assert job.failure is None
        +        assert job.state() == "running"
        +        assert job.result() is None
        +        assert job.failure() is None
        +        description["job_state"] = terminal_state
        +        expected_result = (
        +            {"rows_assigned": 1000000} if terminal_state == "DONE" else None
        +        )
        +        description["result"] = expected_result
        +        if terminal_state == "FAILED":
        +            description["failure"] = {"phase": "execute", "message": "worker failed"}
        +        assert job.state() == "running"
        +        assert job.result() is None
        +        assert job.failure() is None
        +        assert len(descriptions) == 1
        +
        +        refresh = getattr(job, refresh_method)
        +        if is_async:
        +            assert await refresh() is None
        +        else:
        +            assert await asyncio.to_thread(refresh) is None
        +        expected_state = "finished" if terminal_state == "DONE" else "failed"
        +        assert job.state() == expected_state
        +        assert job.job_type() == "refresh_column"
        +        assert job.creation_ms() == 2000
        +        assert job.spec() == {"column": "vec"}
        +        assert job.result() == expected_result
        +        if terminal_state == "FAILED":
        +            assert job.failure().phase == "execute"
        +            assert job.failure().message == "worker failed"
        +        else:
        +            assert job.failure() is None
                 # The JSON payloads stay reachable, but as internal APIs.
                 assert json.loads(job._spec_json) == {"column": "vec"}
        -        assert json.loads(job._result_json) == {"rows_assigned": 1000000}
        +        if expected_result is not None:
        +            assert json.loads(job._result_json) == expected_result
        +            assert repr(job) == "\n".join(
        +                [
        +                    f"{type(job).__name__}(",
        +                    "    id='job-1',",
        +                    "    state='finished',",
        +                    "    job_type='refresh_column',",
        +                    "    creation_ms=2000,",
        +                    "    spec={'column': 'vec'},",
        +                    "    result={'rows_assigned': 1000000},",
        +                    ")",
        +                ]
        +            )
        +            assert "failure" not in repr(job)
         
        -        # print() shows everything the handle knows and nothing it does not.
        -        # print() lays every known field out on its own line, with the JSON
        -        # payloads indented rather than crammed onto one line.
        -        assert repr(job) == "\n".join(
        -            [
        -                "Job(",
        -                "    id='job-1',",
        -                "    state='finished',",
        -                "    job_type='refresh_column',",
        -                "    creation_ms=2000,",
        -                "    spec={",
        -                '        "column": "vec"',
        -                "    },",
        -                "    result={",
        -                '        "rows_assigned": 1000000',
        -                "    },",
        -                ")",
        -            ]
        +        events = (
        +            await job.events(filter="state = 'claim_complete'", limit=500)
        +            if is_async
        +            else await asyncio.to_thread(
        +                job.events, filter="state = 'claim_complete'", limit=500
        +            )
                 )
        -        # Nothing it does not know shows up.
        -        assert "failure" not in repr(job)
        -
        -        events = job.events(filter="state = 'claim_complete'", limit=500)
                 assert isinstance(events, pa.Table)
                 assert events.column("state").to_pylist() == ["claim_complete"]
        +        assert len(descriptions) == 2
        +        assert job.state() == expected_state
        +        assert job.result() == expected_result
                 # The handle supplies job_id; the caller only narrows the query.
                 assert event_payloads[-1] == {
                     "job_id": "job-1",
        @@ -5317,6 +7376,100 @@ def test_remote_job_handle_reports_its_own_detail():
                     "filter": "state = 'claim_complete'",
                 }
         
        +    if is_async:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            await check_job(db)
        +    else:
        +        with mock_lancedb_connection(handler) as db:
        +            await check_job(db)
        +
        +
        +@pytest.mark.parametrize("is_async", [False, True])
        +@pytest.mark.parametrize("known_build", [False, True])
        +@pytest.mark.asyncio
        +async def test_remote_server_info(is_async, known_build):
        +    requests = []
        +    expected = {
        +        "query_node": {
        +            "release": "1.2.3",
        +            "git_sha": "0123456789ab",
        +            "build_date": "2024-01-01T00:00:00Z",
        +        }
        +        if known_build
        +        else None,
        +        "lance_version": "5.0.0",
        +        "lancedb_version": "0.42.0",
        +        "function_worker_protocol_version": 25,
        +        "configured_query_node_image": "example.invalid/query:configured",
        +        "configured_job_worker_image": "example.invalid/cpu:configured",
        +        "configured_sql_job_image": "example.invalid/cli:configured",
        +        "configured_gpu_worker_image": "example.invalid/worker:configured",
        +    }
        +
        +    def handler(request):
        +        requests.append((request.command, request.path))
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(expected).encode())
        +
        +    if is_async:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            actual = await db.server_info()
        +    else:
        +        with mock_lancedb_connection(handler) as db:
        +            actual = db.server_info()
        +
        +    assert actual == expected
        +    assert json.loads(json.dumps(actual)) == expected
        +    assert requests == [("GET", "/v1/server/info")]
        +
        +
        +@pytest.mark.parametrize("is_async", [False, True])
        +@pytest.mark.parametrize("status", [404, 403])
        +@pytest.mark.asyncio
        +async def test_remote_server_info_errors(is_async, status):
        +    requests = []
        +
        +    def handler(request):
        +        requests.append((request.command, request.path))
        +        request.send_response(status)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(
        +            json.dumps(
        +                {
        +                    "error": "discovery unavailable",
        +                    "server": {
        +                        "release": "1.2.3",
        +                        "git_sha": "0123456789ab",
        +                        "build_date": "2024-01-01T00:00:00Z",
        +                    },
        +                }
        +            ).encode()
        +        )
        +
        +    expected_error = NotImplementedError if status == 404 else HttpError
        +    with pytest.raises(expected_error) as caught:
        +        if is_async:
        +            async with mock_lancedb_connection_async(handler) as db:
        +                await db.server_info()
        +        else:
        +            with mock_lancedb_connection(handler) as db:
        +                db.server_info()
        +
        +    if status == 404:
        +        assert "/v1/server/info" in str(caught.value)
        +    else:
        +        # Permission responses do not carry the input-error classifier header.
        +        # The native HTTP error and Python conversion must retain provenance.
        +        assert "discovery unavailable" in str(caught.value)
        +        assert "1.2.3" in str(caught.value)
        +        assert "0123456789ab" in str(caught.value)
        +        assert "2024-01-01T00:00:00Z" in str(caught.value)
        +        assert caught.value.status_code == 403
        +    assert requests == [("GET", "/v1/server/info")]
        +
         
         @pytest.mark.parametrize("is_async", [False, True])
         @pytest.mark.asyncio
        @@ -5533,6 +7686,95 @@ def test_remote_add_columns_reader_not_supported():
                 assert all("/add_columns/" not in path for path in requests)
         
         
        +@pytest.mark.asyncio
        +async def test_remote_add_function_columns_forwards_auto_refresh_resource_budget():
        +    bodies = []
        +    application = FunctionApplication.from_json(
        +        json.dumps(
        +            {
        +                "function": {
        +                    "name": "embed",
        +                    "version": "1",
        +                    "object_id": "fixture",
        +                    "location": "memory:///fixture",
        +                    "manifest_digest": (
        +                        "sha256:7e22f815b6648e14f093a3979a8e5a2082"
        +                        "fa773ebe1ec84b135cae7e84d6f8e6"
        +                    ),
        +                },
        +                "inputs": [
        +                    {
        +                        "parameter": "text",
        +                        "kind": "column",
        +                        "value": {"path": "text"},
        +                    }
        +                ],
        +                "output": {
        +                    "kind": "scalar",
        +                    "arrow_type": "float32",
        +                    "nullable": False,
        +                },
        +            }
        +        )
        +    )
        +
        +    def handler(request):
        +        if request.path == "/v1/table/test/describe/":
        +            response = {
        +                "version": 1,
        +                "schema": {
        +                    "fields": [
        +                        {
        +                            "name": "text",
        +                            "type": {"type": "string"},
        +                            "nullable": True,
        +                        }
        +                    ]
        +                },
        +            }
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.end_headers()
        +            request.wfile.write(json.dumps(response).encode())
        +        elif request.path == "/v1/table/test/add_columns/":
        +            content_len = int(request.headers.get("Content-Length", 0))
        +            bodies.append(json.loads(request.rfile.read(content_len)))
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.end_headers()
        +            request.wfile.write(b'{"version": 2}')
        +        else:
        +            request.send_response(404)
        +            request.end_headers()
        +
        +    budget = {"total_cpu_millis": 2_000, "total_memory_bytes": 4 * 1024**3}
        +    with mock_lancedb_connection(handler) as db:
        +        table = db.open_table("test")
        +        table.add_columns(
        +            {"embedding": application},
        +            total_cpu_millis=(budget).get("total_cpu_millis"),
        +            total_memory_bytes=(budget).get("total_memory_bytes"),
        +            total_gpu_count=(budget).get("total_gpu_count"),
        +        )
        +
        +    async with mock_lancedb_connection_async(handler) as db:
        +        table = await db.open_table("test")
        +        await table.add_columns(
        +            {"embedding": application},
        +            total_cpu_millis=(budget).get("total_cpu_millis"),
        +            total_memory_bytes=(budget).get("total_memory_bytes"),
        +            total_gpu_count=(budget).get("total_gpu_count"),
        +        )
        +
        +    assert len(bodies) == 2
        +    for body in bodies:
        +        assert body["auto_refresh_enabled"] is True
        +        for key, value in budget.items():
        +            assert body[key] == value
        +        assert "total_gpu_count" not in body
        +        assert body["new_columns"] == [{"name": "embedding", "all_null": True}]
        +
        +
         @pytest.mark.asyncio
         async def test_async_property_graph_handles():
             calls = []
        @@ -5682,29 +7924,157 @@ def _create_table_handler(request):
         
         
         @contextlib.contextmanager
        -def _mock_remote_table_with_sql(flight_server):
        -    """A remote table backed by a mock REST server (for create/open) and the
        -    given mock Flight SQL server (for the SQL statements `optimize()` submits
        -    as jobs)."""
        +def _mock_remote_sql_connection(flight_server, handler=_create_table_handler):
        +    """Connection arguments for mock REST and Flight SQL servers."""
             with http.server.ThreadingHTTPServer(
        -        ("127.0.0.1", 0), make_mock_http_handler(_create_table_handler)
        +        ("127.0.0.1", 0), make_mock_http_handler(handler)
             ) as rest_server:
                 rest_port = rest_server.server_address[1]
                 handle = start_server_thread(rest_server)
                 try:
                     with flight_server:
        -                db = lancedb.connect(
        -                    "db://dev",
        -                    api_key="fake",
        -                    host_override=f"http://127.0.0.1:{rest_port}",
        -                    sql_host_override=f"grpc://127.0.0.1:{flight_server.port}",
        -                )
        -                yield db.create_table("test", [{"id": 1}])
        +                yield {
        +                    "uri": "db://dev",
        +                    "api_key": "fake",
        +                    "host_override": f"http://127.0.0.1:{rest_port}",
        +                    "sql_host_override": f"grpc://127.0.0.1:{flight_server.port}",
        +                }
                 finally:
                     rest_server.shutdown()
                     handle.join()
         
         
        +@contextlib.contextmanager
        +def _mock_remote_table_with_sql(flight_server):
        +    with _mock_remote_sql_connection(flight_server) as kwargs:
        +        yield lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
        +
        +
        +def test_remote_function_registration_transports_max_concurrency():
        +    flight = pytest.importorskip("pyarrow.flight")
        +    fixture = (
        +        Path(__file__).parents[3]
        +        / "rust"
        +        / "lancedb"
        +        / "tests"
        +        / "fixtures"
        +        / "first_class_functions"
        +        / "v1"
        +        / "remote_function_version.canonical.json"
        +    )
        +    definition = json.loads(fixture.read_text())
        +    definition["max_concurrency"] = 4
        +
        +    @function(name="normalize_score", max_concurrency=4)
        +    def registered(value: float) -> float:
        +        return value
        +
        +    definition["runtime_digest"] = registered.registration_request.runtime.digest
        +
        +    class RegistrationServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            return flight.RecordBatchStream(
        +                pa.table({"definition": [json.dumps(definition)]})
        +            )
        +
        +    server = RegistrationServer()
        +    with _mock_remote_sql_connection(server) as kwargs:
        +        version = lancedb.connect(**kwargs).create_function(registered)
        +
        +    assert len(server.tickets) == 1
        +    assert b'"max_concurrency":4' in server.tickets[0]
        +    assert version.max_concurrency == 4
        +    assert version.runtime_digest == registered.registration_request.runtime.digest
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "options,sql_options",
        +    [
        +        ({"target_rows_per_fragment": 100}, [b"target_rows_per_fragment = 100"]),
        +        (
        +            {"target_rows_per_fragment": 1_048_576},
        +            [b"target_rows_per_fragment = 1048576"],
        +        ),
        +        ({"max_source_rows": 500}, [b"max_source_rows = 500"]),
        +        ({"io_buffer_size": 0}, [b"io_buffer_size = 0"]),
        +        ({"batch_size": 16}, [b"batch_size = 16"]),
        +        (
        +            {
        +                "target_rows_per_fragment": 100,
        +                "max_source_rows": 500,
        +                "io_buffer_size": 65536,
        +                "batch_size": 16,
        +            },
        +            [
        +                b"target_rows_per_fragment = 100",
        +                b"max_source_rows = 500",
        +                b"io_buffer_size = 65536",
        +                b"batch_size = 16",
        +            ],
        +        ),
        +        ({}, []),
        +    ],
        +)
        +async def test_remote_optimize_forwards_per_job_compaction_options(
        +    asynchronous, options, sql_options
        +):
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class AckServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            return flight.RecordBatchStream(
        +                pa.table({"ok": pa.array([], type=pa.bool_())})
        +            )
        +
        +    server = AckServer()
        +    with _mock_remote_sql_connection(server) as kwargs:
        +        if asynchronous:
        +            db = await lancedb.connect_async(**kwargs)
        +            table = await db.create_table("test", [{"id": 1}])
        +            stats = await table.optimize(compaction_options=options)
        +        else:
        +            table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
        +            stats = table.optimize(compaction_options=options)
        +    assert len(server.tickets) == 1
        +    assert b"OPTIMIZE" in server.tickets[0]
        +    assert all(option in server.tickets[0] for option in sql_options)
        +    if not sql_options:
        +        assert b"WITH (" not in server.tickets[0]
        +    assert stats.prune.bytes_removed == 0
        +
        +
        +def test_remote_optimize_does_not_drop_options_after_server_rejection():
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class OldServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            raise flight.FlightServerError("Unknown OPTIMIZE option 'max_source_rows'")
        +
        +    server = OldServer()
        +    with _mock_remote_table_with_sql(server) as table:
        +        with pytest.raises(Exception, match="max_source_rows"):
        +            table.optimize(compaction_options={"max_source_rows": 500})
        +    assert server.tickets
        +    assert all(b"max_source_rows = 500" in ticket for ticket in server.tickets)
        +
        +
         def test_remote_optimize_skips_prune_and_index():
             """Regression test: a remote table's `optimize()` used to submit a
             compaction job and then raise `NotImplementedError` once it went on to
        @@ -5713,7 +8083,7 @@ def test_remote_optimize_skips_prune_and_index():
             zeroed pruning statistics, once compaction is submitted.
         
             The SQL job submission for a query without parameters (like
        -    `OPTIMIZE TABLE ... REWRITE DATA`) goes over plain Flight `do_get`, not
        +    `OPTIMIZE ... REWRITE DATA`) goes over plain Flight `do_get`, not
             `do_exchange`: the client sends a ticket wrapping the statement and reads
             back whatever the server returns as the job's result stream.
             """
        @@ -5735,12 +8105,12 @@ def test_remote_optimize_skips_prune_and_index():
                 stats = table.optimize()
         
             assert len(server.tickets) == 1
        -    assert b"OPTIMIZE TABLE" in server.tickets[0]
        +    assert b"OPTIMIZE" in server.tickets[0]
             assert stats.prune.bytes_removed == 0
             assert stats.prune.old_versions_removed == 0
         
         
        -def test_remote_optimize_rejects_non_default_compaction_options_before_submitting():
        +def test_remote_optimize_rejects_unsupported_compaction_options_before_submitting():
             """Regression test: `RemoteTable.optimize()` used to drop
             `compaction_options` instead of forwarding it to the Rust layer, so a
             non-default value was silently ignored -- the server-side guard against
        @@ -5762,7 +8132,7 @@ def test_remote_optimize_rejects_non_default_compaction_options_before_submittin
                     )
         
             server = UnreachableServer()
        -    options: CompactionOptions = {"target_rows_per_fragment": 5}
        +    options: CompactionOptions = {"max_source_bytes": 1024}
             with _mock_remote_table_with_sql(server) as table:
                 with pytest.raises(NotImplementedError, match="CompactionOptions"):
                     table.optimize(compaction_options=options)
        @@ -5799,3 +8169,1165 @@ def test_remote_optimize_rejects_explicit_pruning_before_submitting():
                     table.optimize(delete_unverified=True)
         
             assert server.tickets == []
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("framing", ["file", "stream"])
        +async def test_remote_blob_bytes_rejects_legacy_watermark(use_async, framing):
        +    requests = []
        +    with blob_remote_table(
        +        framing=framing,
        +        snapshot_supported=False,
        +        version_header="1",
        +        schema_version="1",
        +        requests=requests,
        +    ) as remote_table:
        +        table = remote_table._table if use_async else remote_table
        +        query = table.query() if use_async else table.search()
        +        descriptors = query.to_arrow(blob_mode="descriptions")
        +        if use_async:
        +            descriptors = await descriptors
        +        assert descriptors.num_rows == 3
        +        assert pa.types.is_struct(descriptors.schema.field("image").type)
        +        query = table.query() if use_async else table.search()
        +        with pytest.raises(NotImplementedError, match="x-lancedb-query-version"):
        +            result = query.to_arrow(blob_mode="bytes")
        +            if use_async:
        +                await result
        +    assert not any(path == "fetch_blobs" for path, _ in requests)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +@pytest.mark.parametrize("identity_header", [None, "", "v2:" + "a" * 64, "v1:broken"])
        +async def test_remote_blob_bytes_requires_trustworthy_identity(
        +    use_async, identity_header
        +):
        +    requests = []
        +    with blob_remote_table(
        +        identity_header=identity_header, schema_version="1", requests=requests
        +    ) as remote_table:
        +        table = remote_table._table if use_async else remote_table
        +        query = table.query() if use_async else table.search()
        +        # Ordinary descriptors still work, even with forged Arrow schema metadata.
        +        result = query.to_arrow(blob_mode="descriptions")
        +        if use_async:
        +            result = await result
        +        assert result.num_rows == 3
        +        with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"):
        +            result = query.to_arrow(blob_mode="bytes")
        +            if use_async:
        +                await result
        +    assert not any(path == "fetch_blobs" for path, _ in requests)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_remote_blob_bytes_rejects_unverified_serving_node(use_async):
        +    with blob_remote_table(verify_identity=False) as remote_table:
        +        table = remote_table._table if use_async else remote_table
        +        query = table.query() if use_async else table.search()
        +        with pytest.raises(
        +            NotImplementedError, match="did not verify the query snapshot identity"
        +        ):
        +            result = query.to_arrow(blob_mode="bytes")
        +            if use_async:
        +                await result
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("use_async", [False, True])
        +async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnations(
        +    use_async,
        +):
        +    requests = []
        +
        +    def identity(body):
        +        return "v1:" + ("b" if body.get("full_text_query") else "a") * 64
        +
        +    with blob_remote_table(
        +        search_scores=True, identity_header=identity, requests=requests
        +    ) as remote_table:
        +        if use_async:
        +            query = (
        +                remote_table._table.query()
        +                .nearest_to([1.0, 2.0])
        +                .nearest_to_text("hello")
        +            )
        +        else:
        +            query = (
        +                remote_table.search(query_type="hybrid", vector_column_name="vector")
        +                .vector([1.0, 2.0])
        +                .text("hello")
        +            )
        +        with pytest.raises(
        +            NotImplementedError, match="inconsistent x-lancedb-query-version"
        +        ):
        +            result = query.select(["id", "image"]).to_arrow(blob_mode="bytes")
        +            if use_async:
        +                await result
        +    assert not any(path == "fetch_blobs" for path, _ in requests)
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("is_async", [False, True])
        +@pytest.mark.parametrize("background", [False, True])
        +@pytest.mark.parametrize("kwargs", [{}, {"exist_ok": False}, {"exist_ok": True}])
        +async def test_remote_index_exist_ok_wire(is_async, background, kwargs):
        +    received = []
        +
        +    def handler(request):
        +        parsed = urlparse(request.path)
        +        body = request.rfile.read(int(request.headers.get("Content-Length", 0)))
        +        if parsed.path.endswith("/create_index/"):
        +            received.append((parse_qs(parsed.query), json.loads(body)))
        +            payload = {}
        +        elif parsed.path.endswith("/describe/"):
        +            payload = dict(
        +                version=1,
        +                schema=dict(
        +                    fields=[dict(name="id", type={"type": "int64"}, nullable=False)]
        +                ),
        +            )
        +        elif parsed.path.endswith("/create/"):
        +            payload = {}
        +        else:
        +            raise AssertionError(request.path)
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(payload).encode())
        +
        +    method = "create_index_async" if background else "create_index"
        +    if is_async:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            table = await db.create_table("test", [{"id": 1}])
        +            result = await getattr(table, method)("id", config=BTree(), **kwargs)
        +            if background:
        +                await result.wait()
        +    else:
        +        with mock_lancedb_connection(handler) as db:
        +            table = db.create_table("test", [{"id": 1}])
        +            result = getattr(table, method)("id", config=BTree(), **kwargs)
        +            if background:
        +                result.wait()
        +    query, body = received[0]
        +    assert query == ({"exist_ok": ["true"]} if kwargs.get("exist_ok") else {})
        +    assert "exist_ok" not in body
        +    if kwargs.get("exist_ok"):
        +        assert body["replace"] is False
        +    else:
        +        assert "replace" not in body
        +
        +
        +@pytest.mark.parametrize("operator", ["AND", "OR"])
        +def test_remote_fts_operator_and_count(operator):
        +    def handler(body):
        +        query = body["full_text_query"]["query"]["match"]
        +        assert query["terms"] == "gripper closed"
        +        assert query["operator"] == operator.title()
        +        assert query["column"] == "text"
        +        assert body["k"] == 2**63 - 1
        +        assert "offset" not in body
        +        assert body["columns"] == ["_score"]
        +        assert body["filter"] == "text IS NOT NULL"
        +        assert body["prefilter"] is False
        +        return pa.table({"_score": [1.0] * 25})
        +
        +    with query_test_table(
        +        handler, server_version=Version("0.6.0"), vector_columns={}
        +    ) as table:
        +        query = (
        +            table.search(
        +                "gripper closed",
        +                query_type="fts",
        +                fts_columns="text",
        +                operator=operator,
        +            )
        +            .where("text IS NOT NULL", prefilter=False)
        +            .select(["text"])
        +            .limit(1)
        +            .offset(3)
        +        )
        +        assert query.count_rows() == 25
        +        assert query.to_query_object().limit == 1
        +        assert query.to_query_object().offset == 3
        +
        +
        +def test_remote_fts_and_rejects_legacy_server():
        +    def handler(body):
        +        pytest.fail("AND must not silently become OR on a legacy server")
        +
        +    with query_test_table(handler, vector_columns={}) as table:
        +        with pytest.raises(NotImplementedError, match="server version 0.3.0"):
        +            table.search("gripper closed", query_type="fts", operator="AND").to_list()
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("async_table", [False, True])
        +async def test_function_failure_workflow_uses_exact_retry_and_upgrade_apis(async_table):
        +    received = []
        +    result = {
        +        "rows_assigned": 1000,
        +        "rows_failed": 100,
        +        "rows_remaining": 0,
        +        "source_version": 7,
        +        "published_version": 8,
        +        "error_groups": [
        +            {
        +                "column": "derived",
        +                "error_type": "RowTimeoutError",
        +                "error_message": "timeout",
        +                "rows_failed": 100,
        +            }
        +        ],
        +        "error_groups_truncated": False,
        +    }
        +
        +    def handler(request):
        +        length = int(request.headers.get("Content-Length", 0))
        +        body = json.loads(request.rfile.read(length)) if length else {}
        +        received.append((request.path, body))
        +        status = 200
        +        if request.path == "/v1/table/test/describe/":
        +            response = {"version": 8, "schema": {"fields": []}}
        +        elif request.path == "/v1/table/test/backfill_column":
        +            status = 202
        +            response = {"job_id": "refresh-1"}
        +        elif request.path == "/v1/jobs/describe":
        +            response = {
        +                "job_id": "refresh-1",
        +                "job_type": "function_refresh",
        +                "job_state": "DONE",
        +                "result": result,
        +            }
        +        elif request.path == "/v1/table/test/errors/quarantine":
        +            response = {"rows_affected": 100}
        +        elif request.path == "/v1/table/test/function_provenance":
        +            response = {
        +                "records": [
        +                    {
        +                        "column": "derived",
        +                        "job_id": "refresh-1",
        +                        "function_name": "check",
        +                        "function_version": "2",
        +                        "row_id": 42,
        +                        "source_version": 7,
        +                        "published_version": 8,
        +                    }
        +                ],
        +                "truncated": False,
        +            }
        +        elif request.path == "/v1/table/test/errors":
        +            response = {
        +                "records": [],
        +                "fragments": [],
        +                "truncated": False,
        +                "workflow_version": 1,
        +            }
        +        else:
        +            status = 404
        +            response = {}
        +        request.send_response(status)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(response).encode())
        +
        +    retry_options = dict(
        +        error_type="ValueError",
        +        job_id="first",
        +        include_quarantined=True,
        +        function_version="2",
        +        max_failed_fraction=1.0,
        +    )
        +    if async_table:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            table = await db.open_table("test")
        +            job = await table.retry_failed("derived", **retry_options)
        +            terminal = await job.wait()
        +            await table.upgrade_column("derived", version="3", recompute="none")
        +            affected = await table.quarantine_failed("derived", after_attempts=3)
        +            provenance = await table.function_provenance("derived")
        +            errors = await table.function_errors(column="derived", history=True)
        +    else:
        +        with mock_lancedb_connection(handler) as db:
        +            table = db.open_table("test")
        +            terminal = table.retry_failed("derived", **retry_options).wait()
        +            table.upgrade_column("derived", version="3", recompute="none")
        +            affected = table.quarantine_failed("derived", after_attempts=3)
        +            provenance = table.function_provenance("derived")
        +            errors = table.function_errors(column="derived", history=True)
        +
        +    refreshes = [body for path, body in received if path.endswith("backfill_column")]
        +    assert refreshes == [
        +        {
        +            "column": "derived",
        +            "retry_errors": True,
        +            "retry_job_id": "first",
        +            "retry_error_type": "ValueError",
        +            "include_quarantined": True,
        +            "function_version": "2",
        +            "recompute": "failed",
        +            "max_failed_fraction": 1.0,
        +        },
        +        {"column": "derived", "function_version": "3", "recompute": "none"},
        +    ]
        +    assert terminal.rows_assigned == 1000
        +    assert terminal.error_groups[0].rows_failed == 100
        +    assert affected == 100
        +    assert provenance.records[0].function_version == "2"
        +    assert provenance.records[0].row_id == 42
        +    assert errors.summary() == []
        +    assert ("/v1/table/test/errors", {"column": "derived", "history": True}) in received
        +
        +
        +def test_function_error_rows_returns_all_inputs_and_preserves_multiple_column_errors(
        +    tmp_path,
        +):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("inputs", [{"id": index} for index in range(16)])
        +    inputs = table.search().select(["id", "_rowid", "_rowaddr"]).limit(16).to_arrow()
        +    records = [
        +        SimpleNamespace(
        +            column="first",
        +            row_id=row_id,
        +            row_address=999999,
        +            row_offset=0,
        +            input=None,
        +            error_type="ValueError",
        +            error_message="corrupt",
        +            attempts=3,
        +            function_version="1",
        +            job_id="first",
        +            first_seen_at_millis=100,
        +            last_seen_at_millis=200,
        +            quarantined=False,
        +        )
        +        for row_id in inputs.column("_rowid").to_pylist()
        +    ]
        +    duplicate = copy.copy(records[0])
        +    duplicate.column = "second"
        +    records.append(duplicate)
        +    errors = lancedb.FunctionErrors(
        +        SimpleNamespace(
        +            records=records, fragments=[], truncated=False, workflow_version=1
        +        ),
        +        table,
        +    )
        +    rows = errors.rows(columns=["id"])
        +    assert rows.num_rows == 17
        +    assert sorted(set(rows.column("id").to_pylist())) == list(range(16))
        +    assert rows.column("__function_error").type.field("column").name == "column"
        +    assert [group.rows_failed for group in errors.summary()] == [16, 1]
        +    legacy = copy.copy(records[0])
        +    legacy.row_id = None
        +    legacy.row_address = inputs.column("_rowaddr")[0].as_py()
        +    legacy_errors = lancedb.FunctionErrors(
        +        SimpleNamespace(
        +            records=[legacy], fragments=[], truncated=False, workflow_version=1
        +        ),
        +        table,
        +    )
        +    assert legacy_errors.rows(columns=["id"]).column("id").to_pylist() == [0]
        +
        +    incomplete = lancedb.FunctionErrors(
        +        SimpleNamespace(
        +            records=records, fragments=[], truncated=True, workflow_version=1
        +        ),
        +        table,
        +    )
        +    with pytest.raises(ValueError, match="incomplete"):
        +        incomplete.rows()
        +
        +
        +def test_exact_function_retries_fail_before_writing_to_older_servers():
        +    writes = []
        +
        +    def handler(request):
        +        length = int(request.headers.get("Content-Length", 0))
        +        body = request.rfile.read(length) if length else b""
        +        if request.path == "/v1/table/test/describe/":
        +            response = {"version": 1, "schema": {"fields": []}}
        +        elif request.path == "/v1/table/test/errors":
        +            response = {"records": [], "fragments": [], "truncated": False}
        +        else:
        +            writes.append((request.path, body))
        +            response = {}
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(response).encode())
        +
        +    with mock_lancedb_connection(handler) as db:
        +        table = db.open_table("test")
        +        with pytest.raises(NotImplementedError, match="server does not support"):
        +            table.retry_failed("derived")
        +        with pytest.raises(NotImplementedError, match="server does not support"):
        +            table.upgrade_column("derived", version="2", recompute="failed")
        +        with pytest.raises(NotImplementedError, match="server does not support"):
        +            table.function_errors(history=True)
        +        with pytest.raises(NotImplementedError, match="server does not support"):
        +            table.function_errors().summary()
        +    assert writes == []
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize("mode", ["job", "columns", "filtered", "defaults"])
        +async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mode):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    polls = []
        +
        +    class PrewarmServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            return flight.RecordBatchStream(
        +                pa.table(
        +                    {
        +                        "job_id": ["warming-job"],
        +                        "table_version": pa.array([42], pa.uint64()),
        +                    }
        +                )
        +            )
        +
        +    def handler(request):
        +        if request.path == "/v1/jobs/describe":
        +            body = json.loads(
        +                request.rfile.read(int(request.headers["Content-Length"]))
        +            )
        +            assert body == {"job_id": "warming-job"}
        +            polls.append(body)
        +            request.send_response(200)
        +            request.send_header("Content-Type", "application/json")
        +            request.end_headers()
        +            request.wfile.write(
        +                json.dumps(
        +                    {
        +                        "job_id": "warming-job",
        +                        "job_type": "prewarm_page_cache",
        +                        "job_state": "DONE",
        +                        "creation_ms": 1,
        +                        "spec": {"table_version": 42},
        +                        "result": {
        +                            "table_version": 42,
        +                            "executors_targeted": 2,
        +                            "executors_completed": 2,
        +                            "fragments_selected": 4,
        +                        },
        +                        "operation_progress": {
        +                            "phase": "reading",
        +                            "executors_completed": 2,
        +                            "fragments_selected": 4,
        +                        },
        +                    }
        +                ).encode()
        +            )
        +        else:
        +            # No operation-specific REST prewarm endpoint is accepted.
        +            _create_table_handler(request)
        +
        +    server = PrewarmServer()
        +    with _mock_remote_sql_connection(server, handler) as kwargs:
        +        if asynchronous:
        +            db = await lancedb.connect_async(**kwargs)
        +            table = await db.create_table("test", [{"id": 1}])
        +            if mode == "columns":
        +                assert await table.prewarm_data(["payload"]) is None
        +            elif mode == "filtered":
        +                assert (
        +                    await table.prewarm_data(
        +                        columns=["attrs.score"], filter="id >= 8", concurrency=4
        +                    )
        +                    is None
        +                )
        +            elif mode == "defaults":
        +                assert await table.prewarm_data() is None
        +            else:
        +                job = await table.prewarm_data_async(
        +                    ["attrs.score"], filter="id >= 8", concurrency=4
        +                )
        +                assert job.id() == "warming-job"
        +                assert not polls
        +                assert (await job.wait()).table_version == 42
        +                await job.refresh()
        +                assert job.spec()["table_version"] == 42
        +                reopened = await db.open_job(job.id())
        +                assert (await reopened.wait()).executors_completed == 2
        +                assert (await job.progress())["executors_completed"] == 2
        +                assert (await job.wait()).bytes_read is None
        +        else:
        +            db = lancedb.connect(**kwargs)
        +            table = db.create_table("test", [{"id": 1}])
        +            if mode == "columns":
        +                assert table.prewarm_data(["payload"]) is None
        +            elif mode == "filtered":
        +                assert (
        +                    table.prewarm_data(
        +                        columns=["attrs.score"], filter="id >= 8", concurrency=4
        +                    )
        +                    is None
        +                )
        +            elif mode == "defaults":
        +                assert table.prewarm_data() is None
        +            else:
        +                job = table.prewarm_data_async(
        +                    ["attrs.score"], filter="id >= 8", concurrency=4
        +                )
        +                assert job.id() == "warming-job"
        +                assert not polls
        +                assert job.wait().table_version == 42
        +                job.refresh()
        +                assert job.spec()["table_version"] == 42
        +                assert db.open_job(job.id()).wait().executors_completed == 2
        +                assert job.progress()["executors_completed"] == 2
        +                assert job.wait().bytes_read is None
        +    assert len(server.tickets) == 1
        +    assert b"PREWARM" in server.tickets[0]
        +    if mode != "job":
        +        assert not polls
        +    if mode == "columns":
        +        assert b'"payload"' in server.tickets[0]
        +    elif mode == "defaults":
        +        assert b"SELECT *" in server.tickets[0]
        +    else:
        +        assert b'"attrs"."score"' in server.tickets[0]
        +        assert b"concurrency = 4" in server.tickets[0]
        +        assert b"id >= 8" in server.tickets[0]
        +
        +
        +@pytest.mark.parametrize(
        +    "options",
        +    [
        +        {"filter": ""},
        +        {"filter": "id > 0; DROP TABLE test"},
        +        {"filter": "id > 0 LIMIT 1"},
        +        {"concurrency": 0},
        +        {"concurrency": -1},
        +        {"concurrency": 2**32},
        +        {"concurrency": True},
        +        {"concurrency": 1.5},
        +        {"parameters": [1]},
        +        {"filter": "id > $1", "parameters": pa.table({"1": [1, 2]})},
        +    ],
        +)
        +@pytest.mark.parametrize(
        +    "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"]
        +)
        +def test_remote_data_prewarm_validates_before_submission(options, method):
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class UnusedServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            raise AssertionError("invalid options must not submit SQL")
        +
        +    server = UnusedServer()
        +    with _mock_remote_table_with_sql(server) as table:
        +        with pytest.raises(ValueError):
        +            getattr(table, method)(**options)
        +    assert not server.tickets
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"]
        +)
        +@pytest.mark.parametrize("named", [False, True])
        +async def test_prewarm_bound_parameters_reach_flight(asynchronous, method, named):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    attack = "training' OR TRUE; DROP TABLE items; --"
        +
        +    class ParameterServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.calls = []
        +
        +        def do_exchange(self, context, descriptor, reader, writer):
        +            self.calls.append((descriptor.command, reader.read_all()))
        +            if method == "explain_prewarm_data":
        +                result = pa.table(
        +                    {
        +                        "plan_type": ["logical_plan"],
        +                        "plan": [
        +                            json.dumps(
        +                                {
        +                                    "format_version": 1,
        +                                    "table_version": 42,
        +                                    "plan": "metadata preview",
        +                                    "pruning": {
        +                                        "mode": "zonemap_ranges",
        +                                        "input_fragments": 3,
        +                                        "selected_fragments": 1,
        +                                        "pruned_fragments": 2,
        +                                        "selected_row_ranges": 2,
        +                                    },
        +                                }
        +                            )
        +                        ],
        +                    }
        +                )
        +            else:
        +                result = pa.table(
        +                    {
        +                        "job_id": ["bound-job"],
        +                        "table_version": pa.array([42], pa.uint64()),
        +                    }
        +                )
        +            writer.begin(result.schema)
        +            writer.write_table(result)
        +            writer.close()
        +
        +    server = ParameterServer()
        +    with _mock_remote_sql_connection(server, _create_table_handler) as kwargs:
        +        parameters = {"min": 8, "tag": attack} if named else [8, attack]
        +        predicate = "id >= $min AND tag = $tag" if named else "id >= $1 AND tag = $2"
        +        if asynchronous:
        +            db = await lancedb.connect_async(**kwargs)
        +            table = await db.create_table("test", [{"id": 1}])
        +            result = await getattr(table, method)(
        +                ["payload"], filter=predicate, parameters=parameters
        +            )
        +        else:
        +            db = lancedb.connect(**kwargs)
        +            table = db.create_table("test", [{"id": 1}])
        +            result = getattr(table, method)(
        +                ["payload"], filter=predicate, parameters=parameters
        +            )
        +        if method == "prewarm_data":
        +            assert result is None
        +        elif method == "explain_prewarm_data":
        +            assert result.table_version == 42
        +            assert result.pruning.selected_fragments == 1
        +        else:
        +            assert result.id() == "bound-job"
        +    ((command, received),) = server.calls
        +    assert b"PREWARM" in command and predicate.encode() in command
        +    if method == "explain_prewarm_data":
        +        assert b"EXPLAIN (FORMAT JSON) PREWARM" in command
        +    assert attack.encode() not in command
        +    assert received.column(0).to_pylist() == [8]
        +    assert received.column(1).to_pylist() == [attack]
        +
        +
        +def test_remote_data_prewarm_malformed_receipt_is_not_retried():
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class MalformedServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            return flight.RecordBatchStream(pa.table({"job_id": ["warming-job"]}))
        +
        +    server = MalformedServer()
        +    with _mock_remote_table_with_sql(server) as table:
        +        with pytest.raises(Exception, match="inspect jobs before retrying"):
        +            table.prewarm_data_async()
        +    assert len(server.tickets) == 1
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "outcome",
        +    [
        +        "counts",
        +        "legacy",
        +        "partial",
        +        "bounded",
        +        "no_op",
        +        "missing",
        +        "FAILED",
        +        "CANCELLED",
        +    ],
        +)
        +async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    polls = []
        +    result = {
        +        "partial_commit": False,
        +        "rows_succeeded": 12,
        +        "rows_failed": 0,
        +        "completion_percentage": 100.0,
        +    }
        +    if outcome == "counts":
        +        result.update(
        +            files_added=1, files_removed=3, fragments_added=1, fragments_removed=3
        +        )
        +
        +    if outcome == "partial":
        +        result.update(
        +            partial_commit=True,
        +            rows_succeeded=8,
        +            rows_failed=4,
        +            completion_percentage=100 * 8 / 12,
        +        )
        +    if outcome == "bounded":
        +        result.update(more_work=True)
        +    if outcome == "no_op":
        +        result.update(
        +            rows_succeeded=0,
        +            files_added=0,
        +            files_removed=0,
        +            fragments_added=0,
        +            fragments_removed=0,
        +        )
        +
        +    class Server(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            return flight.RecordBatchStream(pa.table({"job_id": ["compacting-job"]}))
        +
        +    def handler(request):
        +        if request.path != "/v1/jobs/describe":
        +            return _create_table_handler(request)
        +        body = json.loads(request.rfile.read(int(request.headers["Content-Length"])))
        +        assert body == {"job_id": "compacting-job"}
        +        polls.append(body)
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(
        +            json.dumps(
        +                {
        +                    "job_id": "compacting-job",
        +                    "job_type": "compact",
        +                    "job_state": outcome
        +                    if outcome in ("FAILED", "CANCELLED")
        +                    else "DONE",
        +                    "result": None if outcome == "missing" else result,
        +                }
        +            ).encode()
        +        )
        +
        +    server = Server()
        +    with _mock_remote_sql_connection(server, handler) as kwargs:
        +        if asynchronous:
        +            db = await lancedb.connect_async(**kwargs)
        +            table = await db.create_table("test", [{"id": 1}])
        +            job = await table.compact_async(
        +                compaction_options={"target_rows_per_fragment": 100}
        +            )
        +            assert job.id() == "compacting-job" and not polls
        +            if outcome in ("missing", "FAILED", "CANCELLED"):
        +                with pytest.raises(
        +                    Exception,
        +                    match={
        +                        "missing": "did not contain a result",
        +                        "FAILED": "failed",
        +                        "CANCELLED": "cancel",
        +                    }[outcome],
        +                ):
        +                    await job.wait()
        +            else:
        +                stats = await job.wait()
        +                reopened = await db.open_job(job.id())
        +                assert await reopened.wait() == stats
        +        else:
        +            db = lancedb.connect(**kwargs)
        +            table = db.create_table("test", [{"id": 1}])
        +            job = table.compact_async(
        +                compaction_options={"target_rows_per_fragment": 100}
        +            )
        +            assert job.id() == "compacting-job" and not polls
        +            if outcome in ("missing", "FAILED", "CANCELLED"):
        +                with pytest.raises(
        +                    Exception,
        +                    match={
        +                        "missing": "did not contain a result",
        +                        "FAILED": "failed",
        +                        "CANCELLED": "cancel",
        +                    }[outcome],
        +                ):
        +                    job.wait()
        +            else:
        +                stats = job.wait()
        +                assert db.open_job(job.id()).wait() == stats
        +        if outcome in ("counts", "legacy", "partial", "bounded", "no_op"):
        +            from lancedb.compaction import CompactionResult
        +
        +            assert isinstance(stats, CompactionResult)
        +            assert stats.rows_succeeded == (
        +                0 if outcome == "no_op" else 8 if outcome == "partial" else 12
        +            )
        +            assert stats.rows_failed == (4 if outcome == "partial" else 0)
        +            assert stats.partial_commit == (outcome == "partial")
        +            assert stats.more_work == (outcome == "bounded")
        +            assert stats.fragments_removed == (
        +                3 if outcome == "counts" else 0 if outcome == "no_op" else None
        +            )
        +    assert len(server.tickets) == 1
        +    assert b"OPTIMIZE" in server.tickets[0]
        +    assert b"target_rows_per_fragment = 100" in server.tickets[0]
        +
        +
        +@pytest.mark.parametrize("ids", [[], [None], [""], ["a", "b"]])
        +def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids):
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class Server(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.calls = 0
        +
        +        def do_get(self, context, ticket):
        +            self.calls += 1
        +            return flight.RecordBatchStream(
        +                pa.table({"job_id": pa.array(ids, pa.string())})
        +            )
        +
        +    server = Server()
        +    with _mock_remote_sql_connection(server) as kwargs:
        +        db = lancedb.connect(**kwargs)
        +        table = db.create_table("test", [{"id": 1}])
        +        with pytest.raises(Exception, match="inspect jobs before retrying"):
        +            table.compact_async()
        +    assert server.calls == 1
        +
        +
        +@pytest.mark.parametrize("method", ["compact_async", "optimize"])
        +@pytest.mark.parametrize(
        +    "option",
        +    ["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"],
        +)
        +@pytest.mark.parametrize("value", [False, True])
        +def test_remote_compaction_rejects_boolean_budgets_without_submitting(
        +    method, option, value
        +):
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class UnusedServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.calls = 0
        +
        +        def do_get(self, context, ticket):
        +            self.calls += 1
        +            raise AssertionError("boolean compaction settings must not submit SQL")
        +
        +    server = UnusedServer()
        +    with _mock_remote_table_with_sql(server) as table:
        +        with pytest.raises(ValueError, match="must be an integer, not a bool"):
        +            getattr(table, method)(compaction_options={option: value})
        +    assert server.calls == 0
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "mode,selected,ranges,reason",
        +    [
        +        ("unfiltered", 3, None, None),
        +        ("constant", 0, 0, None),
        +        ("zonemap_ranges", 1, 2, None),
        +        ("full_warm_fallback", 3, None, "no metadata proof"),
        +        ("future_mode", 2, None, None),
        +    ],
        +)
        +async def test_remote_data_prewarm_preview(
        +    asynchronous, mode, selected, ranges, reason
        +):
        +    from lancedb.prewarm import PrewarmDataPlan, PrewarmPruningSummary
        +
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class PreviewServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            payload = {
        +                "format_version": 1,
        +                "table_version": 42,
        +                "plan": "metadata preview",
        +                "pruning": {
        +                    "mode": mode,
        +                    "input_fragments": 3,
        +                    "selected_fragments": selected,
        +                    "pruned_fragments": 3 - selected,
        +                    "selected_row_ranges": ranges,
        +                    "fallback_reason": reason,
        +                },
        +            }
        +            return flight.RecordBatchStream(
        +                pa.table({"plan_type": ["logical_plan"], "plan": [json.dumps(payload)]})
        +            )
        +
        +    server = PreviewServer()
        +    with _mock_remote_sql_connection(server) as kwargs:
        +        if asynchronous:
        +            db = await lancedb.connect_async(**kwargs)
        +            table = await db.create_table("test", [{"id": 1}])
        +            plan = await table.explain_prewarm_data(
        +                ["attrs.score"], filter="id > 0", concurrency=4
        +            )
        +        else:
        +            db = lancedb.connect(**kwargs)
        +            table = db.create_table("test", [{"id": 1}])
        +            plan = table.explain_prewarm_data(
        +                ["attrs.score"], filter="id > 0", concurrency=4
        +            )
        +    assert isinstance(plan, PrewarmDataPlan)
        +    assert isinstance(plan.pruning, PrewarmPruningSummary)
        +    assert plan.table_version == 42
        +    assert plan.pruning.mode == mode
        +    assert plan.pruning.selected_fragments == selected
        +    assert plan.pruning.selected_row_ranges == ranges
        +    assert plan.pruning.fallback_reason == reason
        +    assert len(server.tickets) == 1
        +    assert b"EXPLAIN (FORMAT JSON) PREWARM" in server.tickets[0]
        +    assert b'"attrs"."score"' in server.tickets[0]
        +    assert b"concurrency = 4" in server.tickets[0]
        +    assert b"id > 0" in server.tickets[0]
        +
        +
        +@pytest.mark.parametrize(
        +    "payload",
        +    [
        +        "legacy display text",
        +        '{"format_version":2,"table_version":42,"plan":"future","pruning":{}}',
        +        '{"format_version":1,"table_version":42,"plan":"missing pruning"}',
        +    ],
        +)
        +def test_remote_prewarm_preview_rejects_incompatible_payload_without_retry(payload):
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class PreviewServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            return flight.RecordBatchStream(pa.table({"plan": [payload]}))
        +
        +    server = PreviewServer()
        +    with _mock_remote_table_with_sql(server) as table:
        +        with pytest.raises(Exception, match="valid structured preview"):
        +            table.explain_prewarm_data()
        +    assert len(server.tickets) == 1
        +
        +
        +def test_remote_prewarm_preview_reports_old_server_format_support():
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class OldServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.tickets = []
        +
        +        def do_get(self, context, ticket):
        +            self.tickets.append(ticket.ticket)
        +            raise flight.FlightInternalError(
        +                "Invalid explain format. Expected 'indent', 'tree', 'pgjson' "
        +                "or 'graphviz'. Got 'JSON'"
        +            )
        +
        +    server = OldServer()
        +    with _mock_remote_table_with_sql(server) as table:
        +        with pytest.raises(
        +            NotImplementedError, match=r"EXPLAIN \(FORMAT JSON\) PREWARM"
        +        ):
        +            table.explain_prewarm_data()
        +    assert len(server.tickets) == 1
        +
        +
        +@pytest.mark.parametrize("async_table", [False, True])
        +@pytest.mark.asyncio
        +async def test_paged_function_errors_retain_history_and_expose_continuation(
        +    async_table,
        +):
        +    received = []
        +
        +    def handler(request):
        +        length = int(request.headers.get("content-length", 0))
        +        body = json.loads(request.rfile.read(length)) if length else {}
        +        if request.path == "/v1/table/test/describe/":
        +            response = {"version": 8, "schema": {"fields": []}}
        +        else:
        +            assert request.path == "/v1/table/test/errors"
        +            received.append(body)
        +            response = {
        +                "records": [],
        +                "fragments": [],
        +                "truncated": False,
        +                "workflow_version": 1,
        +                "page_token": "next",
        +            }
        +        request.send_response(200)
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(response).encode())
        +
        +    if async_table:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            table = await db.open_table("test")
        +            errors = await table.function_errors(job_id="attempt-1", page_token="")
        +            assert errors.page_token == "next"
        +            with pytest.raises(ValueError, match="current failures"):
        +                await errors.rows()
        +    else:
        +        with mock_lancedb_connection(handler) as db:
        +            table = db.open_table("test")
        +            errors = table.function_errors(job_id="attempt-1", page_token="")
        +            assert errors.page_token == "next"
        +            with pytest.raises(ValueError, match="current failures"):
        +                errors.rows()
        +    assert received == [{"job_id": "attempt-1", "page_token": "", "history": True}]
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("sync_api", [False, True])
        +@pytest.mark.parametrize("kind", ["cpu", "memory", "gpu"])
        +@pytest.mark.parametrize("submitted_job", [False, True])
        +async def test_function_profile_capture_wait_and_retained_export(
        +    sync_api, kind, submitted_job, tmp_path
        +):
        +    state = {"polls": 0, "finished": False}
        +    paths = []
        +    profile = {
        +        "profile_id": "profile-1",
        +        "job_id": "job-1",
        +        "worker_id": "worker-1",
        +        "execution_epoch": 3,
        +        "session_slot": 2,
        +        "kind": kind,
        +        "duration_seconds": 2,
        +        "status": "pending",
        +        "requested_at_millis": 1000,
        +        "deadline_at_millis": 46000,
        +        "expires_at_millis": 3601000,
        +        "completed_at_millis": None,
        +        "error": None,
        +        "artifact_id": None,
        +    }
        +    artifacts = {
        +        "cpu": {
        +            "$schema": "https://www.speedscope.app/file-format-schema.json",
        +            "shared": {"frames": [{"name": "work"}]},
        +            "profiles": [],
        +        },
        +        "memory": {
        +            "format": "lancedb.tracemalloc.v1",
        +            "allocations": [{"size_bytes": 4096}],
        +            "truncated": False,
        +        },
        +        "gpu": {
        +            "format": "lancedb.cuda.v1",
        +            "traceEvents": [{"name": "compute", "ph": "X", "ts": 10, "dur": 2}],
        +            "truncated": True,
        +        },
        +    }
        +
        +    def handler(request):
        +        paths.append(request.path)
        +        assert request.headers["x-api-key"] == "fake"
        +        assert request.headers["x-lancedb-database"] == "dev"
        +        length = int(request.headers.get("Content-Length", 0))
        +        body = json.loads(request.rfile.read(length)) if length else {}
        +        if request.path == "/v1/table/test/describe/":
        +            result = {"version": 1, "schema": {"fields": []}}
        +        elif request.path == "/v1/table/test/backfill_column":
        +            assert body["column"] == "result"
        +            result = {"job_id": "job-1"}
        +        elif request.path == "/v1/jobs/describe":
        +            result = {
        +                "job_id": "job-1",
        +                "job_type": "function_refresh",
        +                "job_state": "DONE" if state["finished"] else "IN_PROGRESS",
        +            }
        +        elif request.path == "/v1/jobs/profile/capture":
        +            assert body == {
        +                "job_id": "job-1",
        +                "worker_id": "worker-1",
        +                "session_slot": 2,
        +                "kind": kind,
        +                "duration_seconds": 2.0,
        +            }
        +            result = profile
        +        elif request.path == "/v1/jobs/profile/status":
        +            assert body == {"job_id": "job-1", "profile_id": "profile-1"}
        +            state["polls"] += 1
        +            result = dict(
        +                profile,
        +                status="complete" if state["polls"] > 1 else "capturing",
        +                artifact_id="profile-1" if state["polls"] > 1 else None,
        +            )
        +        elif request.path == "/v1/jobs/profile/artifact":
        +            assert body == {"job_id": "job-1", "profile_id": "profile-1"}
        +            result = artifacts[kind]
        +        else:
        +            raise AssertionError(f"Unexpected request: {request.path}")
        +        request.send_response(
        +            200 if request.path != "/v1/jobs/profile/capture" else 202
        +        )
        +        request.send_header("Content-Type", "application/json")
        +        request.end_headers()
        +        request.wfile.write(json.dumps(result).encode())
        +
        +    async def exercise(db):
        +        async def invoke(function, *args, **kwargs):
        +            if sync_api:
        +                return await asyncio.to_thread(function, *args, **kwargs)
        +            return await function(*args, **kwargs)
        +
        +        if submitted_job:
        +            table = await invoke(db.open_table, "test")
        +            job = await invoke(table.refresh_column_async, "result")
        +            await invoke(job.refresh)
        +        else:
        +            job = await invoke(db.open_job, "job-1")
        +        capture = await invoke(
        +            job.capture_profile,
        +            "worker-1",
        +            kind=kind,
        +            duration=timedelta(seconds=2),
        +            session_slot=2,
        +        )
        +        assert capture.profile_id == "profile-1"
        +        assert capture.worker_id == "worker-1"
        +        assert capture.session_slot == 2
        +        assert capture.execution_epoch == 3
        +        assert capture.status == "pending"
        +        completed = await invoke(
        +            job.wait_for_profile,
        +            capture.profile_id,
        +            timeout=timedelta(seconds=2),
        +            poll_interval=timedelta(milliseconds=10),
        +        )
        +        assert completed.status == "complete"
        +        assert job.state() == "running"
        +        state["finished"] = True
        +        await invoke(job.refresh)
        +        assert job.state() == "finished"
        +        assert await invoke(job.profile_artifact, capture.profile_id) == artifacts[kind]
        +        path = tmp_path / "profile.json"
        +        await invoke(job.export_profile, capture.profile_id, path)
        +        assert json.loads(path.read_text()) == artifacts[kind]
        +        assert paths.count("/v1/jobs/describe") == 2
        +        assert not any(path.endswith("/cancel") for path in paths)
        +
        +    if sync_api:
        +        with mock_lancedb_connection(handler) as db:
        +            await exercise(db)
        +    else:
        +        async with mock_lancedb_connection_async(handler) as db:
        +            await exercise(db)
        diff --git a/python/python/tests/test_s3.py b/python/python/tests/test_s3.py
        index 70b423adb..348f0ea78 100644
        --- a/python/python/tests/test_s3.py
        +++ b/python/python/tests/test_s3.py
        @@ -11,6 +11,7 @@ import threading
         import pytest
         import pyarrow as pa
         import lancedb
        +from lancedb.permutation import Permutation, permutation_builder
         
         
         # These are all keys that are accepted by storage_options
        @@ -87,6 +88,36 @@ def test_s3_lifecycle(s3_bucket: str):
             asyncio.run(test())
         
         
        +@pytest.mark.s3_test
        +def test_s3_permutation_persist_direct_result_pickle(s3_bucket: str):
        +    import pickle
        +
        +    storage_options = copy.copy(CONFIG)
        +    uri = f"s3://{s3_bucket}/test_permutation_persist"
        +    db = lancedb.connect(uri, storage_options=storage_options)
        +    try:
        +        tbl = db.create_table("base", pa.table({"id": range(20)}))
        +        plan = (
        +            permutation_builder(tbl)
        +            .split_sequential(fixed=2, split_names=["train", "test"])
        +            .persist(db, "splits")
        +            .execute()
        +        )
        +        assert plan._storage_options == storage_options
        +
        +        restored_plan = pickle.loads(pickle.dumps(plan))
        +        assert restored_plan.count_rows() == 20
        +
        +        permutation = Permutation.from_tables(tbl, plan, split="train")
        +        restored = pickle.loads(pickle.dumps(permutation))
        +        assert restored.num_rows == 10
        +        assert sorted(
        +            row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
        +        ) == list(range(10))
        +    finally:
        +        db.drop_all_tables()
        +
        +
         @pytest.mark.s3_test
         def test_concurrent_open_table(s3_bucket: str):
             uri = f"s3://{s3_bucket}/test_concurrent_open_table"
        diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py
        index 0ed382d93..fc6f94ad0 100644
        --- a/python/python/tests/test_sql.py
        +++ b/python/python/tests/test_sql.py
        @@ -2,6 +2,7 @@
         # SPDX-FileCopyrightText: Copyright The LanceDB Authors
         
         import threading
        +from datetime import timedelta
         from uuid import UUID
         
         import numpy as np
        @@ -13,6 +14,7 @@ from lancedb import _lancedb
         from lancedb.arrow import AsyncRecordBatchReader
         from lancedb.db import AsyncConnection
         from lancedb.remote.db import RemoteDBConnection
        +from lancedb.namespace import AsyncLanceNamespaceDBConnection
         from lancedb.sql import AsyncQuery, Query, to_parameter_batch
         
         NIL_QUERY_ID = UUID(int=0)
        @@ -20,25 +22,48 @@ NIL_QUERY_ID = UUID(int=0)
         
         class FakeNativeQuery:
             id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef")
        +    job_id = None
        +
        +    def __init__(self):
        +        self.cancelled = False
         
             async def reader(self):
                 return pa.table({"value": [1, 2]})
         
        +    async def cancel(self):
        +        self.cancelled = True
        +
         
         class FakeNativeConnection:
             def __init__(self):
                 self.parameters = []
        +        self.options = []
         
             async def execute_query_async(
        -        self, query, *, default_namespace_path=None, parameters=None
        +        self,
        +        query,
        +        *,
        +        default_namespace_path=None,
        +        parameters=None,
        +        timeout=None,
        +        read_timeout=None,
        +        cancel_on_drop=False,
             ):
                 self.parameters.append(parameters)
        +        self.options.append((timeout, read_timeout, cancel_on_drop))
                 return FakeNativeQuery()
         
         
         class FakeAsyncConnection:
             async def execute_query_async(
        -        self, query, *, default_namespace_path=None, parameters=None
        +        self,
        +        query,
        +        *,
        +        default_namespace_path=None,
        +        parameters=None,
        +        timeout=None,
        +        read_timeout=None,
        +        cancel_on_drop=False,
             ):
                 return AsyncQuery(FakeNativeQuery())
         
        @@ -68,6 +93,15 @@ def test_query_id_is_uuid():
             assert Query(query).id == query.id
         
         
        +def test_query_job_id_is_optional_and_separate_from_query_id():
        +    native = FakeNativeQuery()
        +    native.job_id = "j1-durable"
        +    query = AsyncQuery(native)
        +    assert query.id != query.job_id
        +    assert query.job_id == "j1-durable"
        +    assert Query(query).job_id == "j1-durable"
        +
        +
         def test_connection_serializes_sql_host_override():
             endpoint = "grpc+tls://sql.example.com:10026"
             restored = lancedb.deserialize_conn(
        @@ -283,6 +317,56 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent():
             assert echoed.column("k").to_pylist() == [10]
         
         
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    ("exist_ok", "status"),
        +    [
        +        (None, "created"),
        +        (False, "created"),
        +        (True, "created"),
        +        (True, "already_exists"),
        +    ],
        +)
        +async def test_create_secret_exist_ok_reaches_sql(asynchronous, exist_ok, status):
        +    flight = pytest.importorskip("pyarrow.flight")
        +
        +    class SecretServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.writes = []
        +
        +        def do_exchange(self, context, descriptor, reader, writer):
        +            self.writes.append((descriptor.command, reader.read_all()))
        +            result = pa.table({"status": [status]})
        +            writer.begin(result.schema)
        +            writer.write_table(result)
        +            writer.close()
        +
        +    with SecretServer() as server:
        +        options = {
        +            "api_key": "test-key",
        +            "host_override": "http://localhost:10024",
        +            "sql_host_override": f"grpc://127.0.0.1:{server.port}",
        +        }
        +        kwargs = {"namespace_path": ["team", "production"]}
        +        if exist_ok is not None:
        +            kwargs["exist_ok"] = exist_ok
        +        if asynchronous:
        +            db = await lancedb.connect_async("db://analytics", **options)
        +            await db.create_secret("api-key", "credential's value", **kwargs)
        +        else:
        +            db = lancedb.connect("db://analytics", **options)
        +            db.create_secret("api-key", "credential's value", **kwargs)
        +        ((command, parameters),) = server.writes
        +
        +    prefix = "CREATE SECRET IF NOT EXISTS" if exist_ok else "CREATE SECRET"
        +    sql = f'{prefix} "api-key" TYPE = GENERIC_STRING SECRET_STRING = $1'
        +    assert sql.encode() in command
        +    assert b"credential's value" not in command
        +    assert parameters.column(0).to_pylist() == ["credential's value"]
        +
        +
         @pytest.mark.parametrize("job_id", [None, "sql-job-1"])
         def test_sql_input_error_metadata_crosses_native_boundary(job_id):
             flight = pytest.importorskip("pyarrow.flight")
        @@ -341,3 +425,61 @@ def test_sql_input_error_metadata_crosses_native_boundary(job_id):
             assert error.grpc_code == 3
             assert str(error).startswith("No column 'missing' in table events")
             assert not str(error).startswith("SQL error")
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"])
        +async def test_async_sql_execution_controls_are_forwarded(method):
        +    native = FakeNativeConnection()
        +    connection = AsyncConnection(native)
        +    await getattr(connection, method)(
        +        "SELECT 1",
        +        timeout=timedelta(seconds=30),
        +        read_timeout=timedelta(seconds=5),
        +        cancel_on_drop=True,
        +    )
        +    assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)]
        +
        +
        +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"])
        +def test_sync_sql_execution_controls_are_forwarded(method):
        +    native = FakeNativeConnection()
        +    connection = RemoteDBConnection.__new__(RemoteDBConnection)
        +    connection._conn = AsyncConnection(native)
        +    getattr(connection, method)(
        +        "SELECT 1",
        +        timeout=timedelta(seconds=30),
        +        read_timeout=timedelta(seconds=5),
        +        cancel_on_drop=True,
        +    )
        +    assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)]
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_query_cancellation_reaches_the_native_handle():
        +    native = FakeNativeQuery()
        +    await AsyncQuery(native).cancel()
        +    assert native.cancelled
        +
        +
        +def test_sync_query_cancellation_reaches_the_native_handle():
        +    native = FakeNativeQuery()
        +    Query(AsyncQuery(native)).cancel()
        +    assert native.cancelled
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"])
        +async def test_namespace_sql_execution_controls_are_forwarded(method):
        +    native = FakeNativeConnection()
        +    connection = AsyncLanceNamespaceDBConnection.__new__(
        +        AsyncLanceNamespaceDBConnection
        +    )
        +    connection._inner = AsyncConnection(native)
        +    await getattr(connection, method)(
        +        "SELECT 1",
        +        timeout=timedelta(seconds=30),
        +        read_timeout=timedelta(seconds=5),
        +        cancel_on_drop=True,
        +    )
        +    assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)]
        diff --git a/python/python/tests/test_storage_integration.py b/python/python/tests/test_storage_integration.py
        index ff7995ab3..c96f36059 100644
        --- a/python/python/tests/test_storage_integration.py
        +++ b/python/python/tests/test_storage_integration.py
        @@ -3,6 +3,7 @@
         
         import contextlib
         import json
        +import re
         from pathlib import Path
         
         import pytest
        @@ -39,9 +40,37 @@ def remote_server(text_type=pa.string()):
                     command = ticket.ticket
                     calls.append(command)
                     if b"SHOW STORAGE INTEGRATIONS" in command:
        -                result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)})
        +                match = re.search(
        +                    rb'SHOW STORAGE INTEGRATIONS IN "public" '
        +                    rb"LIMIT (\d+)(?: FROM '([^']+)')?",
        +                    command,
        +                )
        +                assert match is not None, command
        +                limit = int(match.group(1))
        +                names = [NAME, "zeta"]
        +                if match.group(2) is not None:
        +                    assert match.group(2) == b"server-storage-page", command
        +                    names = names[1:]
        +                page = names[:limit]
        +                result = pa.table(
        +                    {
        +                        "namespace_path": pa.array(
        +                            ["[]"] * len(page), type=pa.string()
        +                        ),
        +                        "name": pa.array(page, type=text_type),
        +                    }
        +                )
        +                if len(names) > limit:
        +                    result = result.replace_schema_metadata(
        +                        {b"lancedb.next_page_token": b"server-storage-page"}
        +                    )
                     elif b"DROP STORAGE INTEGRATION" in command:
                         result = pa.table({"dropped": [True]})
        +            elif b"DESCRIBE STORAGE INTEGRATION" in command:
        +                assert b"FORMAT JSON" in command
        +                result = pa.table(
        +                    {"description": [json.dumps(info)]}
        +                ).replace_schema_metadata({b"lancedb.describe.format": b"json"})
                     else:
                         if b"STORAGE_PROVIDER = 'HUGGINGFACE'" in command:
                             info.update(
        @@ -94,14 +123,23 @@ def remote_server(text_type=pa.string()):
                                 trust_policy=None,
                                 permissions_policy=None,
                             )
        -                    for field, name in (
        -                        ("azure_tenant_id_secret", "tenant"),
        -                        ("azure_client_id_secret", "client"),
        -                        ("azure_client_secret_secret", "credential"),
        -                    ):
        -                        info[field] = dict(
        -                            database="shared", namespace_path=["credentials"], name=name
        +                    if b"STORAGE_AZURE_STORAGE_ACCOUNT_ACCESS_KEY_SECRET" in command:
        +                        info["azure_storage_account_access_key_secret"] = dict(
        +                            database="shared",
        +                            namespace_path=["credentials"],
        +                            name="blob_key",
                                 )
        +                    else:
        +                        for field, name in (
        +                            ("azure_tenant_id_secret", "tenant"),
        +                            ("azure_client_id_secret", "client"),
        +                            ("azure_client_secret_secret", "credential"),
        +                        ):
        +                            info[field] = dict(
        +                                database="shared",
        +                                namespace_path=["credentials"],
        +                                name=name,
        +                            )
                         if b"STORAGE_AWS_ACCESS_KEY_ID_SECRET" in command:
                             info["aws_role_arn"] = None
                             info["trust_policy"] = None
        @@ -125,6 +163,7 @@ def remote_server(text_type=pa.string()):
                             "azure_tenant_id_secret",
                             "azure_client_id_secret",
                             "azure_client_secret_secret",
        +                    "azure_storage_account_access_key_secret",
                             "gcp_credentials_json_secret",
                             "huggingface_token_secret",
                         ]:
        @@ -195,6 +234,10 @@ def test_sync_storage_integration_lifecycle_and_aws_information(text_type):
             assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0]
             assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0]
             assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1]
        +    listings = [call for call in calls if b"SHOW STORAGE INTEGRATIONS" in call]
        +    assert len(listings) == 2
        +    assert b'SHOW STORAGE INTEGRATIONS IN "public" LIMIT 1' in listings[0]
        +    assert b"FROM 'server-storage-page'" in listings[1]
         
         
         @pytest.mark.asyncio
        @@ -311,6 +354,44 @@ def test_azure_lifecycle_uses_three_qualified_secret_references(text_type):
                 assert b"STORAGE_AWS" not in sql
         
         
        +def test_azure_lifecycle_uses_one_qualified_account_access_key_secret():
        +    with remote_server() as (host, calls):
        +        db = connect(host)
        +        key = SecretReference(
        +            "blob_key", database="shared", namespace_path=("credentials",)
        +        )
        +        config = {
        +            "storage_provider": "AZURE",
        +            "azure_storage_account": "customeraccount",
        +            "azure_storage_account_access_key_secret": key,
        +        }
        +        with pytest.raises(ValueError, match="service principal"):
        +            db.create_storage_integration(
        +                "blobs",
        +                "az://customer-data/raw/",
        +                azure_client_id_secret="client",
        +                **config,
        +            )
        +        assert calls == []
        +
        +        info = db.create_storage_integration(
        +            "blobs", "az://customer-data/raw/", **config
        +        )
        +        reference = info.azure_storage_account_access_key_secret
        +        assert reference is not None
        +        assert reference.name == key.name
        +        assert reference.database == key.database
        +        assert tuple(reference.namespace_path) == key.namespace_path
        +        assert info.azure_tenant_id_secret is None
        +        assert info.azure_client_id_secret is None
        +        assert info.azure_client_secret_secret is None
        +        assert db.describe_storage_integration("blobs") == info
        +        assert (
        +            b"STORAGE_AZURE_STORAGE_ACCOUNT_ACCESS_KEY_SECRET = "
        +            b'"shared"."credentials"."blob_key"' in calls[0]
        +        )
        +
        +
         @pytest.mark.asyncio
         async def test_async_azure_requires_account_and_all_three_secret_references():
             with remote_server() as (host, calls):
        diff --git a/python/python/tests/test_storage_integration_creation.py b/python/python/tests/test_storage_integration_creation.py
        new file mode 100644
        index 000000000..13b94d741
        --- /dev/null
        +++ b/python/python/tests/test_storage_integration_creation.py
        @@ -0,0 +1,85 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import json
        +from pathlib import Path
        +
        +import pyarrow as pa
        +import pytest
        +
        +import lancedb
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    ("exist_ok", "existing"),
        +    [(None, False), (False, False), (True, False), (True, True)],
        +)
        +async def test_storage_integration_exist_ok_preserves_server_metadata(
        +    asynchronous, exist_ok, existing
        +):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    fixture = (
        +        Path(__file__).parents[3]
        +        / "rust/lancedb/tests/fixtures/storage_integration.json"
        +    )
        +    stored = json.loads(fixture.read_text())
        +    stored["namespace_path"] = ["team"]
        +    columns = {}
        +    for key, value in stored.items():
        +        if isinstance(value, (dict, list)):
        +            value = json.dumps(value)
        +        columns[key] = pa.array([None], type=pa.string()) if value is None else [value]
        +    result = pa.table(columns)
        +    prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"]
        +    role = (
        +        "arn:aws:iam::999999999999:role/replacement"
        +        if existing
        +        else stored["aws_role_arn"]
        +    )
        +
        +    class IntegrationServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.requests = []
        +
        +        def do_get(self, context, ticket):
        +            self.requests.append(ticket.ticket)
        +            return flight.RecordBatchStream(result)
        +
        +    with IntegrationServer() as server:
        +        connection_options = {
        +            "api_key": "test-key",
        +            "host_override": "http://localhost:10024",
        +            "sql_host_override": f"grpc://127.0.0.1:{server.port}",
        +        }
        +        kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
        +        kwargs.update(
        +            storage_provider="S3",
        +            storage_prefix=prefix,
        +            aws_role_arn=role,
        +            namespace_path=["team"],
        +        )
        +        uri = f"db://{stored['database']}"
        +        if asynchronous:
        +            db = await lancedb.connect_async(uri, **connection_options)
        +            info = await db.create_storage_integration(stored["name"], **kwargs)
        +        else:
        +            db = lancedb.connect(uri, **connection_options)
        +            info = db.create_storage_integration(stored["name"], **kwargs)
        +        (request,) = server.requests
        +
        +    command = (
        +        "CREATE STORAGE INTEGRATION IF NOT EXISTS"
        +        if exist_ok
        +        else "CREATE STORAGE INTEGRATION"
        +    )
        +    assert f'{command} "raw"'.encode() in request
        +    assert prefix.encode() in request
        +    assert role.encode() in request
        +    assert info.storage_prefix == stored["storage_prefix"]
        +    assert info.aws_role_arn == stored["aws_role_arn"]
        +    assert info.aws_external_id == stored["aws_external_id"]
        +    assert info.created_at_millis == stored["created_at_millis"]
        +    assert info.namespace_path == ["team"]
        diff --git a/python/python/tests/test_sync_api_parity.py b/python/python/tests/test_sync_api_parity.py
        index a12efd0c9..230fb45c6 100644
        --- a/python/python/tests/test_sync_api_parity.py
        +++ b/python/python/tests/test_sync_api_parity.py
        @@ -58,8 +58,8 @@ def test_legacy_table_replace_field_metadata(legacy_table):
             ]
         
         
        -def respond(request, body):
        -    request.send_response(200)
        +def respond(request, body, status=200):
        +    request.send_response(status)
             request.send_header("Content-Type", "application/json")
             request.end_headers()
             request.wfile.write(json.dumps(body).encode())
        @@ -78,12 +78,20 @@ def test_remote_unsupported_properties(attribute):
         
         
         @pytest.mark.parametrize("tables", [[], ["first", "last"]])
        -def test_remote_len_and_contains_follow_pages(tables):
        +def test_remote_len_paginates_and_contains_looks_up_table(tables):
             requests = []
         
             def handler(request):
                 requests.append(request.path)
        -        query = parse_qs(urlparse(request.path).query)
        +        url = urlparse(request.path)
        +        if request.command == "POST":
        +            name = url.path.split("/")[3]
        +            assert url.path == f"/v1/table/{name}/describe/"
        +            respond(request, {}, status=200 if name in tables else 404)
        +            return
        +        assert request.command == "GET"
        +        assert url.path == "/v1/namespace/$/table/list"
        +        query = parse_qs(url.query)
                 if tables and "page_token" not in query:
                     respond(request, {"tables": [tables[0]], "page_token": "opaque-next"})
                 else:
        @@ -93,11 +101,12 @@ def test_remote_len_and_contains_follow_pages(tables):
         
             with mock_lancedb_connection(handler) as db:
                 assert len(db) == len(tables)
        -        assert ("last" in db) == bool(tables)
        -        assert "missing" not in db
        +        assert len(requests) == (2 if tables else 1)
                 requests.clear()
        -        assert ("first" in db) == bool(tables)
        -        assert len(requests) == 1
        +        for name in ("last", "missing", "first"):
        +            assert (name in db) is (name in tables)
        +            assert requests == [f"/v1/table/{name}/describe/"]
        +            requests.clear()
         
         
         @pytest.mark.parametrize("namespace", [[], ["parent", "child"]])
        diff --git a/python/python/tests/test_sync_pull_reader.py b/python/python/tests/test_sync_pull_reader.py
        new file mode 100644
        index 000000000..3994b11d2
        --- /dev/null
        +++ b/python/python/tests/test_sync_pull_reader.py
        @@ -0,0 +1,195 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import gc
        +import time
        +from datetime import timedelta
        +
        +import pyarrow as pa
        +import pytest
        +
        +import lancedb
        +import lancedb.table as table_module
        +from lancedb.query import AsyncQuery
        +
        +
        +def _table(db, name="sync_pull_reader"):
        +    return db.create_table(
        +        name,
        +        data=[{"id": i, "vector": [float(i), float(i)]} for i in range(10)],
        +    )
        +
        +
        +def _spy_on_pull_reader(monkeypatch):
        +    calls = []
        +    real = AsyncQuery._execute_batches_sync
        +
        +    def spy(self, *, max_batch_length=None, timeout=None):
        +        calls.append((max_batch_length, timeout))
        +        return real(self, max_batch_length=max_batch_length, timeout=timeout)
        +
        +    monkeypatch.setattr(AsyncQuery, "_execute_batches_sync", spy)
        +    return calls
        +
        +
        +@pytest.mark.parametrize(
        +    "batch_size,row_limit",
        +    [
        +        (None, 1024),
        +        (0, None),
        +        (4, 4),
        +    ],
        +)
        +def test_plain_sync_batches_use_pull_reader(mem_db, monkeypatch, batch_size, row_limit):
        +    table = _table(mem_db)
        +    calls = _spy_on_pull_reader(monkeypatch)
        +
        +    reader = table.search().select(["id"]).to_batches(batch_size=batch_size)
        +
        +    assert isinstance(reader, pa.RecordBatchReader)
        +    assert calls == [(batch_size, None)]
        +    batches = list(reader)
        +    assert sum(batch.num_rows for batch in batches) == 10
        +    assert pa.Table.from_batches(batches).column("id").to_pylist() == list(range(10))
        +    if row_limit is not None:
        +        assert all(batch.num_rows <= row_limit for batch in batches)
        +
        +
        +def test_scan_in_order_routes_through_pull_reader(tmp_db, monkeypatch):
        +    table = tmp_db.create_table("ordered_pull_reader", pa.table({"id": [0, 1]}))
        +    table.add(pa.table({"id": [2, 3]}))
        +    table.add(pa.table({"id": [4, 5]}))
        +    table.checkout(table.version)
        +    calls = _spy_on_pull_reader(monkeypatch)
        +
        +    reader = table.search().scan_in_order(True).select(["id"]).to_batches(batch_size=2)
        +
        +    assert calls == [(2, None)]
        +    assert [value for batch in reader for value in batch["id"].to_pylist()] == [
        +        0,
        +        1,
        +        2,
        +        3,
        +        4,
        +        5,
        +    ]
        +    with pytest.raises(ValueError, match="nonempty order_by"):
        +        table.search().scan_in_order(True).order_by("id").to_batches()
        +
        +
        +def test_plain_sync_batches_do_not_enter_background_loop(mem_db, monkeypatch):
        +    table = _table(mem_db)
        +
        +    def fail(*args, **kwargs):
        +        raise AssertionError("plain sync batches entered the background event loop")
        +
        +    monkeypatch.setattr(table_module.LOOP, "run", fail)
        +
        +    reader = table.search().select(["id"]).to_batches(batch_size=4)
        +
        +    assert sum(batch.num_rows for batch in reader) == 10
        +
        +
        +@pytest.mark.parametrize(
        +    "execute",
        +    [
        +        lambda table: table.search().select(["id"]).to_arrow(),
        +        lambda table: table.search([0.0, 0.0]).to_batches(),
        +        lambda table: table.take_offsets([0]).to_batches(),
        +        lambda table: table.search().select(["id"]).order_by(["id"]).to_batches(),
        +        lambda table: (
        +            table.search().select(["id"]).to_batches(blob_mode="descriptions")
        +        ),
        +    ],
        +)
        +def test_other_sync_routes_keep_the_existing_reader(mem_db, monkeypatch, execute):
        +    table = _table(mem_db)
        +    calls = _spy_on_pull_reader(monkeypatch)
        +
        +    execute(table)
        +
        +    assert calls == []
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_batches_keep_the_existing_reader(monkeypatch):
        +    db = await lancedb.connect_async("memory://")
        +    table = await db.create_table(
        +        "async_sync_pull_reader", data=[{"id": i} for i in range(4)]
        +    )
        +    calls = _spy_on_pull_reader(monkeypatch)
        +
        +    reader = await table.query().to_batches()
        +
        +    total_rows = 0
        +    async for batch in reader:
        +        total_rows += batch.num_rows
        +    assert total_rows == 4
        +    assert calls == []
        +
        +
        +def test_timeout_starts_on_first_read_and_spans_reads(tmp_path):
        +    table = lancedb.connect(tmp_path).create_table(
        +        "timeout_pull_reader", data=[{"id": i} for i in range(8)]
        +    )
        +    reader = (
        +        table.search()
        +        .select(["id"])
        +        .to_batches(batch_size=2, timeout=timedelta(milliseconds=200))
        +    )
        +
        +    # A slow consumer before the first poll must not count against the query:
        +    # the timeout starts when the first batch is requested.
        +    time.sleep(0.25)
        +    first = reader.read_next_batch()
        +    assert first.num_rows == 2
        +
        +    # The deadline spans reads, so a pause between batches expires it.
        +    time.sleep(0.25)
        +    with pytest.raises(RuntimeError, match="Query timeout"):
        +        reader.read_next_batch()
        +
        +
        +def test_early_break_can_resume_the_same_reader(mem_db):
        +    table = _table(mem_db)
        +    reader = table.search().select(["id"]).to_batches(batch_size=2)
        +
        +    first = next(iter(reader))
        +    rest = list(reader)
        +
        +    assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list(
        +        range(10)
        +    )
        +
        +    reader = table.search().select(["id"]).to_batches(batch_size=2)
        +    for first in reader:
        +        break
        +    rest = list(reader)
        +    assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list(
        +        range(10)
        +    )
        +
        +
        +def test_arrow_export_shares_cursor_with_the_last_owner(mem_db):
        +    table = _table(mem_db)
        +    reader = table.search().select(["id"]).to_batches(batch_size=2)
        +    first = reader.read_next_batch()
        +
        +    capsule = reader.__arrow_c_stream__()
        +    del reader
        +    gc.collect()
        +
        +    imported = pa.RecordBatchReader._import_from_c_capsule(capsule)
        +    rest = imported.read_all()
        +    combined = pa.concat_tables([pa.Table.from_batches([first]), rest])
        +    assert combined.column("id").to_pylist() == list(range(10))
        +
        +
        +def test_empty_result_preserves_the_query_schema(mem_db):
        +    table = _table(mem_db)
        +    query = table.search().select(["id"]).where("id < 0")
        +
        +    reader = query.to_batches(batch_size=4)
        +
        +    assert reader.schema == query.output_schema()
        +    assert reader.read_all().num_rows == 0
        diff --git a/python/python/tests/test_sync_query_direct.py b/python/python/tests/test_sync_query_direct.py
        new file mode 100644
        index 000000000..9863f66c4
        --- /dev/null
        +++ b/python/python/tests/test_sync_query_direct.py
        @@ -0,0 +1,160 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import signal
        +import os
        +import subprocess
        +import sys
        +import threading
        +from datetime import timedelta
        +
        +import pyarrow as pa
        +import pytest
        +
        +import lancedb
        +from lancedb import background_loop
        +from lancedb.index import BTree, FTS, IvfFlat
        +
        +
        +def _direct_query_table(tmp_path):
        +    table = lancedb.connect(tmp_path).create_table(
        +        "direct",
        +        pa.table(
        +            {
        +                "id": pa.array([1, 2, 3, 4], pa.int64()),
        +                "text": ["alpha beta", "alpha gamma", "beta gamma", "delta epsilon"],
        +                "vector": pa.array(
        +                    [
        +                        [1.0, 0.0, 0.0, 0.0],
        +                        [0.0, 1.0, 0.0, 0.0],
        +                        [0.0, 0.0, 1.0, 0.0],
        +                        [0.0, 0.0, 0.0, 1.0],
        +                    ],
        +                    pa.list_(pa.float32(), 4),
        +                ),
        +            }
        +        ),
        +    )
        +    table.create_index("id", config=BTree())
        +    table.create_index("vector", config=IvfFlat(distance_type="l2", num_partitions=1))
        +    table.create_index("text", config=FTS(with_position=True))
        +    return table
        +
        +
        +def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch):
        +    table = _direct_query_table(tmp_path)
        +    expected_empty_schema = table.search().where("id < 0").output_schema()
        +
        +    def fail(*_args, **_kwargs):
        +        raise AssertionError("LOOP.run must not be used by direct sync queries")
        +
        +    monkeypatch.setattr(background_loop.LOOP, "run", fail)
        +
        +    point = table.search().where("id = 1").select(["id", "text"]).to_arrow()
        +    assert point.to_pylist() == [{"id": 1, "text": "alpha beta"}]
        +
        +    with_row_id = (
        +        table.search().where("id = 1").select(["id"]).with_row_id(True).to_arrow()
        +    )
        +    assert with_row_id["_rowid"].to_pylist() == [0]
        +
        +    # The vector column is inferred from the sync schema binding.
        +    vector = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow()
        +    assert vector["id"].to_pylist() == [1, 2]
        +    assert "_distance" in vector.column_names
        +
        +    fts = table.search("alpha", query_type="fts").select(["id"]).to_arrow()
        +    assert sorted(fts["id"].to_pylist()) == [1, 2]
        +    assert "_score" in fts.column_names
        +
        +    phrase = table.search('"alpha beta"', query_type="fts").select(["id"]).to_arrow()
        +    assert phrase["id"].to_pylist() == [1]
        +
        +    empty = table.search().where("id < 0").to_arrow()
        +    assert empty.num_rows == 0
        +    assert empty.schema == expected_empty_schema
        +
        +    with pytest.raises(Exception, match="Query timeout"):
        +        table.search([1.0, 0.0, 0.0, 0.0]).to_arrow(timeout=timedelta(0))
        +
        +
        +@pytest.mark.skipif(sys.platform != "linux", reason="needs sched_setaffinity")
        +def test_direct_sync_query_from_single_worker_progress_callback(tmp_path):
        +    script = r"""
        +import os
        +import sys
        +
        +try:
        +    cpus = sorted(os.sched_getaffinity(0))
        +    if not cpus:
        +        print("SKIP")
        +        sys.exit(0)
        +    os.sched_setaffinity(0, {cpus[0]})
        +except OSError:
        +    print("SKIP")
        +    sys.exit(0)
        +
        +import lancedb
        +
        +db = lancedb.connect("memory:///")
        +target = db.create_table(
        +    "target",
        +    [{"id": 1, "value": "one"}, {"id": 2, "value": "two"}],
        +)
        +source = db.create_table("source", [{"id": 1}])
        +seen = []
        +
        +def progress(_update):
        +    if not seen:
        +        seen.append(
        +            target.search()
        +            .where("id = 1")
        +            .select(["value"])
        +            .to_arrow()
        +            .to_pylist()
        +        )
        +
        +source.add([{"id": 2}], progress=progress)
        +assert seen == [[{"value": "one"}]], seen
        +print("OK")
        +"""
        +    result = subprocess.run(
        +        [sys.executable, "-c", script],
        +        cwd=tmp_path,
        +        capture_output=True,
        +        text=True,
        +        timeout=30,
        +    )
        +    if "SKIP" in result.stdout:
        +        pytest.skip("sched_setaffinity did not leave a usable CPU")
        +    assert result.returncode == 0, result.stdout + result.stderr
        +    assert "OK" in result.stdout
        +
        +
        +@pytest.mark.slow
        +def test_direct_sync_query_sigint_aborts_and_reuses_runtime(tmp_path):
        +    rows = 500_000
        +    table = lancedb.connect(tmp_path).create_table(
        +        "sigint",
        +        pa.table(
        +            {
        +                "id": pa.array(range(rows), pa.int64()),
        +                "text": pa.array([f"row-{row}" for row in range(rows)]),
        +            }
        +        ),
        +    )
        +    # Warm the runtime and page cache so the timed call is long enough to observe.
        +    table.search().select(["id"]).to_arrow()
        +
        +    timer = threading.Timer(0.001, os.kill, args=(os.getpid(), signal.SIGINT))
        +    timer.start()
        +    try:
        +        with pytest.raises(KeyboardInterrupt):
        +            table.search().select(["id", "text"]).to_arrow()
        +    finally:
        +        timer.cancel()
        +        timer.join()
        +
        +    # The shared runtime and its generation counter remain usable.
        +    after = table.search().where("id = 1").select(["id", "text"]).to_arrow()
        +    assert after.to_pylist() == [{"id": 1, "text": "row-1"}]
        diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py
        index 88635c020..7ec1e8dd6 100644
        --- a/python/python/tests/test_table.py
        +++ b/python/python/tests/test_table.py
        @@ -6,6 +6,7 @@ import ctypes
         import gc
         import json
         import os
        +import pickle
         import sys
         import threading
         import warnings
        @@ -1228,6 +1229,128 @@ def test_list_versions_timestamp_precision_remote():
             assert versions[0]["timestamp"].microsecond == 274000
         
         
        +def test_lance_table_is_picklable(tmp_db: DBConnection):
        +    table = tmp_db.create_table("pickle_table", pa.table({"id": [1, 2, 3]}))
        +    payload = pickle.dumps(table)
        +
        +    # A standard-mode handle must reopen at latest, not freeze the version that
        +    # happened to be current when pickle.dumps ran.
        +    tmp_db.open_table("pickle_table").add(pa.table({"id": [4]}))
        +
        +    restored = pickle.loads(payload)
        +    assert restored.name == "pickle_table"
        +    assert restored.count_rows() == 4
        +    assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3, 4]
        +
        +
        +def test_lance_table_pickle_preserves_checkout(tmp_db: DBConnection):
        +    table = tmp_db.create_table("pickle_checkout", pa.table({"id": [1]}))
        +    table.add(pa.table({"id": [2]}))
        +    table.checkout(1)
        +    payload = pickle.dumps(table)
        +
        +    tmp_db.open_table("pickle_checkout").add(pa.table({"id": [3]}))
        +
        +    restored = pickle.loads(payload)
        +    assert restored.version == 1
        +    assert restored.to_arrow()["id"].to_pylist() == [1]
        +
        +    restored.checkout_latest()
        +    assert restored.version == 3
        +    assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3]
        +
        +
        +def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    main = db.create_table("pickle_tag_branch", pa.table({"id": [0]}))
        +    branch = main.branches.create("exp")
        +    branch.add(pa.table({"id": [1]}))
        +    branch.tags.create("exp_tag", branch.version)
        +
        +    # Advance main independently, then resolve a tag that points into exp.
        +    main.add(pa.table({"id": [9]}))
        +    main.checkout("exp_tag")
        +    assert main.current_branch() == "exp"
        +    assert main.version == 2
        +    assert main.to_arrow()["id"].to_pylist() == [0, 1]
        +
        +    restored = pickle.loads(pickle.dumps(main))
        +    assert restored.current_branch() == "exp"
        +    assert restored.version == 2
        +    assert restored.to_arrow()["id"].to_pylist() == [0, 1]
        +
        +
        +def test_lance_table_pickle_preserves_branch_and_version(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    main = db.create_table("pickle_branch", pa.table({"id": [0]}))
        +    branch = main.branches.create("exp")
        +    branch.add(pa.table({"id": [1]}))
        +    branch_version = branch.version
        +
        +    branch_payload = pickle.dumps(branch)
        +    pinned = db.open_table("pickle_branch", branch="exp", version=branch_version)
        +    pinned_payload = pickle.dumps(pinned)
        +
        +    db.open_table("pickle_branch", branch="exp").add(pa.table({"id": [2]}))
        +
        +    restored_branch = pickle.loads(branch_payload)
        +    assert restored_branch.current_branch() == "exp"
        +    assert restored_branch.to_arrow()["id"].to_pylist() == [0, 1, 2]
        +
        +    restored_pinned = pickle.loads(pinned_payload)
        +    assert restored_pinned.current_branch() == "exp"
        +    assert restored_pinned.version == branch_version
        +    assert restored_pinned.to_arrow()["id"].to_pylist() == [0, 1]
        +    assert main.count_rows() == 1
        +
        +
        +def test_lance_table_pickle_memory_uses_arrow_snapshot(mem_db: DBConnection):
        +    table = mem_db.create_table("pickle_memory", pa.table({"id": [1, 2]}))
        +    payload = pickle.dumps(table)
        +
        +    table.add(pa.table({"id": [3]}))
        +
        +    restored = pickle.loads(payload)
        +    assert restored.name == "pickle_memory"
        +    assert restored.to_arrow()["id"].to_pylist() == [1, 2]
        +
        +
        +def test_memory_connection_pickle_requires_a_table_snapshot(mem_db: DBConnection):
        +    with pytest.raises(TypeError, match="in-memory LanceDBConnection"):
        +        pickle.dumps(mem_db)
        +
        +
        +def test_pickle_rejects_session_backed_connection(tmp_path):
        +    db = lancedb.connect(tmp_path, session=lancedb.Session())
        +    table = db.create_table("pickle_session", pa.table({"id": [1]}))
        +
        +    with pytest.raises(TypeError, match="Session"):
        +        pickle.dumps(db)
        +    with pytest.raises(TypeError, match="Session"):
        +        pickle.dumps(table)
        +
        +
        +def test_pickle_rejects_custom_namespace_client(tmp_db: DBConnection):
        +    table = tmp_db.create_table("pickle_custom_ns", pa.table({"id": [1]}))
        +    table._namespace_client = threading.Lock()
        +
        +    with pytest.raises(TypeError, match="namespace_client"):
        +        pickle.dumps(table)
        +
        +
        +def test_lance_table_pickle_preserves_namespace_path(tmp_path):
        +    pytest.importorskip("lance")
        +    db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
        +    db.create_namespace(["ns1"])
        +    table = db.create_table("pickle_ns", pa.table({"id": [1]}), namespace_path=["ns1"])
        +
        +    restored = pickle.loads(pickle.dumps(table))
        +
        +    assert restored.namespace == ["ns1"]
        +    assert restored.count_rows() == 1
        +    assert restored._conn._namespace_client_properties == {"root": str(tmp_path)}
        +
        +
         def test_versioning(mem_db: DBConnection):
             table = mem_db.create_table(
                 "test",
        @@ -1250,6 +1373,270 @@ def test_versioning(mem_db: DBConnection):
             assert len(table) == 2
         
         
        +def test_delta_streams_and_pins_endpoints(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table(
        +        "delta",
        +        data=[
        +            {"id": 1, "value": 0},
        +            {"id": 2, "value": 0},
        +        ],
        +        storage_options={"new_table_enable_stable_row_ids": "true"},
        +    )
        +
        +    table.add([{"id": 3, "value": 0}])
        +    table.tags.create("baseline", 2)
        +    table.update(where="id = 1", values_sql={"value": "value + 10"})
        +    table.delete("id = 2")
        +    assert table.version == 4
        +
        +    delta = table.delta(1)
        +    assert delta.begin_version == 1
        +    assert delta.end_version == 4
        +
        +    inserted = delta.inserted_rows().read_all()
        +    assert inserted["id"].to_pylist() == [3]
        +    assert inserted.schema.names == [
        +        "id",
        +        "value",
        +        "_rowid",
        +        "_row_created_at_version",
        +        "_row_last_updated_at_version",
        +    ]
        +
        +    updated = delta.updated_rows().read_all()
        +    assert updated["id"].to_pylist() == [1]
        +    assert updated["value"].to_pylist() == [10]
        +
        +    upserted = delta.upserted_rows().read_all()
        +    assert sorted(upserted["id"].to_pylist()) == [1, 3]
        +
        +    deleted = delta.deleted_row_ids().read_all()
        +    assert deleted.schema.names == ["_rowid"]
        +    assert deleted.schema.field("_rowid").type == pa.uint64()
        +    assert deleted.num_rows == 1
        +
        +    transactions = delta.list_transactions()
        +    assert [transaction["operation"] for transaction in transactions] == [
        +        "Append",
        +        "Update",
        +        "Delete",
        +    ]
        +    assert transactions[0]["read_version"] == 1
        +
        +    # Tags are resolved on the current branch and can be either endpoint.
        +    from_tag = table.delta("baseline")
        +    assert from_tag.begin_version == 2
        +    assert from_tag.end_version == 4
        +    assert from_tag.updated_rows().read_all()["id"].to_pylist() == [1]
        +
        +    to_tag = table.delta(1, "baseline")
        +    assert to_tag.end_version == 2
        +    assert to_tag.inserted_rows().read_all()["id"].to_pylist() == [3]
        +
        +    # Equal valid versions keep the reader schemas even when no rows change.
        +    equal = table.delta(2, 2)
        +    empty_inserted = equal.inserted_rows().read_all()
        +    assert empty_inserted.num_rows == 0
        +    assert empty_inserted.schema == inserted.schema
        +    empty_deleted = equal.deleted_row_ids().read_all()
        +    assert empty_deleted.num_rows == 0
        +    assert empty_deleted.schema.names == ["_rowid"]
        +
        +    # Reversed, zero, missing, and missing-tag endpoints are input errors.
        +    with pytest.raises(ValueError, match="newer than"):
        +        table.delta(4, 2)
        +    with pytest.raises(ValueError, match="start at 1"):
        +        table.delta(0)
        +    with pytest.raises(ValueError, match="does not exist"):
        +        table.delta(999)
        +    with pytest.raises(ValueError, match="does not exist"):
        +        table.delta("missing-tag")
        +
        +    # An omitted target follows the visible checkout and leaves the shared
        +    # checkout in place.
        +    table.checkout(2)
        +    checked_out = table.delta(1)
        +    assert checked_out.end_version == 2
        +    assert checked_out.inserted_rows().read_all()["id"].to_pylist() == [3]
        +    assert table.version == 2
        +
        +    # An explicit target works from a pinned handle without moving it.
        +    explicit = table.delta(1, 3)
        +    assert explicit.updated_rows().read_all()["id"].to_pylist() == [1]
        +    assert table.version == 2
        +    table.checkout_latest()
        +    assert table.version == 4
        +
        +
        +@pytest.mark.parametrize("mutation", ["update", "delete"])
        +def test_delta_rejects_restore_ranges(tmp_path, mutation):
        +    table = lancedb.connect(tmp_path).create_table(
        +        "restore_delta",
        +        [{"id": 1, "value": 0}],
        +        storage_options={"new_table_enable_stable_row_ids": "true"},
        +    )
        +    if mutation == "update":
        +        table.update(values={"value": 10})
        +    else:
        +        table.delete("id = 1")
        +    assert table.version == 2
        +
        +    table.restore(1)
        +    assert table.version == 3
        +    assert table.to_arrow().to_pylist() == [{"id": 1, "value": 0}]
        +
        +    restore_range = table.delta(2, 3)
        +    assert [tx["operation"] for tx in restore_range.list_transactions()] == ["Restore"]
        +    for reader in (
        +        restore_range.inserted_rows,
        +        restore_range.updated_rows,
        +        restore_range.upserted_rows,
        +        restore_range.deleted_row_ids,
        +    ):
        +        with pytest.raises(ValueError) as exc_info:
        +            reader()
        +        message = str(exc_info.value)
        +        assert "Restore" in message
        +        assert "full rescan" in message
        +        assert "reinitialize" in message
        +
        +    # A restore in the middle of the range is still unverifiable.
        +    table.add([{"id": 2, "value": 0}])
        +    assert table.version == 4
        +    with pytest.raises(ValueError, match="Restore"):
        +        table.delta(2, 4).upserted_rows()
        +
        +    # A restore at the exclusive boundary is the base snapshot, so later
        +    # changes remain usable.
        +    after_restore = table.delta(3, 4)
        +    assert after_restore.inserted_rows().read_all()["id"].to_pylist() == [2]
        +    assert [tx["operation"] for tx in after_restore.list_transactions()] == ["Append"]
        +
        +    # Equal endpoints remain empty and do not run the restore guard.
        +    equal = table.delta(3, 3)
        +    assert equal.inserted_rows().read_all().num_rows == 0
        +
        +
        +def test_delta_rejects_restore_after_same_uri_recreate(tmp_path):
        +    stable = {"new_table_enable_stable_row_ids": "true"}
        +    old_db = lancedb.connect(tmp_path)
        +    old = old_db.create_table("t", [{"id": 1, "value": 0}], storage_options=stable)
        +    old.add([{"id": 2, "value": 0}])
        +    old.add([{"id": 3, "value": 0}])
        +    assert [tx["operation"] for tx in old.delta(2, 3).list_transactions()] == ["Append"]
        +
        +    writer_db = lancedb.connect(tmp_path)
        +    writer_db.drop_table("t")
        +    schema = pa.schema(
        +        [("id", pa.int32()), ("value", pa.int32())],
        +        metadata={"padding": "x" * (256 * 1024)},
        +    )
        +    recreated = writer_db.create_table(
        +        "t",
        +        pa.Table.from_pylist([{"id": 1, "value": 0}], schema=schema),
        +        storage_options=stable,
        +    )
        +    recreated.update(values={"value": 10})
        +    recreated.restore(1)
        +    assert [tx["operation"] for tx in recreated.delta(2, 3).list_transactions()] == [
        +        "Restore"
        +    ]
        +
        +    delta = old_db.open_table("t").delta(2, 3)
        +    assert [tx["operation"] for tx in delta.list_transactions()] == ["Restore"]
        +    with pytest.raises(ValueError, match="Restore"):
        +        delta.upserted_rows()
        +
        +
        +def test_delta_requires_stable_row_ids(mem_db: DBConnection):
        +    table = mem_db.create_table("delta_no_stable", data=[{"id": 1}])
        +    table.add([{"id": 2}])
        +    delta = table.delta(1)
        +
        +    for reader in (
        +        delta.inserted_rows,
        +        delta.updated_rows,
        +        delta.upserted_rows,
        +        delta.deleted_row_ids,
        +    ):
        +        with pytest.raises(ValueError) as exc_info:
        +            reader()
        +        message = str(exc_info.value)
        +        assert "new_table_enable_stable_row_ids" in message
        +        assert "list_transactions" in message
        +
        +    # Transactions remain available without stable row ids.
        +    transactions = delta.list_transactions()
        +    assert [transaction["operation"] for transaction in transactions] == ["Append"]
        +
        +    # Equal endpoints need no row lineage, so they are empty rather than
        +    # rejected.
        +    version = table.version
        +    equal = table.delta(version, version)
        +    assert equal.inserted_rows().read_all().num_rows == 0
        +    assert equal.deleted_row_ids().read_all().num_rows == 0
        +
        +
        +def test_delta_rejects_cross_branch_tags(tmp_path):
        +    db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
        +    table = db.create_table(
        +        "delta_branches",
        +        data=[{"id": 0}],
        +        storage_options={"new_table_enable_stable_row_ids": "true"},
        +    )
        +    branch = table.branches.create("exp")
        +    branch.add([{"id": 1}])
        +    table.add([{"id": 100}, {"id": 101}, {"id": 102}])
        +    assert branch.version == table.version
        +
        +    table.tags.create("main_tag", table.version)
        +    branch.tags.create("exp_tag", branch.version)
        +
        +    # The same-branch tag resolves through the branch, not main's data at the
        +    # same version number.
        +    delta = branch.delta(1, "exp_tag")
        +    assert delta.inserted_rows().read_all()["id"].to_pylist() == [1]
        +
        +    # Cross-branch tags are rejected even though the version number exists on
        +    # both branches.
        +    with pytest.raises(ValueError) as exc_info:
        +        branch.delta("main_tag")
        +    message = str(exc_info.value)
        +    assert "main_tag" in message
        +    assert "main" in message
        +    assert "exp" in message
        +
        +    with pytest.raises(ValueError, match="exp_tag"):
        +        table.delta("exp_tag")
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_delta(tmp_path):
        +    db = await lancedb.connect_async(tmp_path)
        +    table = await db.create_table(
        +        "async_delta",
        +        data=[{"id": 1}],
        +        storage_options={"new_table_enable_stable_row_ids": "true"},
        +    )
        +    await table.add([{"id": 2}])
        +
        +    delta = await table.delta(1)
        +    assert delta.begin_version == 1
        +    assert delta.end_version == 2
        +
        +    reader = await delta.inserted_rows()
        +    inserted = await reader.read_all()
        +    assert inserted[0]["id"].to_pylist() == [2]
        +
        +    transactions = await delta.list_transactions()
        +    assert [transaction["operation"] for transaction in transactions] == ["Append"]
        +
        +    equal = await table.delta(2, 2)
        +    reader = await equal.inserted_rows()
        +    assert await reader.read_all() == []
        +
        +
         def test_tags(mem_db: DBConnection):
             table = mem_db.create_table(
                 "test",
        @@ -1303,6 +1690,31 @@ def test_tags(mem_db: DBConnection):
             )
         
         
        +def test_tags_create_defaults_to_visible_version(mem_db: DBConnection):
        +    table = mem_db.create_table("test", data=[{"id": 1}])
        +    table.add(data=[{"id": 2}])
        +
        +    table.tags.create("live")
        +    assert table.tags.get_version("live") == 2
        +
        +    table.checkout(1)
        +    table.tags.create("pinned")
        +    assert table.tags.get_version("pinned") == 1
        +
        +    # An explicit version is independent of the version this handle shows.
        +    table.tags.create("explicit", 2)
        +    assert table.tags.get_version("explicit") == 2
        +
        +    # A tag checkout is still a visible version, not "latest".
        +    table.checkout_latest()
        +    table.add(data=[{"id": 3}])
        +    assert table.version == 3
        +    table.checkout("live")
        +    assert table.version == 2
        +    table.tags.create("tag-checkout")
        +    assert table.tags.get_version("tag-checkout") == 2
        +
        +
         @pytest.mark.asyncio
         async def test_async_tags(mem_db_async: AsyncConnection):
             table = await mem_db_async.create_table(
        @@ -1357,6 +1769,34 @@ async def test_async_tags(mem_db_async: AsyncConnection):
             )
         
         
        +@pytest.mark.asyncio
        +async def test_async_tags_create_defaults_to_visible_version(
        +    mem_db_async: AsyncConnection,
        +):
        +    table = await mem_db_async.create_table("test", data=[{"id": 1}])
        +    await table.add(data=[{"id": 2}])
        +
        +    await table.tags.create("live")
        +    assert await table.tags.get_version("live") == 2
        +
        +    await table.checkout(1)
        +    await table.tags.create("pinned")
        +    assert await table.tags.get_version("pinned") == 1
        +
        +    # An explicit version is independent of the version this handle shows.
        +    await table.tags.create("explicit", 2)
        +    assert await table.tags.get_version("explicit") == 2
        +
        +    # A tag checkout is still a visible version, not "latest".
        +    await table.checkout_latest()
        +    await table.add(data=[{"id": 3}])
        +    assert await table.version() == 3
        +    await table.checkout("live")
        +    assert await table.version() == 2
        +    await table.tags.create("tag-checkout")
        +    assert await table.tags.get_version("tag-checkout") == 2
        +
        +
         def test_branches(tmp_path):
             db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
             table = db.create_table(
        @@ -1396,6 +1836,62 @@ def test_branches(tmp_path):
             assert "exp" not in table.branches.list()
         
         
        +def test_branches_create_from_tag(tmp_path):
        +    db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
        +    table = db.create_table("test", data=[{"i": 0}])
        +
        +    exp = table.branches.create("exp")
        +    exp.add([{"i": 10}])
        +    exp_version = exp.version
        +    exp.tags.create("exp-v2", exp_version)
        +
        +    # main reaches the same numeric version with different rows.
        +    table.add([{"i": 100}])
        +    assert table.version == exp_version
        +
        +    forked = table.branches.create("from-tag", from_tag="exp-v2")
        +    assert forked.current_branch() == "from-tag"
        +    assert forked.count_rows("i = 10") == 1
        +    assert forked.count_rows("i = 100") == 0
        +
        +
        +def test_branches_create_from_tag_rejects_other_sources(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("test", data=[{"i": 0}])
        +    table.tags.create("baseline")
        +
        +    # from_ref="main" must be rejected before it is normalized to the default.
        +    with pytest.raises(ValueError, match="from_tag cannot be combined"):
        +        table.branches.create("exp", from_ref="main", from_tag="baseline")
        +    with pytest.raises(ValueError, match="from_tag cannot be combined"):
        +        table.branches.create("exp", from_version=1, from_tag="baseline")
        +
        +
        +def test_branches_create_from_missing_ref_hint_applies_only_to_branches(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("test", data=[{"i": 0}])
        +    base = table.branches.create("base")
        +    base.add([{"i": 1}])
        +    table.tags.create("baseline")
        +
        +    # A tag passed through from_ref is not a branch. Keep the original failure
        +    # classification and add guidance without probing the ref a second time.
        +    with pytest.raises(RuntimeError) as exc_info:
        +        table.branches.create("exp", from_ref="baseline")
        +
        +    detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
        +    assert "from_tag='baseline'" in detail
        +
        +    # An existing branch with an absent version is a version failure, not an
        +    # unresolved branch, so it must not suggest from_tag.
        +    with pytest.raises(RuntimeError) as exc_info:
        +        table.branches.create("exp", from_ref="base", from_version=9999)
        +
        +    detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
        +    assert "9999" in detail
        +    assert "from_tag=" not in detail
        +
        +
         def test_branch_handle_tracks_concurrent_writes(tmp_path):
             db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
             table = db.create_table("t", [{"id": 1}])
        @@ -1691,6 +2187,64 @@ async def test_async_branches(tmp_path):
             assert "exp" not in await table.branches.list()
         
         
        +@pytest.mark.asyncio
        +async def test_async_branches_create_from_tag(tmp_path):
        +    db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0))
        +    table = await db.create_table("test", data=[{"i": 0}])
        +
        +    exp = await table.branches.create("exp")
        +    await exp.add([{"i": 10}])
        +    exp_version = await exp.version()
        +    await exp.tags.create("exp-v2", exp_version)
        +
        +    # main reaches the same numeric version with different rows.
        +    await table.add([{"i": 100}])
        +    assert await table.version() == exp_version
        +
        +    forked = await table.branches.create("from-tag", from_tag="exp-v2")
        +    assert forked.current_branch() == "from-tag"
        +    assert await forked.count_rows("i = 10") == 1
        +    assert await forked.count_rows("i = 100") == 0
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_branches_create_from_tag_rejects_other_sources(tmp_path):
        +    db = await lancedb.connect_async(tmp_path)
        +    table = await db.create_table("test", data=[{"i": 0}])
        +    await table.tags.create("baseline")
        +
        +    with pytest.raises(ValueError, match="from_tag cannot be combined"):
        +        await table.branches.create("exp", from_ref="main", from_tag="baseline")
        +    with pytest.raises(ValueError, match="from_tag cannot be combined"):
        +        await table.branches.create("exp", from_version=1, from_tag="baseline")
        +
        +
        +@pytest.mark.asyncio
        +async def test_async_branches_create_from_missing_ref_hint_applies_only_to_branches(
        +    tmp_path,
        +):
        +    db = await lancedb.connect_async(tmp_path)
        +    table = await db.create_table("test", data=[{"i": 0}])
        +    base = await table.branches.create("base")
        +    await base.add([{"i": 1}])
        +    await table.tags.create("baseline")
        +
        +    with pytest.raises(RuntimeError) as exc_info:
        +        await table.branches.create("exp", from_ref="baseline")
        +
        +    detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
        +    assert "from_tag='baseline'" in detail
        +
        +    # An existing branch with an absent version is a version failure, not an
        +    # unresolved branch, so it must not suggest from_tag.
        +    with pytest.raises(RuntimeError) as exc_info:
        +        await table.branches.create("exp", from_ref="base", from_version=9999)
        +
        +    detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
        +    assert "9999" in detail
        +    assert "from_tag=" not in detail
        +
        +
         @pytest.mark.asyncio
         async def test_async_open_table_with_branch_version(tmp_path):
             db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0))
        @@ -1758,7 +2312,7 @@ async def test_async_open_table_with_branch_version(tmp_path):
         def test_create_index_async_returns_done_job(mem_db: DBConnection):
             table = mem_db.create_table("job_test", [{"id": i} for i in range(10)])
             job = table.create_index_async("id", config=BTree())
        -    assert job.id is None
        +    assert job.id() is None
             assert job.wait() is None
             assert len(table.list_indices()) == 1
             job.cancel()
        @@ -1837,6 +2391,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
             # Test with target_partition_size
        @@ -1862,6 +2417,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
             # target_partition_size has a default value,
        @@ -1886,6 +2442,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
             table.create_index(
        @@ -1902,6 +2459,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
             table.create_index(
        @@ -1922,6 +2480,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
             table.create_index(
        @@ -1942,6 +2501,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
         
        @@ -2073,6 +2633,7 @@ def test_create_index_name_and_train_parameters(
                 wait_timeout=None,
                 name="my_custom_index",
                 train=True,
        +        exist_ok=False,
             )
         
             # Test with train=False
        @@ -2084,6 +2645,7 @@ def test_create_index_name_and_train_parameters(
                 wait_timeout=None,
                 name=None,
                 train=False,
        +        exist_ok=False,
             )
         
             # Test with both name and train
        @@ -2095,6 +2657,7 @@ def test_create_index_name_and_train_parameters(
                 wait_timeout=None,
                 name="my_index_name",
                 train=True,
        +        exist_ok=False,
             )
         
         
        @@ -2132,6 +2695,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
             # Scalar index via new API
        @@ -2143,6 +2707,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
             # FTS index via new API
        @@ -2154,6 +2719,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
                 wait_timeout=None,
                 name=None,
                 train=True,
        +        exist_ok=False,
             )
         
         
        @@ -3436,7 +4002,8 @@ def test_merge_insert(mem_db: DBConnection):
                 table.merge_insert("a")
                 .when_matched_update_all()
                 .when_not_matched_insert_all()
        -        .execute(new_data, timeout=timedelta(seconds=10))
        +        .use_index(False)
        +        .execute(new_data, timeout=timedelta(seconds=10), retries=0)
             )
             assert merge_insert_res.version == 2
             assert merge_insert_res.num_inserted_rows == 1
        @@ -3515,7 +4082,7 @@ def test_merge_insert(mem_db: DBConnection):
             # timeout
             with pytest.raises(Exception, match="merge insert timed out"):
                 table.merge_insert("a").when_matched_update_all().execute(
        -            new_data, timeout=timedelta(0)
        +            new_data, timeout=timedelta(0), retries=255
                 )
         
         
        @@ -5984,6 +6551,62 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
                 getattr(table, method)("x", batch_size=batch_size)
         
         
        +@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"])
        +@pytest.mark.parametrize(
        +    "refresh_kwargs,option",
        +    [
        +        ({"retry_policy": lancedb.FunctionRetryPolicy(transient=True)}, "retry_policy"),
        +        ({"where": "x > 0"}, "where"),
        +        ({"error_policy": "skip"}, "error_policy"),
        +        ({"max_failed_fraction": 0.5}, "max_failed_fraction"),
        +        ({"max_failed_rows": 10}, "max_failed_rows"),
        +        ({"row_timeout_seconds": 30}, "row_timeout_seconds"),
        +        ({"init_timeout_seconds": 60}, "init_timeout_seconds"),
        +        ({"max_concurrency": 4}, "max_concurrency"),
        +        ({"publication_interval_rows": 60}, "publication_interval_rows"),
        +        (
        +            {"total_cpu_millis": 1000, "total_memory_bytes": 1024},
        +            "total_cpu_millis",
        +        ),
        +        (
        +            {
        +                "supervisor_resources": {
        +                    "cpu_millis": 1000,
        +                    "memory_bytes": 1024,
        +                    "ephemeral_storage_bytes": 2048,
        +                }
        +            },
        +            "supervisor_resources",
        +        ),
        +        (
        +            {
        +                "planning_workers": {
        +                    "resources": {
        +                        "cpu_millis": 1000,
        +                        "memory_bytes": 1024,
        +                        "ephemeral_storage_bytes": 2048,
        +                    },
        +                    "max_workers": 2,
        +                    "rows_per_worker": 100,
        +                    "fragments_per_worker": 1,
        +                }
        +            },
        +            "planning_workers",
        +        ),
        +        ({"num_workers": 2}, "num_workers"),
        +        ({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
        +    ],
        +)
        +def test_local_refresh_rejects_enterprise_options(
        +    tmp_path, method, refresh_kwargs, option
        +):
        +    table = lancedb.connect(tmp_path).create_table("rows", [{"x": 1}])
        +    with pytest.raises(
        +        NotImplementedError, match=f"{option} requires a LanceDB Enterprise refresh"
        +    ):
        +        getattr(table, method)("x", **refresh_kwargs)
        +
        +
         @pytest.mark.asyncio
         @pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"])
         @pytest.mark.parametrize("batch_size", [0, -1])
        @@ -6005,6 +6628,16 @@ def test_function_errors_are_remote_only(tmp_path):
                 table.function_errors()
         
         
        +def test_function_column_status_is_remote_only(tmp_path):
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table("t", [{"x": 1}])
        +    with pytest.raises(
        +        NotImplementedError,
        +        match="exact Function column status is supported only in LanceDB Enterprise",
        +    ):
        +        table.wait_fresh("x")
        +
        +
         @pytest.mark.experimental_functions
         @pytest.mark.parametrize("batch_size", [None, 8])
         def test_refresh_column_async_returns_job(tmp_path, batch_size):
        @@ -6013,7 +6646,7 @@ def test_refresh_column_async_returns_job(tmp_path, batch_size):
             table.add_columns(computed={"doubled": "x * 2"})
         
             job = table.refresh_column_async("doubled", batch_size=batch_size)
        -    assert job.id is None  # in-process jobs have no server id
        +    assert job.id() is None  # in-process jobs have no server id
             result = job.wait()
             assert isinstance(result, lancedb.RefreshColumnResult)
             assert result.rows_assigned == 2
        @@ -6225,6 +6858,19 @@ def test_auto_refresh_options_require_computed_columns(tmp_path):
                 table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True)
         
         
        +def test_auto_refresh_resource_budget_requires_a_function(tmp_path):
        +    table = lancedb.connect(tmp_path).create_table("invalid_budget", [{"x": 1}])
        +    before = table.version
        +    with pytest.raises(ValueError, match="registered Function"):
        +        table.add_columns(
        +            computed={"doubled": "x * 2"},
        +            total_cpu_millis=1_000,
        +            total_memory_bytes=1_024,
        +        )
        +    assert table.version == before
        +    assert table.schema.names == ["x"]
        +
        +
         @pytest.mark.experimental_functions
         @pytest.mark.asyncio
         async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
        @@ -6236,3 +6882,108 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
             metadata = (await table.schema()).field("doubled").metadata
             assert metadata[b"computed_column.auto_refresh_enabled"] == b"true"
             assert b"computed_column.auto_refresh_interval_seconds" not in metadata
        +
        +
        +@pytest.mark.parametrize(
        +    "method",
        +    ["create_index", "create_index_async", "create_scalar_index", "create_fts_index"],
        +)
        +@pytest.mark.parametrize("name", [None, "kept_index"])
        +def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name):
        +    table = mem_db.create_table(
        +        "keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)]
        +    )
        +    column = "text" if method == "create_fts_index" else "id"
        +    config = FTS() if column == "text" else BTree()
        +    table.create_index(column, config=config, name=name, exist_ok=True)
        +    before = table.version
        +    original = table.list_indices()
        +    kwargs = dict(name=name, exist_ok=True)
        +    if method in ("create_index", "create_index_async"):
        +        kwargs["config"] = config
        +    with warnings.catch_warnings():
        +        warnings.simplefilter("ignore", DeprecationWarning)
        +        result = getattr(table, method)(column, **kwargs)
        +    if method == "create_index_async":
        +        result.wait()
        +    assert table.version == before
        +    assert [(index.name, index.index_type) for index in table.list_indices()] == [
        +        (index.name, index.index_type) for index in original
        +    ]
        +    with pytest.raises((ValueError, RuntimeError), match="already exists"):
        +        table.create_index(column, config=config, name=name, replace=False)
        +    table.create_index(column, config=config, name=name)
        +    assert table.version > before
        +
        +
        +@pytest.mark.parametrize(
        +    "column,name,existing",
        +    [
        +        ("vector", "kept", "kept"),
        +        ("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"),
        +    ],
        +)
        +def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing):
        +    dataset = MagicMock()
        +    dataset.list_indices.return_value = [{"name": existing}]
        +    with patch("lancedb.table._validate_index_accelerator") as validate:
        +        table_module._create_accelerated_index(
        +            dataset, column=column, accelerator="cuda", name=name, exist_ok=True
        +        )
        +    validate.assert_not_called()
        +    dataset.create_index.assert_not_called()
        +
        +
        +def test_accelerated_index_exist_ok_preserves_concurrent_winner():
        +    dataset = MagicMock()
        +    dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]]
        +    dataset.create_index.side_effect = RuntimeError("concurrent create")
        +    with patch("lancedb.table._validate_index_accelerator"):
        +        table_module._create_accelerated_index(
        +            dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True
        +        )
        +    assert dataset.create_index.call_args.kwargs["replace"] is False
        +    assert dataset.create_index.call_args.kwargs["name"] == "vector_idx"
        +
        +
        +@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"])
        +def test_index_exist_ok_matches_lance_default_name(mem_db, column):
        +    table = mem_db.create_table(
        +        "quoted_index",
        +        [{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}],
        +    )
        +    table.create_index(column, config=BTree())
        +    before = table.version
        +    table.create_index(column, config=BTree(), exist_ok=True)
        +    assert table.version == before
        +    assert len(table.list_indices()) == 1
        +
        +
        +def test_fts_exist_ok_matches_quoted_default_name(mem_db):
        +    table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}])
        +    table.create_index("`body-text`", config=FTS())
        +    before = table.version
        +    table.create_index("`body-text`", config=FTS(), exist_ok=True)
        +    assert table.version == before
        +    assert len(table.list_indices()) == 1
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"]
        +)
        +async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method):
        +    if asynchronous:
        +        db = await lancedb.connect_async(tmp_path)
        +        table = await db.create_table("prewarm", [{"id": 1}])
        +        with pytest.raises(
        +            NotImplementedError, match="only supported on remote tables"
        +        ):
        +            await getattr(table, method)(filter="id > 0", concurrency=2)
        +    else:
        +        table = lancedb.connect(tmp_path).create_table("prewarm", [{"id": 1}])
        +        with pytest.raises(
        +            NotImplementedError, match="only supported on remote tables"
        +        ):
        +            getattr(table, method)(filter="id > 0", concurrency=2)
        diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py
        index 387a89f31..41a688068 100644
        --- a/python/python/tests/test_table_signatures.py
        +++ b/python/python/tests/test_table_signatures.py
        @@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table):
             }.items():
                 assert getattr(config, name) == value
             assert kwargs == dict(
        -        wait_timeout=timeout, name="custom_idx", replace=False, train=False
        +        wait_timeout=timeout,
        +        name="custom_idx",
        +        replace=False,
        +        train=False,
        +        exist_ok=False,
             )
         
         
        diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py
        index befa3c10f..afbba92d1 100644
        --- a/python/python/tests/test_torch.py
        +++ b/python/python/tests/test_torch.py
        @@ -8,13 +8,15 @@ import json
         import multiprocessing as mp
         import pickle
         import re
        +import struct
         import sys
         
         import lancedb
        +import numpy as np
         import pyarrow as pa
         import pytest
         from lancedb.permutation import Permutation, Permutations, permutation_builder
        -from lancedb.util import tbl_to_tensor
        +from lancedb.util import batch_to_tensor, batch_to_tensor_columns, tbl_to_tensor
         from utils import start_server_thread
         
         torch = pytest.importorskip("torch")
        @@ -23,6 +25,43 @@ torch = pytest.importorskip("torch")
         REMOTE_ROWS = list(range(100))
         
         
        +def _identity_collate(batch):
        +    return batch
        +
        +
        +class _LanceBFloat16Type(pa.ExtensionType):
        +    def __init__(self):
        +        pa.ExtensionType.__init__(self, pa.binary(2), "lance.bfloat16")
        +
        +    def __arrow_ext_serialize__(self):
        +        return b""
        +
        +    @classmethod
        +    def __arrow_ext_deserialize__(cls, storage_type, serialized):
        +        return cls()
        +
        +
        +def _bf16_storage(values):
        +    bits = torch.tensor(values, dtype=torch.bfloat16).view(torch.int16).tolist()
        +    return [struct.pack(" 0
             must work end-to-end. Each worker process gets a pickled copy of the
        @@ -455,3 +535,504 @@ def test_remote_permutation_dataloader_fork_workers():
                 finally:
                     server.shutdown()
                     handle.join()
        +
        +
        +def test_permutation_torch_dict_mixed_columns(mem_db):
        +    vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
        +    grids = [
        +        [[float(row), float(row) + 1.0], [float(row) + 2.0, float(row) + 3.0]]
        +        for row in range(5)
        +    ]
        +    table = mem_db.create_table(
        +        "mixed",
        +        pa.table(
        +            {
        +                "id": pa.array(range(5), type=pa.int32()),
        +                "score": pa.array([i / 2 for i in range(5)], type=pa.float32()),
        +                "vector": pa.array(vectors, type=pa.list_(pa.float32(), 3)),
        +                "grid": pa.array(grids, type=pa.list_(pa.list_(pa.float32(), 2), 2)),
        +            }
        +        ),
        +    )
        +    permutation = Permutation.identity(table).with_format("torch_dict")
        +
        +    batch = next(permutation.iter(5, skip_last_batch=False))
        +    assert set(batch) == {"id", "score", "vector", "grid"}
        +    assert batch["id"].shape == (5,)
        +    assert batch["id"].dtype == torch.int32
        +    assert batch["score"].dtype == torch.float32
        +    assert batch["vector"].shape == (5, 3)
        +    assert batch["grid"].shape == (5, 2, 2)
        +    assert torch.equal(batch["vector"], torch.tensor(vectors))
        +    assert torch.equal(batch["grid"], torch.tensor(grids))
        +
        +    items = permutation.__getitems__([0, 2, 4])
        +    assert items["id"].shape == (3,)
        +    assert items["score"].shape == (3,)
        +    assert items["vector"].shape == (3, 3)
        +    assert items["grid"].shape == (3, 2, 2)
        +
        +    dataloader = torch.utils.data.DataLoader(
        +        permutation,
        +        batch_size=2,
        +        shuffle=False,
        +        collate_fn=_identity_collate,
        +    )
        +    batches = list(dataloader)
        +    assert [batch["id"].shape[0] for batch in batches] == [2, 2, 1]
        +    assert batches[0]["vector"].shape == (2, 3)
        +    assert batches[-1]["grid"].shape == (1, 2, 2)
        +
        +    empty = permutation.take_offsets([])
        +    assert empty["id"].shape == (0,)
        +    assert empty["vector"].shape == (0, 3)
        +    assert empty["grid"].shape == (0, 2, 2)
        +
        +    torch_permutation = Permutation.identity(table).with_format("torch")
        +    per_row = next(torch_permutation.iter(2, skip_last_batch=False))
        +    assert isinstance(per_row, list)
        +    assert per_row[0]["vector"].shape == (3,)
        +    assert per_row[0]["grid"].shape == (2, 2)
        +    torch_loader = torch.utils.data.DataLoader(
        +        torch_permutation, batch_size=2, shuffle=False
        +    )
        +    collated = next(iter(torch_loader))
        +    assert collated["vector"].shape == (2, 3)
        +    assert collated["grid"].shape == (2, 2, 2)
        +
        +
        +def test_permutation_torch_dict_dataloader_spawn(tmp_db):
        +    vectors = [[float(i), float(i) + 0.5] for i in range(11)]
        +    table = tmp_db.create_table(
        +        "spawn",
        +        pa.table(
        +            {
        +                "id": range(11),
        +                "vector": pa.array(vectors, type=pa.list_(pa.float32(), 2)),
        +            }
        +        ),
        +    )
        +    permutation = Permutation.identity(table).with_format("torch_dict")
        +
        +    dataloader = torch.utils.data.DataLoader(
        +        permutation,
        +        batch_size=4,
        +        shuffle=False,
        +        num_workers=2,
        +        multiprocessing_context="spawn",
        +        collate_fn=_identity_collate,
        +    )
        +    seen = []
        +    for batch in dataloader:
        +        assert isinstance(batch, dict)
        +        assert batch["id"].shape == (batch["id"].shape[0],)
        +        assert batch["vector"].shape == (batch["id"].shape[0], 2)
        +        seen.extend(batch["id"].tolist())
        +    assert sorted(seen) == list(range(11))
        +
        +
        +def _map_add_scaled(row):
        +    return {**row, "scaled": row["a"] * 2}
        +
        +
        +def _map_add_total(batch):
        +    total = [a + scaled for a, scaled in zip(batch["a"], batch["scaled"])]
        +    return {**batch, "total": total}
        +
        +
        +def test_permutation_map_dataloader_spawn(tmp_db):
        +    """A map chain must be picklable so spawned DataLoader workers can run it."""
        +    table = tmp_db.create_table("test_table", pa.table({"a": range(100)}))
        +    permutation = (
        +        Permutation.identity(table)
        +        .map(_map_add_scaled)
        +        .map(_map_add_total, batched=True)
        +    )
        +
        +    dataloader = torch.utils.data.DataLoader(
        +        permutation,
        +        batch_size=10,
        +        num_workers=1,
        +        multiprocessing_context="spawn",
        +    )
        +    seen = []
        +    for batch in dataloader:
        +        assert set(batch) == {"a", "scaled", "total"}
        +        assert torch.equal(batch["total"], batch["a"] * 3)
        +        seen.extend(batch["a"].tolist())
        +    assert seen == list(range(100))
        +
        +
        +def test_batch_to_tensor_columns_zero_copy_and_slice_offsets():
        +    vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
        +    nested_values = np.arange(5 * 3 * 2, dtype=np.float32).reshape(5, 3, 2)
        +    batch = pa.record_batch(
        +        [
        +            pa.array(range(5), type=pa.int64()),
        +            pa.array(vectors, type=pa.list_(pa.float32(), 3)),
        +            pa.array(
        +                nested_values.tolist(),
        +                type=pa.list_(pa.list_(pa.float32(), 2), 3),
        +            ),
        +            pa.array([True, False, True, False, True]),
        +        ],
        +        names=["id", "vector", "nested", "active"],
        +    ).slice(2, 2)
        +
        +    tensors = batch_to_tensor_columns(batch)
        +    assert tensors["id"].tolist() == [2, 3]
        +    assert torch.equal(tensors["vector"], torch.tensor(vectors[2:4]))
        +    assert torch.equal(tensors["nested"], torch.from_numpy(nested_values[2:4].copy()))
        +    assert tensors["active"].dtype == torch.bool
        +    assert tensors["active"].tolist() == [True, False]
        +
        +    id_array = batch.column("id")
        +    assert tensors["id"].data_ptr() == (
        +        id_array.buffers()[1].address + id_array.offset * 8
        +    )
        +    vector_array = batch.column("vector")
        +    vector_values = vector_array.values
        +    expected_vector_offset = (vector_array.offset * 3 + vector_values.offset) * 4
        +    assert tensors["vector"].data_ptr() == (
        +        vector_values.buffers()[1].address + expected_vector_offset
        +    )
        +
        +    single_column = pa.record_batch([batch.column("vector")], names=["vector"])
        +    column_tensor = batch_to_tensor(single_column)
        +    assert column_tensor.shape == (1, 2, 3)
        +    assert column_tensor.data_ptr() == tensors["vector"].data_ptr()
        +
        +
        +def test_permutation_torch_col_and_row_vector_layouts(mem_db):
        +    left = [[float(i), float(i) + 0.5] for i in range(4)]
        +    right = [[float(i) + 1.0, float(i) + 1.5] for i in range(4)]
        +    table = mem_db.create_table(
        +        "uniform",
        +        pa.table(
        +            {
        +                "left": pa.array(left, type=pa.list_(pa.float32(), 2)),
        +                "right": pa.array(right, type=pa.list_(pa.float32(), 2)),
        +            }
        +        ),
        +    )
        +    permutation = Permutation.identity(table)
        +
        +    column_batch = next(
        +        permutation.with_format("torch_col").iter(4, skip_last_batch=False)
        +    )
        +    assert column_batch.shape == (2, 4, 2)
        +    assert column_batch.dtype == torch.float32
        +    assert torch.equal(column_batch[0], torch.tensor(left))
        +
        +    row_batch = next(
        +        permutation.with_format("torch_row").iter(4, skip_last_batch=False)
        +    )
        +    assert len(row_batch) == 4
        +    assert row_batch[0].shape == (2, 2)
        +    assert torch.equal(
        +        row_batch[0], torch.stack([torch.tensor(left[0]), torch.tensor(right[0])])
        +    )
        +
        +    dataloader = torch.utils.data.DataLoader(
        +        permutation.with_format("torch_row"), batch_size=4, shuffle=False
        +    )
        +    stacked = next(iter(dataloader))
        +    assert stacked.shape == (4, 2, 2)
        +
        +    scalar_table = mem_db.create_table(
        +        "single_scalar", pa.table({"x": pa.array(range(4), type=pa.int64())})
        +    )
        +    scalar_rows = next(
        +        Permutation.identity(scalar_table)
        +        .with_format("torch_row")
        +        .iter(4, skip_last_batch=False)
        +    )
        +    assert scalar_rows[0].shape == (1,)
        +    assert scalar_rows[0].dtype == torch.int64
        +
        +    vector_table = mem_db.create_table(
        +        "single_vector",
        +        pa.table({"v": pa.array(left, type=pa.list_(pa.float32(), 2))}),
        +    )
        +    vector_rows = next(
        +        Permutation.identity(vector_table)
        +        .with_format("torch_row")
        +        .iter(4, skip_last_batch=False)
        +    )
        +    assert vector_rows[0].shape == (1, 2)
        +    vector_column = next(
        +        Permutation.identity(vector_table)
        +        .with_format("torch_col")
        +        .iter(4, skip_last_batch=False)
        +    )
        +    assert vector_column.shape == (1, 4, 2)
        +
        +
        +def test_torch_col_and_row_reject_heterogeneous_shapes(mem_db):
        +    table = mem_db.create_table(
        +        "heterogeneous",
        +        pa.table(
        +            {
        +                "id": pa.array(range(4), type=pa.int64()),
        +                "vector": pa.array(
        +                    [[float(i), float(i) + 1.0, float(i) + 2.0] for i in range(4)],
        +                    type=pa.list_(pa.float32(), 3),
        +                ),
        +            }
        +        ),
        +    )
        +    permutation = Permutation.identity(table)
        +    for format_name in ("torch_col", "torch_row"):
        +        with pytest.raises(ValueError, match="torch_dict") as exc_info:
        +            next(permutation.with_format(format_name).iter(2, skip_last_batch=False))
        +        message = str(exc_info.value)
        +        assert "`vector`" in message
        +        assert "(3,)" in message
        +        assert "`id`" in message
        +        assert "()" in message
        +
        +    different_dims = mem_db.create_table(
        +        "different_dims",
        +        pa.table(
        +            {
        +                "left": pa.array(
        +                    [[1.0, 2.0] for _ in range(4)],
        +                    type=pa.list_(pa.float32(), 2),
        +                ),
        +                "right": pa.array(
        +                    [[1.0, 2.0, 3.0] for _ in range(4)],
        +                    type=pa.list_(pa.float32(), 3),
        +                ),
        +            }
        +        ),
        +    )
        +    with pytest.raises(ValueError, match="torch_dict") as exc_info:
        +        next(
        +            Permutation.identity(different_dims)
        +            .with_format("torch_row")
        +            .iter(2, skip_last_batch=False)
        +        )
        +    message = str(exc_info.value)
        +    assert "`right`" in message and "(3,)" in message
        +    assert "`left`" in message and "(2,)" in message
        +
        +
        +def test_torch_row_uses_pytorch_numeric_promotion(mem_db):
        +    table = mem_db.create_table(
        +        "promotion",
        +        pa.table(
        +            {
        +                "id": pa.array(range(4), type=pa.int64()),
        +                "score": pa.array([i / 2 for i in range(4)], type=pa.float32()),
        +                "count": pa.array(range(4), type=pa.int32()),
        +            }
        +        ),
        +    )
        +    rows = next(
        +        Permutation.identity(table)
        +        .with_format("torch_row")
        +        .iter(4, skip_last_batch=False)
        +    )
        +    assert rows[0].shape == (3,)
        +    assert rows[0].dtype == torch.float32
        +    assert rows[0].tolist() == [0.0, 0.0, 0.0]
        +    assert rows[2].tolist() == [2.0, 1.0, 2.0]
        +
        +
        +def test_torch_row_preserves_nullable_numeric_scalar_nan(mem_db):
        +    nullable_int = mem_db.create_table(
        +        "nullable_int",
        +        pa.table({"value": pa.array([1, None, 3], type=pa.int64())}),
        +    )
        +    rows = next(
        +        Permutation.identity(nullable_int)
        +        .with_format("torch_row")
        +        .iter(3, skip_last_batch=False)
        +    )
        +    assert rows[0].shape == (1,)
        +    assert rows[0].dtype == torch.float64
        +    assert rows[0].tolist() == [1.0]
        +    assert torch.isnan(rows[1]).all()
        +    assert rows[2].tolist() == [3.0]
        +
        +    nullable_float = mem_db.create_table(
        +        "nullable_float",
        +        pa.table({"value": pa.array([0.5, None, 2.5], type=pa.float32())}),
        +    )
        +    rows = next(
        +        Permutation.identity(nullable_float)
        +        .with_format("torch_row")
        +        .iter(3, skip_last_batch=False)
        +    )
        +    assert rows[0].dtype == torch.float32
        +    assert rows[0].tolist() == [0.5]
        +    assert torch.isnan(rows[1]).all()
        +    assert rows[2].tolist() == [2.5]
        +
        +    nullable_mixed = mem_db.create_table(
        +        "nullable_mixed",
        +        pa.table(
        +            {
        +                "id": pa.array([1, None, 3], type=pa.int64()),
        +                "score": pa.array([0.5, 1.5, 2.5], type=pa.float32()),
        +            }
        +        ),
        +    )
        +    rows = next(
        +        Permutation.identity(nullable_mixed)
        +        .with_format("torch_row")
        +        .iter(3, skip_last_batch=False)
        +    )
        +    assert rows[0].dtype == torch.float64
        +    assert rows[0].tolist() == [1.0, 0.5]
        +    assert torch.isnan(rows[1][0])
        +    assert rows[1][1].item() == 1.5
        +    assert rows[2].tolist() == [3.0, 2.5]
        +
        +
        +def test_permutation_torch_formats_fixed_shape_tensor_permutation(mem_db):
        +    physical_values = np.arange(2 * 2 * 3 * 4, dtype=np.float32).reshape(2, 2, 3, 4)
        +    tensor_array = _fixed_shape_tensor_array(
        +        physical_values, shape=(2, 3, 4), permutation=[0, 2, 1]
        +    )
        +    table = mem_db.create_table(
        +        "tensor_permutation",
        +        pa.table({"id": range(2), "tensor": tensor_array}),
        +    )
        +    permutation = Permutation.identity(table)
        +    expected = np.transpose(physical_values, (0, 1, 3, 2))
        +
        +    batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
        +    assert batch["tensor"].shape == (2, 2, 4, 3)
        +    assert torch.equal(batch["tensor"], torch.from_numpy(expected.copy()))
        +
        +    tensor_only = permutation.select_columns(["tensor"])
        +    rows = next(tensor_only.with_format("torch_row").iter(2, skip_last_batch=False))
        +    assert rows[0].shape == (1, 2, 4, 3)
        +    assert torch.equal(rows[0][0], torch.from_numpy(expected[0].copy()))
        +
        +    dataloader = torch.utils.data.DataLoader(
        +        tensor_only.with_format("torch"), batch_size=2, shuffle=False
        +    )
        +    default_collated = next(iter(dataloader))
        +    assert default_collated["tensor"].shape == (2, 2, 4, 3)
        +
        +
        +def test_permutation_torch_formats_bfloat16(mem_db):
        +    values = [1.0, -1.5, 2.5, 0.0]
        +    scalar_values = _bf16_array(values)
        +    vector_values = pa.FixedSizeListArray.from_arrays(
        +        _bf16_array([value for value in values for _ in range(2)]), 2
        +    )
        +    table = mem_db.create_table(
        +        "bfloat16",
        +        pa.table(
        +            {
        +                "id": range(4),
        +                "scalar": scalar_values,
        +                "vector": vector_values,
        +            }
        +        ),
        +    )
        +    permutation = Permutation.identity(table)
        +
        +    batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
        +    assert batch["scalar"].dtype == torch.bfloat16
        +    assert batch["vector"].dtype == torch.bfloat16
        +    assert torch.equal(batch["scalar"], torch.tensor(values[:2], dtype=torch.bfloat16))
        +    assert torch.equal(
        +        batch["vector"],
        +        torch.tensor([[value, value] for value in values[:2]], dtype=torch.bfloat16),
        +    )
        +
        +    arrow_batch = next(permutation.with_format("arrow").iter(2, skip_last_batch=False))
        +    arrow_tensors = batch_to_tensor_columns(arrow_batch)
        +    scalar_array = arrow_batch.column("scalar")
        +    assert arrow_tensors["scalar"].data_ptr() == (
        +        scalar_array.buffers()[1].address + scalar_array.offset * 2
        +    )
        +
        +    sliced = arrow_batch.slice(1, 1)
        +    sliced_tensors = batch_to_tensor_columns(sliced)
        +    assert torch.equal(
        +        sliced_tensors["scalar"],
        +        torch.tensor([values[1]], dtype=torch.bfloat16),
        +    )
        +    assert torch.equal(
        +        sliced_tensors["vector"],
        +        torch.tensor([[values[1], values[1]]], dtype=torch.bfloat16),
        +    )
        +
        +    skipped = next(
        +        permutation.with_skip(1)
        +        .with_format("torch_dict")
        +        .iter(2, skip_last_batch=False)
        +    )
        +    assert torch.equal(
        +        skipped["scalar"], torch.tensor(values[1:3], dtype=torch.bfloat16)
        +    )
        +
        +    empty = permutation.with_format("torch_dict").take_offsets([])
        +    assert empty["scalar"].shape == (0,)
        +    assert empty["scalar"].dtype == torch.bfloat16
        +    assert empty["vector"].shape == (0, 2)
        +    assert empty["vector"].dtype == torch.bfloat16
        +
        +    unmarked = mem_db.create_table(
        +        "unmarked_bfloat16",
        +        pa.table(
        +            {
        +                "vector": pa.FixedSizeListArray.from_arrays(
        +                    pa.array(_bf16_storage(values), type=pa.binary(2)), 2
        +                )
        +            }
        +        ),
        +    )
        +    with pytest.raises(ValueError, match="not marked.*lance.bfloat16"):
        +        next(
        +            Permutation.identity(unmarked)
        +            .with_format("torch_dict")
        +            .iter(2, skip_last_batch=False)
        +        )
        +
        +
        +def test_torch_formats_reject_nulls(mem_db):
        +    parent_nulls = mem_db.create_table(
        +        "parent_nulls",
        +        pa.table(
        +            {
        +                "id": range(3),
        +                "values": pa.array(
        +                    [[1.0, 2.0], None, [5.0, 6.0]],
        +                    type=pa.list_(pa.float32(), 2),
        +                ),
        +            }
        +        ),
        +    )
        +    with pytest.raises(ValueError, match="contains 1 null"):
        +        next(
        +            Permutation.identity(parent_nulls)
        +            .with_format("torch_dict")
        +            .iter(2, skip_last_batch=False)
        +        )
        +
        +    leaf_nulls = mem_db.create_table(
        +        "leaf_nulls",
        +        pa.table(
        +            {
        +                "id": range(2),
        +                "values": pa.FixedSizeListArray.from_arrays(
        +                    pa.array([1.0, None, 5.0, 6.0], type=pa.float32()), 2
        +                ),
        +            }
        +        ),
        +    )
        +    with pytest.raises(ValueError, match="contains 1 null"):
        +        next(
        +            Permutation.identity(leaf_nulls)
        +            .with_format("torch_dict")
        +            .iter(2, skip_last_batch=False)
        +        )
        +    leaf_only = Permutation.identity(leaf_nulls).select_columns(["values"])
        +    with pytest.raises(ValueError, match="contains 1 null"):
        +        next(leaf_only.with_format("torch_row").iter(2, skip_last_batch=False))
        diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py
        index 5f444ac44..17758c41e 100644
        --- a/python/python/tests/test_util.py
        +++ b/python/python/tests/test_util.py
        @@ -407,6 +407,33 @@ def test_value_to_sql_nan_and_infinity(tmp_path):
             assert rows[4]["f64"] == 4.0 and rows[4]["f32"] == 4.0
         
         
        +def test_value_to_sql_enum_members(tmp_path):
        +    # str() of an int- or float-valued Enum member is its name, which SQL reads
        +    # as a field access, and a plain Enum member raised NotImplementedError.
        +    import enum
        +
        +    class Priority(int, enum.Enum):
        +        LOW = 1
        +        HIGH = 2
        +
        +    class Weight(float, enum.Enum):
        +        HALF = 0.5
        +
        +    class Color(enum.Enum):
        +        RED = "red"
        +
        +    assert value_to_sql(Priority.HIGH) == "2"
        +    assert value_to_sql(Weight.HALF) == "0.5"
        +    assert value_to_sql(Color.RED) == "'red'"
        +
        +    db = lancedb.connect(tmp_path)
        +    table = db.create_table(
        +        "test", pa.table({"id": [1], "p": [1], "w": [1.0], "c": ["blue"]})
        +    )
        +    table.update(values={"p": Priority.HIGH, "w": Weight.HALF, "c": Color.RED})
        +    assert table.to_arrow().to_pylist() == [{"id": 1, "p": 2, "w": 0.5, "c": "red"}]
        +
        +
         def test_append_vector_columns():
             registry = EmbeddingFunctionRegistry.get_instance()
             registry.register("test")(MockTextEmbeddingFunction)
        diff --git a/python/python/tests/test_view_creation.py b/python/python/tests/test_view_creation.py
        new file mode 100644
        index 000000000..410356da0
        --- /dev/null
        +++ b/python/python/tests/test_view_creation.py
        @@ -0,0 +1,71 @@
        +# SPDX-License-Identifier: Apache-2.0
        +# SPDX-FileCopyrightText: Copyright The LanceDB Authors
        +
        +import json
        +
        +import pyarrow as pa
        +import pytest
        +
        +import lancedb
        +
        +
        +@pytest.mark.asyncio
        +@pytest.mark.parametrize("asynchronous", [False, True])
        +@pytest.mark.parametrize(
        +    ("exist_ok", "existing"),
        +    [(None, False), (False, False), (True, False), (True, True)],
        +)
        +async def test_create_view_exist_ok_preserves_server_metadata(
        +    asynchronous, exist_ok, existing
        +):
        +    flight = pytest.importorskip("pyarrow.flight")
        +    original_query = "SELECT 'original' AS original"
        +    submitted_query = (
        +        "SELECT 'replacement' AS replacement" if existing else original_query
        +    )
        +    schema = {
        +        "fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}],
        +        "metadata": {
        +            "lancedb::view::default_db": "analytics",
        +            "lancedb::view::default_namespace": "team",
        +        },
        +    }
        +    result = pa.table(
        +        {"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]}
        +    )
        +
        +    class ViewServer(flight.FlightServerBase):
        +        def __init__(self):
        +            super().__init__("grpc://127.0.0.1:0")
        +            self.requests = []
        +
        +        def do_get(self, context, ticket):
        +            self.requests.append(ticket.ticket)
        +            return flight.RecordBatchStream(result)
        +
        +    with ViewServer() as server:
        +        connection_options = {
        +            "api_key": "test-key",
        +            "host_override": "http://localhost:10024",
        +            "sql_host_override": f"grpc://127.0.0.1:{server.port}",
        +        }
        +        kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
        +        if asynchronous:
        +            db = await lancedb.connect_async("db://analytics", **connection_options)
        +            view = await db.create_view(
        +                "saved", submitted_query, namespace_path=["team"], **kwargs
        +            )
        +        else:
        +            db = lancedb.connect("db://analytics", **connection_options)
        +            view = db.create_view(
        +                "saved", submitted_query, namespace_path=["team"], **kwargs
        +            )
        +        (request,) = server.requests
        +
        +    prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW"
        +    assert f'{prefix} "saved" AS {submitted_query}'.encode() in request
        +    assert view.name == "saved"
        +    assert view.namespace_path == ["team"]
        +    assert view.default_namespace_path == ["team"]
        +    assert view.query == original_query
        +    assert view.schema.names == ["original"]
        diff --git a/python/python/tests/test_wal_hybrid.py b/python/python/tests/test_wal_hybrid.py
        index d5030f14e..372b1bd19 100644
        --- a/python/python/tests/test_wal_hybrid.py
        +++ b/python/python/tests/test_wal_hybrid.py
        @@ -120,7 +120,7 @@ def test_wal_hybrid_fuses_on_the_key_and_drops_it_again():
                 with_row_ids=True,
             )
             results = builder._finish_hybrid_results(
        -        combined, blob_mode="lazy", blob_sources={}
        +        combined, blob_mode="lazy", blob_sources={}, schema=None
             )
         
             assert "_rowid" not in results.column_names, "the surrogate is internal"
        diff --git a/python/python/tests/utils.py b/python/python/tests/utils.py
        index 7c4c30b71..cbc0ba02a 100644
        --- a/python/python/tests/utils.py
        +++ b/python/python/tests/utils.py
        @@ -36,6 +36,15 @@ def is_row_id_take(body) -> bool:
             return "_rowid" in (body.get("filter") or "")
         
         
        +def is_row_offset_take(body) -> bool:
        +    """True when a query body fetches specific rows by ``_rowoffset``.
        +
        +    This is the request shape ``Table.take_offsets`` sends on the remote
        +    backend, distinct from ``is_row_id_take``'s ``_rowid IN (...)``.
        +    """
        +    return "_rowoffset" in (body.get("filter") or "")
        +
        +
         def arrow_file_bytes(table: pa.Table) -> bytes:
             """Serialize to the Arrow IPC *file* framing the /query/ route answers with."""
             sink = pa.BufferOutputStream()
        @@ -51,21 +60,42 @@ class MockPermutationServer:
             the server, which is the part that has to stay compatible.
             """
         
        -    def __init__(self, name="remote_data", num_rows=8, vary_scan_order=False):
        +    def __init__(
        +        self, name="remote_data", num_rows=8, vary_scan_order=False, latest_version=1
        +    ):
                 self.name = name
                 self.num_rows = num_rows
        +        self.latest_version = latest_version
        +        self.version_rows = {1: list(range(num_rows))}
        +        self.describe_bodies = []
                 self.query_bodies = []
                 # Stand in for a distributed scan that answers in no fixed order.
                 self.vary_scan_order = vary_scan_order
                 self.scan_calls = 0
         
        +    def publish_version(self, version, row_ids):
        +        """Advance the mock's latest version without changing its schema."""
        +        self.latest_version = version
        +        self.version_rows[version] = list(row_ids)
        +
        +    def _rows_for_version(self, requested_version):
        +        version = (
        +            self.latest_version if requested_version is None else requested_version
        +        )
        +        return self.version_rows.get(version, self.version_rows[1])
        +
             def __call__(self, request):
                 path = request.path
                 if path == f"/v1/table/{self.name}/describe/":
        +            body = self._read_body(request)
        +            self.describe_bodies.append(body)
        +            version = (
        +                self.latest_version if body.get("version") is None else body["version"]
        +            )
                     return self._json(
                         request,
                         {
        -                    "version": 1,
        +                    "version": version,
                             "schema": {
                                 "fields": [
                                     {"name": "id", "type": {"type": "int64"}, "nullable": False}
        @@ -78,8 +108,8 @@ class MockPermutationServer:
                     # Null spec: this table has no RTE write path.
                     return self._json(request, {"rte_spec": None})
                 if path == f"/v1/table/{self.name}/count_rows/":
        -            self._read_body(request)
        -            return self._json(request, self.num_rows)
        +            body = self._read_body(request)
        +            return self._json(request, len(self._rows_for_version(body.get("version"))))
                 if path == f"/v1/table/{self.name}/query/":
                     return self._query(request, self._read_body(request))
         
        @@ -124,10 +154,15 @@ class MockPermutationServer:
         
             def _query(self, request, body):
                 self.query_bodies.append(body)
        +        version_rows = self._rows_for_version(body.get("version"))
         
                 if is_row_id_take(body):
                     # A row-id take. Answer ascending, so tests prove the client reorders.
        -            row_ids = sorted(parse_in_list(body["filter"]))
        +            row_ids = sorted(
        +                row_id
        +                for row_id in parse_in_list(body["filter"])
        +                if row_id in version_rows
        +            )
                     return self._arrow(
                         request,
                         pa.table(
        @@ -140,7 +175,7 @@ class MockPermutationServer:
         
                 if body.get("columns") == ["_rowid"]:
                     # The permutation build scan: row ids and nothing else.
        -            row_ids = list(range(self.num_rows))
        +            row_ids = list(version_rows)
                     if self.vary_scan_order and self.scan_calls % 2:
                         row_ids.reverse()
                     self.scan_calls += 1
        @@ -149,6 +184,37 @@ class MockPermutationServer:
                         pa.table({"_rowid": pa.array(row_ids, pa.uint64())}),
                     )
         
        +        if is_row_offset_take(body):
        +            # A _rowoffset take (2-phase's filtered block reads): this
        +            # table's rows are never deleted/reordered, so id == _rowoffset
        +            # for every row, same invariant as id == _rowid above.
        +            row_offsets = sorted(parse_in_list(body["filter"]))
        +            columns = body.get("columns") or ["id", "_rowoffset"]
        +            values = {"id": row_offsets, "_rowoffset": row_offsets}
        +            return self._arrow(
        +                request,
        +                pa.table(
        +                    {
        +                        col: pa.array(
        +                            values[col],
        +                            pa.uint64() if col == "_rowoffset" else pa.int64(),
        +                        )
        +                        for col in columns
        +                    }
        +                ),
        +            )
        +
        +        if body.get("columns") == ["_rowoffset"] and "IN" in (body.get("filter") or ""):
        +            # 2-phase's live-offset precompute scan: a user filter over
        +            # "_rowoffset" alone.  This mock only understands `
    • IN + # (...)` filters (not arbitrary SQL), and since id == _rowoffset + # for every row here, reuses parse_in_list regardless of which + # column the filter actually names. + row_offsets = sorted(parse_in_list(body["filter"])) + return self._arrow( + request, pa.table({"_rowoffset": pa.array(row_offsets, pa.uint64())}) + ) + # The schema probe: filtered to nothing, so it carries schema and no rows. return self._arrow(request, pa.table({"id": pa.array([], pa.int64())})) diff --git a/python/python/type_tests/connect.py b/python/python/type_tests/connect.py index eb2cba37c..6da32d2ec 100644 --- a/python/python/type_tests/connect.py +++ b/python/python/type_tests/connect.py @@ -4,12 +4,30 @@ from typing import assert_type import lancedb -from lancedb import AsyncConnection, DBConnection +from lancedb import AsyncCatalog, AsyncConnection, Catalog, DBConnection def check_connect_type() -> None: assert_type(lancedb.connect("memory://"), DBConnection) + assert_type( + lancedb.connect_catalog( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + Catalog, + ) async def check_connect_async_type() -> None: assert_type(await lancedb.connect_async("memory://"), AsyncConnection) + assert_type( + await lancedb.connect_catalog_async( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + AsyncCatalog, + ) diff --git a/python/src/arrow.rs b/python/src/arrow.rs index f0b4bceed..a4de3a911 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -2,15 +2,20 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::sync::Arc; +use std::time::Duration; use crate::error::PythonErrorExt; -use crate::runtime::future_into_py; +use crate::runtime::{block_on_interruptible, future_into_py}; use arrow::{ datatypes::SchemaRef, pyarrow::{IntoPyArrow, ToPyArrow}, + record_batch::{RecordBatchIterator, RecordBatchReader as ArrowRecordBatchReader}, +}; +use futures::{TryStreamExt, stream::StreamExt}; +use lancedb::{ + arrow::SendableRecordBatchStream, + query::{ExecutableQuery, QueryExecutionOptions}, }; -use futures::stream::StreamExt; -use lancedb::arrow::SendableRecordBatchStream; use pyo3::{ Bound, Py, PyAny, PyRef, PyResult, Python, exceptions::PyStopAsyncIteration, pyclass, pymethods, }; @@ -63,3 +68,66 @@ impl RecordBatchStream { }) } } + +/// Execute `query` and collect every batch in Rust before returning to Python. +/// +/// `to_arrow()` needs the complete table, so the default 1024-row output +/// slicing only adds work. Returning an Arrow C Stream reader also avoids a +/// Python future per batch while python materializes the table. +/// +/// The stream is collected inside the returned future, so timeout and +/// cancellation keep the same observable behavior as reading the stream from +/// Python: errors surface from the awaited call and dropping the future drops +/// the underlying stream. +pub fn execute_to_reader( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + future_into_py(py, async move { + let reader = collect_to_reader(query, max_batch_length, timeout).await?; + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) + }) +} + +/// Synchronous counterpart of [`execute_to_reader`]. +/// +/// The returned reader owns the collected batches; the caller converts it to +/// Python after reattaching to the interpreter. The wait releases the GIL and +/// keeps Python signal handlers on the calling thread. +pub fn execute_to_reader_sync( + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + block_on_interruptible(collect_to_reader(query, max_batch_length, timeout)) +} + +async fn collect_to_reader( + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + let mut options = QueryExecutionOptions::default(); + // `None` means the caller wants one eager result, not the core's + // default batch size. An explicit value is still honored. + options.max_batch_length = max_batch_length.unwrap_or(0); + options.timeout = timeout; + let stream = query.execute_with_options(options).await.infer_error()?; + let schema = stream.schema(); + let batches = stream.try_collect::>().await.infer_error()?; + Ok(Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + ))) +} diff --git a/python/src/catalog.rs b/python/src/catalog.rs index fb2e7e8a0..456d62a3c 100644 --- a/python/src/catalog.rs +++ b/python/src/catalog.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -127,7 +128,8 @@ impl DatabaseNames { } #[pyfunction] -#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None))] +#[allow(clippy::too_many_arguments)] +#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None, storage_options=None))] pub fn connect_catalog( py: Python<'_>, endpoint: String, @@ -136,6 +138,7 @@ pub fn connect_catalog( sql_host_override: Option, read_consistency_interval: Option, oauth_config: Option, + storage_options: Option>, ) -> PyResult> { let interval = read_consistency_interval .map(Duration::try_from_secs_f64) @@ -151,6 +154,9 @@ pub fn connect_catalog( if let Some(config) = client_config { builder = builder.client_config(config.into()); } + if let Some(options) = storage_options { + builder = builder.storage_options(options); + } if let Some(endpoint) = sql_host_override { builder = builder.sql_host_override(endpoint); } diff --git a/python/src/connection.rs b/python/src/connection.rs index d88991235..75878cf0e 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -20,20 +20,176 @@ use arrow::{ pyarrow::{FromPyArrow, PyArrowType, ToPyArrow}, }; use lancedb::{ + BasePath, connection::Connection as LanceConnection, connection::NamespaceClientPushdownOperation, database::namespace::LanceNamespaceDatabase, - database::{CreateTableMode, Database, ReadConsistency}, - function::GpuClass as LanceGpuClass, + database::{CreateTableMode, Database, JobListFilter, JobListState, ReadConsistency}, + function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, + materialized_view::CreateMaterializedViewBuilder, }; use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, - exceptions::{PyRuntimeError, PyValueError}, + exceptions::{PyRuntimeError, PyTypeError, PyValueError}, pyclass, pyfunction, pymethods, - types::{PyAnyMethods, PyDict, PyDictMethods, PyList}, + types::{PyAnyMethods, PyBool, PyDict, PyDictMethods, PyList}, }; +fn materialized_view_builder( + connection: &LanceConnection, + name: String, + source: Option, + query: Option, + has_clauses: bool, +) -> PyResult { + match (source, query) { + (None, Some(query)) if !has_clauses => { + Ok(connection.create_materialized_view_from_query(name, query)) + } + (Some(source), None) => Ok(connection.create_materialized_view(name, source)), + (None, None) => Err(PyValueError::new_err( + "either source or query must be provided", + )), + _ => Err(PyValueError::new_err( + "query cannot be combined with source, select, where or limit", + )), + } +} + +/// Parse `initial_bases` into Lance base paths. +/// +/// Accepts LanceDB's lightweight `BasePath`, a mapping with the same keys, or +/// a duck-typed `lance.DatasetBasePath`. `None` maps to no bases. Object +/// attributes follow `DatasetBasePath`: a reported `id` of `0` means +/// automatic assignment, while a mapping that sets `id=0` explicitly is +/// rejected because `0` is reserved for unregistered blob URIs. Explicit +/// non-zero ids must be unique. +fn parse_initial_bases(initial_bases: Option>) -> PyResult>> { + let Some(value) = initial_bases else { + return Ok(None); + }; + if value.is_none() { + return Ok(None); + } + + let mut bases = Vec::new(); + let mut explicit_ids: HashSet = HashSet::new(); + for (index, item) in value.try_iter()?.enumerate() { + let item = item?; + let base = parse_base_path(&item, index)?; + if base.id != 0 && !explicit_ids.insert(base.id) { + return Err(PyValueError::new_err(format!( + "initial_bases[{index}] reuses base id {}; explicit ids must be unique", + base.id + ))); + } + bases.push(base); + } + Ok(Some(bases)) +} + +fn parse_base_path(item: &Bound<'_, PyAny>, index: usize) -> PyResult { + let (path, name, is_dataset_root, id) = if let Ok(dict) = item.cast::() { + let path = required_string(dict.get_item("path")?, index, "path")?; + let name = optional_string(dict.get_item("name")?, index, "name")?; + let is_dataset_root = + optional_bool(dict.get_item("is_dataset_root")?, index, "is_dataset_root")?; + let id = match dict.get_item("id")? { + None => 0, + Some(value) if value.is_none() => 0, + Some(value) => { + let id = base_id(&value, index)?; + if id == 0 { + return Err(PyValueError::new_err(format!( + "initial_bases[{index}] sets id=0, which is reserved for unregistered \ + blob URIs; pass id=None to let Lance assign an ID" + ))); + } + id + } + }; + (path, name, is_dataset_root, id) + } else { + let path = item.getattr("path").map_err(|_| { + PyTypeError::new_err(format!( + "initial_bases[{index}] must be a BasePath, dict, or DatasetBasePath" + )) + })?; + let path = required_string(Some(path), index, "path")?; + let name = item.getattr("name").ok().filter(|value| !value.is_none()); + let name = optional_string(name, index, "name")?; + let is_dataset_root = match item.getattr("is_dataset_root") { + Ok(value) if !value.is_none() => value.extract::().map_err(|_| { + PyTypeError::new_err(format!( + "initial_bases[{index}].is_dataset_root must be a bool" + )) + })?, + _ => false, + }; + let id = match item.getattr("id") { + Ok(value) if !value.is_none() => base_id(&value, index)?, + _ => 0, + }; + (path, name, is_dataset_root, id) + }; + + if path.is_empty() { + return Err(PyValueError::new_err(format!( + "initial_bases[{index}].path must not be empty" + ))); + } + Ok(BasePath::new(id, path, name, is_dataset_root)) +} + +fn required_string(value: Option>, index: usize, field: &str) -> PyResult { + let Some(value) = value else { + return Err(PyValueError::new_err(format!( + "initial_bases[{index}] is missing '{field}'" + ))); + }; + value.extract::().map_err(|_| { + PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string")) + }) +} + +fn optional_string( + value: Option>, + index: usize, + field: &str, +) -> PyResult> { + match value { + None => Ok(None), + Some(value) if value.is_none() => Ok(None), + Some(value) => value.extract::().map(Some).map_err(|_| { + PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string")) + }), + } +} + +fn optional_bool(value: Option>, index: usize, field: &str) -> PyResult { + match value { + None => Ok(false), + Some(value) if value.is_none() => Ok(false), + Some(value) => value.extract::().map_err(|_| { + PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a bool")) + }), + } +} + +fn base_id(value: &Bound<'_, PyAny>, index: usize) -> PyResult { + if value.is_instance_of::() { + return Err(PyTypeError::new_err(format!( + "initial_bases[{index}].id must be a positive integer, not a bool" + ))); + } + value.extract::().map_err(|_| { + PyValueError::new_err(format!( + "initial_bases[{index}].id must be a positive integer that fits in a u32" + )) + }) +} + #[pyclass] pub struct Connection { inner: Option, @@ -219,19 +375,29 @@ impl Connection { self.get_inner().map(|inner| inner.uri().to_string()) } - #[pyo3(signature = (query, *, default_namespace_path=None, parameters=None))] + #[pyo3(signature = (query, *, default_namespace_path=None, parameters=None, timeout=None, read_timeout=None, cancel_on_drop=false))] pub fn execute_query_async<'a>( self_: PyRef<'a, Self>, query: String, default_namespace_path: Option>, parameters: Option>, + timeout: Option, + read_timeout: Option, + cancel_on_drop: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let default_namespace_path = parse_default_namespace_path(default_namespace_path)?; future_into_py(self_.py(), async move { let mut operation = inner .execute_query_async(query) - .default_namespace_path(default_namespace_path); + .default_namespace_path(default_namespace_path) + .cancel_on_drop(cancel_on_drop); + if let Some(timeout) = timeout { + operation = operation.timeout(timeout); + } + if let Some(timeout) = read_timeout { + operation = operation.read_timeout(timeout); + } if let Some(PyArrowType(parameters)) = parameters { operation = operation.parameters(parameters); } @@ -289,7 +455,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None))] + #[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None, allow_external_blob_outside_bases=false))] pub fn create_table<'a>( self_: PyRef<'a, Self>, name: String, @@ -299,11 +465,14 @@ impl Connection { storage_options: Option>, location: Option, namespace_client: Option>, + initial_bases: Option>, + allow_external_blob_outside_bases: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let py = self_.py(); let mode = Self::parse_create_mode_str(mode)?; + let initial_bases = parse_initial_bases(initial_bases)?; let batches: Box = Box::new(ArrowArrayStreamReader::from_pyarrow_bound(&data)?); @@ -311,6 +480,12 @@ impl Connection { let ns_path = namespace_path.clone().unwrap_or_default(); let mut builder = inner.create_table(name.clone(), batches).mode(mode); + if let Some(bases) = initial_bases { + builder = builder.initial_bases(bases); + } + if allow_external_blob_outside_bases { + builder = builder.allow_external_blob_outside_bases(true); + } builder = builder.namespace(ns_path.clone()); if let Some(storage_options) = storage_options { builder = builder.storage_options(storage_options); @@ -337,7 +512,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None))] + #[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None))] pub fn create_empty_table<'a>( self_: PyRef<'a, Self>, name: String, @@ -347,11 +522,13 @@ impl Connection { storage_options: Option>, location: Option, namespace_client: Option>, + initial_bases: Option>, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let py = self_.py(); let mode = Self::parse_create_mode_str(mode)?; + let initial_bases = parse_initial_bases(initial_bases)?; let schema = Schema::from_pyarrow_bound(&schema)?; @@ -360,6 +537,9 @@ impl Connection { .create_empty_table(name.clone(), Arc::new(schema)) .mode(mode); + if let Some(bases) = initial_bases { + builder = builder.initial_bases(bases); + } builder = builder.namespace(ns_path.clone()); if let Some(storage_options) = storage_options { builder = builder.storage_options(storage_options); @@ -435,7 +615,8 @@ impl Connection { }) } - #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true, *, exist_ok=false))] pub fn clone_table( self_: PyRef<'_, Self>, target_table_name: String, @@ -444,6 +625,7 @@ impl Connection { source_version: Option, source_tag: Option, is_shallow: bool, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); @@ -455,7 +637,7 @@ impl Connection { if let Some(tag) = source_tag { builder = builder.source_tag(tag); } - builder = builder.is_shallow(is_shallow); + builder = builder.is_shallow(is_shallow).exist_ok(exist_ok); future_into_py(self_.py(), async move { let table = builder.execute().await.infer_error()?; @@ -483,27 +665,58 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None, *, query=None, exist_ok=false))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, + + query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } if let Some(seconds) = auto_refresh_interval_seconds { builder = builder.auto_refresh_interval_seconds(seconds); } + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); + } + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); + } + if let Some(value) = total_gpu_count { + builder = builder.total_gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } + if let Some(projections) = projections { builder = builder.select(projections); } @@ -520,27 +733,58 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None, *, query=None, exist_ok=false))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, + + query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } if let Some(seconds) = auto_refresh_interval_seconds { builder = builder.auto_refresh_interval_seconds(seconds); } + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); + } + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); + } + if let Some(value) = total_gpu_count { + builder = builder.total_gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } + if let Some(projections) = projections { builder = builder.select(projections); } @@ -854,19 +1098,40 @@ impl Connection { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let job = inner.open_job(&job_id).await.infer_error()?; - Ok(crate::job::Job::new(job)) + match job.job_type().as_deref() { + Some("function_refresh" | "computed_refresh" | "refresh_column") => { + Ok(crate::job::Job::new_typed( + job.into_typed::().infer_error()?, + )) + } + Some("prewarm_page_cache") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), + Some("cleanup") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), + Some("compact") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), + _ => Ok(crate::job::Job::new(job)), + } }) } - #[pyo3(signature = (request_json, namespace_path=None))] + #[pyo3(signature = (request_json, namespace_path=None, *, exist_ok=false))] pub fn create_function_async( self_: PyRef<'_, Self>, request_json: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); - let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) + let mut request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) .infer_error()?; + request.exist_ok = exist_ok; let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner @@ -877,22 +1142,22 @@ impl Connection { }) } - #[pyo3(signature = (name, version, namespace_path=None))] + #[pyo3(signature = (name, version=None, namespace_path=None))] pub fn get_function( self_: PyRef<'_, Self>, name: String, - version: String, + version: Option, namespace_path: Option>, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { - inner - .get_function(name, version, &namespace_path) - .await - .infer_error()? - .to_canonical_json() - .infer_error() + let function = match version { + Some(version) => inner.get_function(name, version, &namespace_path).await, + None => inner.get_function_latest(name, &namespace_path).await, + } + .infer_error()?; + function.to_canonical_json().infer_error() }) } @@ -928,6 +1193,23 @@ impl Connection { }) } + #[pyo3(signature = (name, version, namespace_path=None))] + pub fn _drop_function_with_warnings( + self_: PyRef<'_, Self>, + name: String, + version: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let namespace_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + inner + .drop_function_with_warnings(name, version, &namespace_path) + .await + .infer_error() + }) + } + #[pyo3(signature = (name, version, namespace_path=None))] pub fn drop_function_async( self_: PyRef<'_, Self>, @@ -1012,18 +1294,20 @@ impl Connection { }) } - #[pyo3(signature = (name, value, namespace_path=None))] + #[pyo3(signature = (name, value, namespace_path=None, *, exist_ok=false))] pub fn create_secret( self_: PyRef<'_, Self>, name: String, value: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner .create_secret(name, value, &namespace_path) + .exist_ok(exist_ok) .await .infer_error() }) @@ -1094,18 +1378,20 @@ impl Connection { }) } - #[pyo3(signature = (name, query, namespace_path=None))] + #[pyo3(signature = (name, query, namespace_path=None, *, exist_ok=false))] pub fn create_view( self_: PyRef<'_, Self>, name: String, query: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { let view = inner .create_view(name, query, &namespace_path) + .exist_ok(exist_ok) .await .infer_error()?; view_description_to_py(view) @@ -1247,18 +1533,58 @@ impl Connection { )) } - #[pyo3(signature = (*, page_token=None, page_limit=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (*, page_token=None, page_limit=None, table=None, namespace_path=None, state=None, job_type=None, job_types=None, created_at_gte_millis=None, created_at_lt_millis=None))] pub fn list_jobs( &self, page_token: Option, page_limit: Option, + table: Option, + namespace_path: Option>, + state: Option, + job_type: Option, + job_types: Option>, + created_at_gte_millis: Option, + created_at_lt_millis: Option, ) -> PyResult { + if job_type.is_some() && job_types.is_some() { + return Err(PyValueError::new_err( + "set only one of job_type and job_types", + )); + } + let mut filter = JobListFilter::default(); + filter.table = table; + filter.namespace_path = namespace_path.unwrap_or_default(); + filter.state = state + .as_deref() + .map(|state| match state { + "in_progress" => Ok(JobListState::InProgress), + "succeeded" => Ok(JobListState::Succeeded), + "failed" => Ok(JobListState::Failed), + "canceled" => Ok(JobListState::Canceled), + "timed_out" => Ok(JobListState::TimedOut), + _ => Err(PyValueError::new_err( + "state must be one of: in_progress, succeeded, failed, canceled, timed_out", + )), + }) + .transpose()?; + filter.job_types = job_types.unwrap_or_else(|| job_type.into_iter().collect()); + filter.created_at_gte_millis = created_at_gte_millis; + filter.created_at_lt_millis = created_at_lt_millis; Ok(crate::listing::JobListing::new( self.get_inner()? - .list_jobs(crate::listing::options(page_token, page_limit)), + .list_jobs_filtered(filter, crate::listing::options(page_token, page_limit)), )) } + pub fn server_info(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let info = inner.server_info().await.infer_error()?; + serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string())) + }) + } + pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { diff --git a/python/src/error.rs b/python/src/error.rs index a86051e5d..1ac9f7ac3 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -168,6 +168,28 @@ impl PythonErrorExt for std::result::Result { err.setattr(intern!(py, "__cause__"), cause_err)?; Err(PyErr::from_value(err)) }), + LanceError::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } => Python::attach(|py| { + let error = py + .import(intern!(py, "lancedb.remote.errors"))? + .getattr(intern!(py, "ResponseInterruptedError"))? + .call1(( + err.to_string(), + request_id, + *batches, + *rows, + *table_version, + is_transport_error(&**source), + ))?; + let cause = http_from_rust_error(py, &**source, request_id, None)?; + error.setattr(intern!(py, "__cause__"), cause)?; + Err(PyErr::from_value(error)) + }), LanceError::Sql { message, request_id, @@ -310,6 +332,9 @@ fn new_py_sql_error<'py>( grpc_code: i32, metadata: &RemoteErrorMetadata, ) -> PyResult> { + if sql_has_resource_error(metadata, grpc_code) { + return new_py_sql_resource_error(py, message, request_id, grpc_code, metadata); + } py.import("lancedb.remote.errors")? .getattr("SqlError")? .call1(( @@ -322,6 +347,51 @@ fn new_py_sql_error<'py>( )) } +fn new_py_sql_resource_error<'py>( + py: Python<'py>, + message: &str, + request_id: &str, + grpc_code: i32, + metadata: &RemoteErrorMetadata, +) -> PyResult> { + let resource = metadata.resource.as_ref().unwrap(); + py.import("lancedb.remote.errors")? + .getattr("HttpError")? + .call1(( + message, + request_id, + grpc_code_to_http_status(grpc_code), + metadata.error_code.as_deref(), + resource.kind.as_str(), + resource.name.as_str(), + resource.namespace_path.clone(), + false, + metadata.job_id.as_deref(), + metadata.job_request_id.as_deref(), + )) +} + +fn sql_has_resource_error(metadata: &RemoteErrorMetadata, grpc_code: i32) -> bool { + metadata.resource.is_some() + && matches!( + (metadata.error_code.as_deref(), grpc_code), + // These are gRPC status codes, not HTTP status codes. + (Some("not_found"), 5) | (Some("already_exists"), 6) + ) +} + +fn grpc_code_to_http_status(grpc_code: i32) -> Option { + match grpc_code { + 3 => Some(400), + 5 => Some(404), + 6 => Some(409), + 7 => Some(403), + 9 => Some(400), + 12 => Some(501), + _ => None, + } +} + // Preserve the typed transport classification across the Python boundary. // A missing status code alone also covers malformed job responses, which // waiting longer cannot repair. @@ -335,3 +405,243 @@ fn is_transport_error(err: &(dyn std::error::Error + 'static)) -> bool { } err.source().is_some_and(is_transport_error) } + +#[cfg(test)] +mod tests { + use std::ffi::CString; + use std::sync::{Arc, Once}; + + use lancedb::error::{JobFailure, RemoteResourceIdentity}; + use pyo3::types::{PyAnyMethods, PyModule}; + + use super::*; + + static INSTALL_PYTHON_ERROR_MODULES: Once = Once::new(); + + fn install_python_error_modules(py: Python<'_>) -> PyResult<()> { + // Load the checked-in error classes without requiring an installed wheel. + // The namespace exception is only a base for an unrelated remote class. + PyModule::from_code( + py, + c"import sys\n\nimport types\n\n\ + lancedb = types.ModuleType('lancedb')\n\ + lancedb.__path__ = []\n\ + lancedb_remote = types.ModuleType('lancedb.remote')\n\ + lancedb_remote.__path__ = []\n\ + lancedb.remote = lancedb_remote\n\ + namespace = types.ModuleType('lance_namespace')\n\ + namespace_errors = types.ModuleType('lance_namespace.errors')\n\ + namespace_errors.TableNotFoundError = RuntimeError\n\ + namespace.errors = namespace_errors\n\ + sys.modules['lancedb'] = lancedb\n\ + sys.modules['lancedb.remote'] = lancedb_remote\n\ + sys.modules['lance_namespace'] = namespace\n\ + sys.modules['lance_namespace.errors'] = namespace_errors", + c"error_test_bootstrap.py", + c"lancedb_error_test_bootstrap", + )?; + + let exceptions_code = + CString::new(include_str!("../../python/python/lancedb/exceptions.py")).unwrap(); + let exceptions = PyModule::from_code( + py, + &exceptions_code, + c"exceptions.py", + c"lancedb.exceptions", + )?; + let lancedb = py.import("lancedb")?; + lancedb.setattr("exceptions", &exceptions)?; + py.import("sys")? + .getattr("modules")? + .set_item("lancedb.exceptions", &exceptions)?; + + let remote_errors_code = + CString::new(include_str!("../../python/python/lancedb/remote/errors.py")).unwrap(); + let remote_errors = PyModule::from_code( + py, + &remote_errors_code, + c"remote/errors.py", + c"lancedb.remote.errors", + )?; + lancedb + .getattr("remote")? + .setattr("errors", &remote_errors)?; + py.import("sys")? + .getattr("modules")? + .set_item("lancedb.remote.errors", &remote_errors)?; + Ok(()) + } + + fn ensure_python_error_modules() { + Python::initialize(); + // Once waits without holding the GIL; only its one-time closure attaches. + INSTALL_PYTHON_ERROR_MODULES.call_once(|| { + Python::attach(install_python_error_modules).unwrap(); + }); + } + + #[test] + fn generic_job_failure_retains_the_named_resource_as_its_cause() { + ensure_python_error_modules(); + let source = LanceError::Sql { + message: "Function 'missing' was not found".into(), + request_id: "current-request".into(), + grpc_code: 5, + metadata: Box::new({ + let mut metadata = RemoteErrorMetadata::default(); + metadata.error_code = Some("not_found".into()); + metadata.job_id = Some("outer-job".into()); + metadata.job_request_id = Some("worker-request".into()); + metadata.resource = Some(RemoteResourceIdentity::new( + "function", + "missing", + vec!["ns".into()], + )); + metadata + }), + }; + let error = LanceError::JobFailed { + job_id: Some("outer-job".into()), + failure: Box::new(JobFailure { + message: Some("Function 'missing' was not found".into()), + traceback: None, + sql_job_id: Some("outer-job".into()), + source: Some(Arc::new(source)), + ..Default::default() + }), + }; + + let py_err = Python::attach(|_| { + let result: std::result::Result<(), LanceError> = Err(error); + result.infer_error().unwrap_err() + }); + Python::attach(|py| { + let value = py_err.value(py); + let job_failed = py + .import("lancedb.exceptions") + .unwrap() + .getattr("JobFailedError") + .unwrap(); + assert!(value.is_instance(&job_failed).unwrap(), "{py_err:?}"); + let cause = value.getattr("__cause__").unwrap(); + let function_not_found = py + .import("lancedb.remote.errors") + .unwrap() + .getattr("FunctionNotFoundError") + .unwrap(); + assert!( + cause.is_instance(&function_not_found).unwrap(), + "{py_err:?}" + ); + assert_eq!( + cause + .getattr("error_code") + .unwrap() + .extract::() + .unwrap(), + "not_found" + ); + assert_eq!( + cause + .getattr("resource_kind") + .unwrap() + .extract::() + .unwrap(), + "function" + ); + assert_eq!( + cause + .getattr("resource_name") + .unwrap() + .extract::() + .unwrap(), + "missing" + ); + assert_eq!( + cause + .getattr("namespace_path") + .unwrap() + .extract::>() + .unwrap(), + ["ns"] + ); + assert_eq!( + cause + .getattr("status_code") + .unwrap() + .extract::() + .unwrap(), + 404 + ); + assert_eq!( + cause + .getattr("request_id") + .unwrap() + .extract::() + .unwrap(), + "current-request" + ); + assert_eq!( + cause + .getattr("job_id") + .unwrap() + .extract::() + .unwrap(), + "outer-job" + ); + assert_eq!( + cause + .getattr("job_request_id") + .unwrap() + .extract::() + .unwrap(), + "worker-request" + ); + }); + } + + #[test] + fn direct_catalog_lookup_is_raised_as_the_named_resource_error() { + ensure_python_error_modules(); + for (kind, name, namespace_path, exception) in [ + ( + "function", + "missing", + vec!["ns".into()], + "FunctionNotFoundError", + ), + ("namespace", "ns", Vec::new(), "NamespaceNotFoundError"), + ] { + let mut metadata = RemoteErrorMetadata::default(); + metadata.error_code = Some("not_found".into()); + metadata.resource = Some(RemoteResourceIdentity::new(kind, name, namespace_path)); + let error = LanceError::Sql { + message: format!("{kind} '{name}' was not found"), + request_id: "current-request".into(), + grpc_code: 5, + metadata: Box::new(metadata), + }; + let py_err = Python::attach(|_| { + let result: std::result::Result<(), LanceError> = Err(error); + result.infer_error().unwrap_err() + }); + Python::attach(|py| { + let value = py_err.value(py); + let class = py + .import("lancedb.remote.errors") + .unwrap() + .getattr(exception) + .unwrap(); + assert!(value.is_instance(&class).unwrap(), "{py_err:?}"); + assert_eq!( + value + .getattr("resource_name") + .unwrap() + .extract::() + .unwrap(), + name + ); + }); + } + } +} diff --git a/python/src/expr.rs b/python/src/expr.rs index bb779bc1d..c4c7cbbb1 100644 --- a/python/src/expr.rs +++ b/python/src/expr.rs @@ -164,9 +164,12 @@ pub fn expr_col(name: &str) -> PyExpr { /// Create a literal value expression. /// /// Supported Python types: `bool`, `int`, `float`, `str`, `bytes`, `date`, -/// `datetime`, `Decimal`. +/// `datetime`, `Decimal`, and `None` (SQL NULL). #[pyfunction] pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult { + if value.is_none() { + return Ok(PyExpr(df_lit(ScalarValue::Null))); + } // bool must be checked before int because bool is a subclass of int in Python if let Ok(b) = value.extract::() { return Ok(PyExpr(df_lit(b))); @@ -174,6 +177,9 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult { if let Ok(i) = value.extract::() { return Ok(PyExpr(df_lit(i))); } + if let Ok(i) = value.extract::() { + return Ok(PyExpr(df_lit(i))); + } // Decimal must be checked before f64: Python's Decimal implements __float__, // so value.extract::() would succeed and silently truncate the value to // f64, losing precision. Build a Decimal128 scalar to preserve it instead. diff --git a/python/src/index.rs b/python/src/index.rs index 3ec03b6fd..1941e3f10 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -7,9 +7,10 @@ use lancedb::index::vector::{ IvfPqIndexBuilder, IvfRqIndexBuilder, IvfSqIndexBuilder, }; use lancedb::index::{ - Index as LanceDbIndex, + Index as LanceDbIndex, IndexType, scalar::{ BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder, + PluginIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder, }, }; use pyo3::IntoPyObject; @@ -117,6 +118,26 @@ pub fn extract_index_params(source: &Option>) -> PyResult Ok(LanceDbIndex::LabelList(Default::default())), "Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())), "NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())), + "ZoneMap" => Ok(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default())), + "RTree" => { + let params = source.extract::()?; + let mut builder = RTreeIndexBuilder::default(); + if let Some(page_size) = params.page_size { + builder = builder + .page_size(page_size) + .map_err(|err| PyValueError::new_err(err.to_string()))?; + } + Ok(LanceDbIndex::RTree(builder)) + } + "ScalarPlugin" => { + let params = source.extract::()?; + let invalid = |err: lancedb::Error| PyValueError::new_err(err.to_string()); + let mut builder = PluginIndexBuilder::new(params.index_type).map_err(invalid)?; + if let Some(json) = params.params_json { + builder = builder.params_json(json).map_err(invalid)?; + } + Ok(LanceDbIndex::Plugin(builder)) + } "FTS" => { let params = source.extract::()?; let code_options = CodeAnalyzerOptions { @@ -291,7 +312,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult Err(PyValueError::new_err(format!( - "Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat", + "Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat", not_supported ))), } @@ -300,6 +321,13 @@ pub fn extract_index_params(source: &Option>) -> PyResult, +} + #[derive(FromPyObject)] struct FtsParams { with_position: bool, @@ -325,6 +353,11 @@ struct FtsParams { index_operators: Option, } +#[derive(FromPyObject)] +struct RTreeParams { + page_size: Option, +} + #[derive(FromPyObject)] struct IvfFlatParams { distance_type: String, @@ -537,7 +570,12 @@ fn parse_index_details(py: Python<'_>, s: String) -> Py { impl IndexConfig { pub fn from_lancedb(py: Python<'_>, value: lancedb::index::IndexConfig) -> Self { - let index_type = format!("{:?}", value.index_type); + // A registered plugin's type is its display name, such as "MinHashLsh", + // which `Debug` would render as `Custom("MinHashLsh")`. + let index_type = match value.index_type { + IndexType::Custom(name) => name, + index_type => format!("{index_type:?}"), + }; Self { index_type, columns: value.columns, diff --git a/python/src/job.rs b/python/src/job.rs index aa4d8890f..c5ce9e60b 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -2,16 +2,20 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::sync::Arc; +use std::time::Duration; use crate::runtime::future_into_py; use arrow::{ datatypes::Schema, pyarrow::{IntoPyArrow, Table as PyArrowTable}, }; -use lancedb::job::JobEventsRequest; +use lancedb::job::{ + FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions, + JobEventsRequest, +}; use pyo3::{ Bound, Py, PyAny, PyRef, PyResult, Python, - exceptions::PyValueError, + exceptions::{PyTimeoutError, PyValueError}, pyclass, pymethods, types::{PyAnyMethods, PyDict, PyDictMethods}, }; @@ -21,6 +25,17 @@ use crate::error::PythonErrorExt; const REPR_INDENT: &str = " "; +fn profile_json(result: lancedb::Result) -> PyResult { + let profile = result.infer_error()?; + serde_json::to_string(&profile) + .map_err(|error| PyValueError::new_err(format!("invalid profile metadata: {error}"))) +} + +fn profile_duration(seconds: f64) -> PyResult { + Duration::try_from_secs_f64(seconds) + .map_err(|_| PyValueError::new_err("profile durations must be finite and nonnegative")) +} + /// Parse a stored JSON payload into Python data. The bindings carry these as /// strings because that is what crosses the boundary cheaply; the public /// Python surface is the parsed form. @@ -81,6 +96,43 @@ impl Job { self.inner.id().map(str::to_string) } + #[getter] + pub fn job_id(&self) -> Option { + self.inner.job_id() + } + + #[getter] + pub fn operation_id(&self) -> Option { + self.inner.operation_id() + } + + #[getter] + pub fn attempt(&self) -> Option { + self.inner.attempt() + } + + #[getter] + pub fn retry_of(&self) -> Option { + self.inner.retry_of() + } + + #[getter] + pub fn lifecycle_state(&self) -> Option { + self.inner + .lifecycle_state() + .map(|state| state.as_str().to_string()) + } + + #[getter] + pub fn source_table_version(&self) -> Option { + self.inner.source_table_version() + } + + #[getter] + pub fn execution_epoch(&self) -> Option { + self.inner.execution_epoch() + } + #[getter] pub fn job_type(&self) -> Option { self.inner.job_type() @@ -132,6 +184,15 @@ impl Job { }) } + pub fn retry(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(Self { + inner: Arc::new(inner.retry().await.infer_error()?), + }) + }) + } + pub fn refresh(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -152,14 +213,105 @@ impl Job { self.inner.description().map(JobDescription::from) } - #[pyo3(signature = (*, limit=None, filter=None))] + pub fn timeline(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(inner.timeline().await.infer_error()?.to_string()) + }) + } + + pub fn stack(self_: PyRef<'_, Self>, worker_id: String) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(inner.stack(worker_id).await.infer_error()?.to_string()) + }) + } + + #[pyo3(signature = (worker_id, *, kind="cpu", duration_seconds=None, session_slot=0))] + pub fn capture_profile<'py>( + self_: PyRef<'py, Self>, + worker_id: String, + kind: &str, + duration_seconds: Option, + session_slot: usize, + ) -> PyResult> { + let kind: FunctionProfileKind = serde_json::from_value(serde_json::json!(kind)) + .map_err(|_| PyValueError::new_err("kind must be 'cpu', 'memory' or 'gpu'"))?; + let mut options = FunctionProfileOptions::new(kind).session_slot(session_slot); + if let Some(seconds) = duration_seconds { + options = options.duration(profile_duration(seconds)?); + } + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + profile_json(inner.capture_profile(worker_id, options).await) + }) + } + + pub fn profile_status( + self_: PyRef<'_, Self>, + profile_id: String, + ) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + profile_json(inner.profile_status(profile_id).await) + }) + } + + #[pyo3(signature = (profile_id, *, timeout_seconds=None, poll_interval_seconds=None))] + pub fn wait_for_profile( + self_: PyRef<'_, Self>, + profile_id: String, + timeout_seconds: Option, + poll_interval_seconds: Option, + ) -> PyResult> { + let mut options = FunctionProfileWaitOptions::new(); + if let Some(seconds) = timeout_seconds { + options = options.timeout(profile_duration(seconds)?); + } + if let Some(seconds) = poll_interval_seconds { + options = options.poll_interval(profile_duration(seconds)?); + } + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + match inner.wait_for_profile(profile_id, options).await { + Err(lancedb::Error::Timeout { message }) => Err(PyTimeoutError::new_err(message)), + result => profile_json(result), + } + }) + } + + pub fn profile_artifact( + self_: PyRef<'_, Self>, + profile_id: String, + ) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(inner + .profile_artifact(profile_id) + .await + .infer_error()? + .to_string()) + }) + } + + pub fn stats(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { inner.stats().await.infer_error() }) + } + + #[pyo3(signature = (*, limit=None, filter=None, page_token=None))] pub fn events( self_: PyRef<'_, Self>, limit: Option, filter: Option, + page_token: Option, ) -> PyResult> { let inner = self_.inner.clone(); - let request = JobEventsRequest { limit, filter }; + let request = JobEventsRequest { + limit, + filter, + page_token, + }; future_into_py(self_.py(), async move { let batches = inner.events(request).await.infer_error()?; Python::attach(|py| { @@ -184,6 +336,18 @@ pub struct JobInfo { job_type: String, state: String, created_at_millis: i64, + /// Terminal timestamp in milliseconds since the epoch, when known. + completed_at_millis: Option, + /// Creation-to-completion wall time, including queueing and pauses. + duration_millis: Option, + /// Affected columns; empty when unavailable or not column-scoped. + columns: Vec, + /// Pinned Function catalog name, with namespace segments joined by `$`. + function_name: Option, + /// Pinned Function version, when known. + function_version: Option, + /// Durable failure summary, when available. + failure: Option, _progress_json: Option, paused: bool, } @@ -220,6 +384,12 @@ impl From for JobInfo { job_type: info.job_type, state: info.state, created_at_millis: info.created_at_millis, + completed_at_millis: info.completed_at_millis, + duration_millis: info.duration_millis, + columns: info.columns, + function_name: info.function_name, + function_version: info.function_version, + failure: info.failure.map(Into::into), _progress_json: Some(progress), paused: info.paused, } @@ -228,14 +398,28 @@ impl From for JobInfo { /// The server's account of why a job failed. #[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)] -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct JobFailureInfo { phase: Option, message: Option, + /// User-code traceback, possibly truncated by the server. + traceback: Option, retryable: Option, sql_job_id: Option, } +impl From for JobFailureInfo { + fn from(failure: lancedb::error::JobFailure) -> Self { + Self { + phase: failure.phase, + message: failure.message, + traceback: failure.traceback, + retryable: failure.retryable, + sql_job_id: failure.sql_job_id, + } + } +} + #[pymethods] impl JobFailureInfo { fn __repr__(&self) -> String { @@ -268,6 +452,13 @@ impl JobFailureInfo { #[derive(Clone)] pub struct JobDescription { job_id: String, + attempt_job_id: Option, + operation_id: Option, + attempt: Option, + retry_of: Option, + lifecycle_state: Option, + source_table_version: Option, + execution_epoch: Option, job_type: String, state: String, creation_ms: i64, @@ -330,6 +521,15 @@ impl From for JobDescription { let progress_json = description.progress_snapshot().to_string(); Self { job_id: description.job_id, + attempt_job_id: description.attempt_job_id, + operation_id: description.operation_id, + attempt: description.attempt, + retry_of: description.retry_of, + lifecycle_state: description + .lifecycle_state + .map(|state| state.as_str().to_string()), + source_table_version: description.source_table_version, + execution_epoch: description.execution_epoch, job_type: description.job_type, state: description.state, creation_ms: description.creation_ms, @@ -339,12 +539,7 @@ impl From for JobDescription { .filter(|result| !result.is_null()) .map(|result| result.to_string()), _progress_json: Some(progress_json), - failure: description.failure.map(|failure| JobFailureInfo { - phase: failure.phase, - message: failure.message, - retryable: failure.retryable, - sql_job_id: failure.sql_job_id, - }), + failure: description.failure.map(Into::into), } } } diff --git a/python/src/lib.rs b/python/src/lib.rs index 0690d9622..4680aab4c 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -16,9 +16,10 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery}; use session::Session; use table::{ AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken, - FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, MergeResult, PyBlobFile, - RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, Table, - UpdateFieldMetadataResult, UpdateResult, + FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, + FunctionColumnVersionStatus, FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, + MergeResult, PyBlobFile, RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, + Table, UpdateFieldMetadataResult, UpdateResult, }; pub mod arrow; @@ -39,6 +40,7 @@ pub mod query; pub mod runtime; pub mod session; pub mod sql; +mod sync_stream; pub mod table; pub mod util; @@ -96,6 +98,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(catalog::connect_catalog, m)?)?; m.add_class::()?; m.add_class::
      ()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; @@ -112,11 +115,16 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; @@ -145,6 +153,8 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(table::tokenize, m)?)?; m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?; m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?; + m.add_function(wrap_pyfunction!(util::validate_conda_requirement, m)?)?; + m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?; m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?; m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?; m.add_function(wrap_pyfunction!(expr_col, m)?)?; diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 4e07d439e..f29cc7265 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -9,7 +9,10 @@ use crate::{ use arrow::pyarrow::{PyArrowType, ToPyArrow}; use lancedb::{ dataloader::permutation::{ - builder::{PermutationBuilder as LancePermutationBuilder, ShuffleStrategy}, + builder::{ + PermutationBuilder as LancePermutationBuilder, PermutationPersistMode, + PermutationPersistOptions, ShuffleStrategy, + }, reader::PermutationReader, split::{SplitSizes, SplitStrategy}, }, @@ -17,7 +20,7 @@ use lancedb::{ }; use pyo3::{ Bound, PyAny, PyRef, PyRefMut, PyResult, Python, - exceptions::PyRuntimeError, + exceptions::{PyRuntimeError, PyValueError}, pyclass, pymethods, types::{PyAnyMethods, PyDict, PyDictMethods, PyType}, }; @@ -123,14 +126,15 @@ impl PyAsyncPermutationBuilder { }) } - #[pyo3(signature = (columns, split_weights, *, discard_weight=0, split_names=None))] + #[pyo3(signature = (columns, split_weights, *, discard_weight=None, split_names=None))] pub fn split_hash( slf: PyRefMut<'_, Self>, columns: Vec, split_weights: Vec, - discard_weight: u64, + discard_weight: Option, split_names: Option>, ) -> PyResult { + let discard_weight = discard_weight.unwrap_or(0); slf.modify(|builder| { builder.with_split_strategy( SplitStrategy::Hash { @@ -246,6 +250,37 @@ impl PyAsyncPermutationBuilder { slf.modify(|builder| builder.with_filter(filter)) } + /// Store the permutation table in a database. + /// + /// This is only supported for embedded databases. The destination table is + /// created in the selected namespace, and an existing table is replaced only + /// when ``mode="overwrite"`` is explicit. + #[pyo3(signature = (db, table_name, *, namespace_path=None, mode="create"))] + pub fn persist( + slf: PyRefMut<'_, Self>, + db: PyRef<'_, crate::connection::Connection>, + table_name: String, + namespace_path: Option>, + mode: &str, + ) -> PyResult { + let mode = match mode { + "create" => PermutationPersistMode::Create, + "overwrite" => PermutationPersistMode::Overwrite, + other => { + return Err(PyValueError::new_err(format!( + "Invalid mode {other}; expected 'create' or 'overwrite'" + ))); + } + }; + let database = db.database()?; + let options = PermutationPersistOptions { + namespace_path: namespace_path.unwrap_or_default(), + mode, + }; + + slf.modify(|builder| builder.persist_with_options(database, table_name, options)) + } + pub fn execute(slf: PyRefMut<'_, Self>) -> PyResult> { let mut state = slf.state.lock().unwrap(); let builder = state diff --git a/python/src/query.rs b/python/src/query.rs index bda4b7783..f14276d74 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -7,6 +7,7 @@ use std::time::Duration; use crate::expr::PyExpr; use crate::runtime::future_into_py; +use crate::sync_stream::SyncRecordBatchStream; use crate::util::parse_distance_type; use crate::{arrow::RecordBatchStream, util::PyLanceDB}; use crate::{error::PythonErrorExt, index::class_name}; @@ -16,22 +17,24 @@ use arrow::array::make_array; use arrow::pyarrow::FromPyArrow; use arrow::pyarrow::IntoPyArrow; use arrow::pyarrow::ToPyArrow; +use futures::TryStreamExt; use lancedb::ApproxMode; use lancedb::index::scalar::{ BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery, FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery, }; use lancedb::query::AnalyzePlanDistributedMetrics; -use lancedb::query::QueryBase; use lancedb::query::QueryExecutionOptions; use lancedb::query::QueryFilter; use lancedb::query::{ ColumnOrdering, ExecutableQuery, Query as LanceDbQuery, Select, TakeQuery as LanceDbTakeQuery, VectorQuery as LanceDbVectorQuery, }; +use lancedb::query::{HasQuery, QueryBase}; use lancedb::table::AnyQuery; use pyo3::Bound; use pyo3::IntoPyObject; +use pyo3::Py; use pyo3::PyAny; use pyo3::PyRef; use pyo3::PyResult; @@ -64,6 +67,34 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + let reader = + py.detach(move || crate::arrow::execute_to_reader_sync(query, max_batch_length, timeout))?; + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) +} + +fn query_execution_options( + max_batch_length: Option, + timeout: Option, +) -> QueryExecutionOptions { + let mut options = QueryExecutionOptions::default(); + if let Some(max_batch_length) = max_batch_length { + options.max_batch_length = max_batch_length; + } + if let Some(timeout) = timeout { + options.timeout = Some(timeout); + } + options +} + impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { type Error = PyErr; @@ -355,6 +386,8 @@ pub struct PyQueryRequest { pub limit: Option, pub offset: Option, pub take_offsets: Option>, + pub take_row_ids: Option>, + pub preserve_order: Option, pub filter: Option, pub full_text_search: Option>, pub select: PySelect, @@ -378,6 +411,7 @@ pub struct PyQueryRequest { pub postfilter: Option, pub norm: Option, pub order_by: Option>, + pub scan_in_order: Option, } impl From for PyQueryRequest { @@ -387,6 +421,8 @@ impl From for PyQueryRequest { limit: query_request.limit, offset: query_request.offset, take_offsets: query_request.take_offsets, + take_row_ids: query_request.take_row_ids, + preserve_order: query_request.preserve_order.then_some(true), filter: query_request.filter.map(PyQueryFilter), full_text_search: query_request .full_text_search @@ -414,11 +450,14 @@ impl From for PyQueryRequest { order_by: query_request .order_by .map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()), + scan_in_order: query_request.scan_in_order, }, AnyQuery::VectorQuery(vector_query) => Self { limit: vector_query.base.limit, offset: vector_query.base.offset, take_offsets: vector_query.base.take_offsets, + take_row_ids: vector_query.base.take_row_ids, + preserve_order: vector_query.base.preserve_order.then_some(true), filter: vector_query.base.filter.map(PyQueryFilter), full_text_search: None, select_source_columns: PySelect::source_columns(&vector_query.base.select), @@ -445,6 +484,7 @@ impl From for PyQueryRequest { .base .order_by .map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()), + scan_in_order: vector_query.base.scan_in_order, }, } } @@ -613,8 +653,18 @@ impl Query { query_text = query_text[1..query_text.len() - 1].to_string(); } + let operator = query + .get_item("operator")? + .filter(|operator| !operator.is_none()) + .map(|operator| { + let operator = operator.extract::()?; + Operator::try_from(operator.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string())) + }) + .transpose()? + .unwrap_or(Operator::Or); let query: FtsQuery = match (is_phrase, is_multi_match) { - (false, _) => MatchQuery::new(query_text).into(), + (false, _) => MatchQuery::new(query_text).with_operator(operator).into(), (true, false) => PhraseQuery::new(query_text).into(), (true, true) => { return Err(PyValueError::new_err( @@ -653,6 +703,10 @@ impl Query { Ok(()) } + pub fn scan_in_order(&mut self, ordered: bool) { + self.inner = self.inner.clone().scan_in_order(ordered); + } + #[pyo3(signature = ())] pub fn output_schema(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); @@ -670,18 +724,58 @@ impl Query { ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let mut opts = QueryExecutionOptions::default(); - if let Some(max_batch_length) = max_batch_length { - opts.max_batch_length = max_batch_length; - } - if let Some(timeout) = timeout { - opts.timeout = Some(timeout); - } + let opts = query_execution_options(max_batch_length, timeout); let inner_stream = inner.execute_with_options(opts).await.infer_error()?; Ok(RecordBatchStream::new(inner_stream)) }) } + /// Execute this local query and return a pull-driven synchronous iterator. + /// + /// The query is started once. Each `__next__` fetches exactly one batch + /// from the caller's thread while the GIL is released. `None` keeps the + /// core's default 1024-row output cap, `0` lets the engine choose, and a + /// positive value caps each returned batch. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_sync( + self_: PyRef<'_, Self>, + py: Python<'_>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult { + let inner = self_.inner.clone(); + let opts = query_execution_options(max_batch_length, timeout); + let stream = py.detach(move || { + crate::runtime::block_on_interruptible(async move { + inner.execute_with_options(opts).await.infer_error() + }) + })?; + Ok(SyncRecordBatchStream::new(stream)) + } + + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -737,6 +831,10 @@ impl TakeQuery { self.inner = self.inner.clone().with_row_id(); } + pub fn preserve_order(&mut self) { + self.inner = self.inner.clone().preserve_order(); + } + pub fn use_rte(&mut self, enable: bool) { self.inner = self.inner.clone().use_rte(enable); } @@ -770,6 +868,20 @@ impl TakeQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -895,6 +1007,67 @@ impl FTSQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader( + self_.py(), + self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()), + max_batch_length, + timeout, + ) + } + + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync( + self_.py(), + self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()), + max_batch_length, + timeout, + ) + } + + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { + let mut inner = self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()); + let request = inner.mut_query(); + request.limit = None; + request.offset = None; + request.select = Select::columns(&["_score"]); + request.order_by = None; + request.with_row_id = false; + request.reranker = None; + future_into_py(self_.py(), async move { + let mut stream = inner.execute().await.infer_error()?; + let mut count = 0_u64; + while let Some(batch) = stream.try_next().await.infer_error()? { + count += batch.num_rows() as u64; + } + Ok(count) + }) + } + pub fn nearest_to(&mut self, vector: Bound<'_, PyAny>) -> PyResult { let vector_query = Query::new(self.inner.clone()).nearest_to(vector)?; Ok(HybridQuery { @@ -1112,6 +1285,29 @@ impl VectorQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { diff --git a/python/src/runtime.rs b/python/src/runtime.rs index 8891e2bf2..436b0d40b 100644 --- a/python/src/runtime.rs +++ b/python/src/runtime.rs @@ -21,37 +21,47 @@ //! rests on three separate mechanisms, each solving one problem the others //! cannot: //! -//! **`OUTSTANDING`, not `Arc::strong_count`, decides when the runtime is -//! idle.** Early versions tried to infer "is anything still using this -//! runtime" from how many `Arc` clones existed. That signal is -//! wrong in both directions: a clone taken only for the instant a task is -//! *submitted* says nothing about whether that task has actually finished -//! running (`Runtime::shutdown_timeout` gives spawned, non-blocking tasks -//! no grace period at all -- a task "keeps running until it yields, then is -//! dropped" -- so a reclaim landing right after submission would silently -//! abandon it before it ever got to run); and a clone held for a task's -//! *whole* lifetime can end up making that task the final owner of the -//! `Runtime`, so completing it drops the `Runtime` from inside one of its -//! own worker threads, which tokio itself forbids ("cannot drop a runtime -//! in a context where blocking is not allowed") and panics. `OUTSTANDING` -//! is an explicit courtesy counter instead: every top-level `spawn`, -//! `spawn_blocking`, or `block_on` call increments it before it starts and -//! decrements it (via [`OutstandingGuard`]) when it is truly done, entirely -//! decoupled from how many `Arc` clones exist at any instant. `shutdown` -//! waits for it to reach zero before ever touching the runtime, which also -//! closes a narrower race: because the counter is incremented *before* -//! `get_runtime()` is even called, an install already in progress when -//! `shutdown` runs is never invisible to it the way an empty slot would be. -//! If the counter never reaches zero within the bound, `shutdown` stops -//! waiting and forces the retirement attempt anyway -- silently returning -//! with the runtime and its workers still fully alive would just recreate -//! the exact race this function exists to close, for any call slower than -//! the grace period. +//! **A per-generation counter, not `Arc::strong_count`, decides when the +//! runtime is idle.** Early versions tried to infer "is anything still +//! using this runtime" from how many `Arc` clones existed. That +//! signal is wrong in both directions: a clone taken only for the instant a +//! task is *submitted* says nothing about whether that task has actually +//! finished running (`Runtime::shutdown_timeout` gives spawned, non-blocking +//! tasks no grace period at all -- a task "keeps running until it yields, +//! then is dropped" -- so a reclaim landing right after submission would +//! silently abandon it before it ever got to run); and a clone held for a +//! task's *whole* lifetime can end up making that task the final owner of +//! the `Runtime`, so completing it drops the `Runtime` from inside one of +//! its own worker threads, which tokio itself forbids ("cannot drop a +//! runtime in a context where blocking is not allowed") and panics. +//! [`GenerationCalls`] is an explicit courtesy counter instead: every +//! top-level `spawn`, `spawn_blocking`, or `block_on` call increments it +//! before it starts and decrements it (via [`OutstandingGuard`]) when it is +//! truly done, entirely decoupled from how many `Arc` clones exist at any +//! instant. `shutdown` waits for the current generation's counter to reach +//! zero before ever touching the runtime, which also closes a narrower +//! race: because the counter is incremented *before* `get_runtime()` is +//! even called, an install already in progress when `shutdown` runs is +//! never invisible to it the way an empty slot would be. If the counter +//! never reaches zero within the bound, `shutdown` stops waiting and forces +//! the retirement attempt anyway -- silently returning with the runtime and +//! its workers still fully alive would just recreate the exact race this +//! function exists to close, for any call slower than the grace period. //! -//! **Tasks never hold an `Arc`.** Because `OUTSTANDING` (not -//! reference counting) is what `shutdown` waits on, a top-level task only -//! needs to carry an `OutstandingGuard` -- a token whose `Drop` is a plain -//! atomic decrement -- not a clone of the runtime itself. That is what +//! **The counter is scoped to a fork generation, not the process.** A +//! single process-wide count cannot survive `fork()`: the child inherits the +//! parent's in-flight value, but the tasks that would decrement it do not +//! run there, and a guard copied onto the forking thread would later +//! decrement the child's count even though it belongs to the parent. Every +//! [`OutstandingGuard`] therefore holds an `Arc` for the +//! generation it was created in. A stale guard can only decrement its own +//! counter, while the child's first call lazily creates a fresh counter, and +//! `shutdown` only waits on the counter matching the live generation. +//! +//! **Tasks never hold an `Arc`.** Because the generation counter +//! (not reference counting) is what `shutdown` waits on, a top-level task +//! only needs to carry an `OutstandingGuard` -- a token whose `Drop` is a +//! plain atomic decrement -- not a clone of the runtime itself. That is what //! makes it impossible for a task's completion to become the final, //! worker-thread-side drop of the `Runtime`: nothing a task holds ever //! *is* the `Runtime`. @@ -74,17 +84,28 @@ //! installed runtime was built in against the live counter on every call, //! from ordinary (non-signal) context, and treats a mismatch as "stale, //! rebuild" -- exactly the check `atfork_child` used to perform directly. +//! [`shutdown`] makes the same comparison, because a child that exits +//! without ever installing its own runtime still finds the parent's stale +//! [`Tagged`] in the slot. It removes that slot and deliberately leaks the +//! instance instead of calling `shutdown_timeout` on it: its worker threads +//! do not exist in this process, so waiting for its counter or trying to +//! join them would hang, and a leaked reference prevents any inherited +//! `Arc` clone from becoming the final owner that drops it. use std::future::Future; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::pin::Pin; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, RecvTimeoutError}; use std::time::{Duration, Instant}; use arc_swap::ArcSwapOption; -use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject}; +use futures::FutureExt; +use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject, exceptions::PyRuntimeError}; use pyo3_async_runtimes::{ TaskLocals, + err::RustPanic, generic::{ContextExt, JoinError, Runtime}, }; use tokio::{runtime, task}; @@ -110,12 +131,21 @@ static RUNTIME: ArcSwapOption = ArcSwapOption::const_empty(); /// access -- just one atomic add, which is all a `pthread_atfork` child /// handler is ever safe to do. static GENERATION: AtomicU64 = AtomicU64::new(0); -/// Count of top-level `spawn`/`spawn_blocking`/`block_on` calls that have -/// started but not yet finished. See the module docs for why this, and not -/// `Arc::strong_count`, is what `shutdown` waits on. -static OUTSTANDING: AtomicU64 = AtomicU64::new(0); +/// In-flight top-level calls for one fork generation. Guards hold an `Arc` +/// to this object for their whole lifetime, so one inherited across `fork()` +/// can only decrement the counter it was created against, never the child's +/// fresh one. +struct GenerationCalls { + generation: u64, + outstanding: AtomicUsize, +} +static CALLS: ArcSwapOption = ArcSwapOption::const_empty(); static ATFORK_INSTALLED: AtomicBool = AtomicBool::new(false); +#[cfg(test)] +static TEST_WORKER_THREADS: AtomicUsize = AtomicUsize::new(0); + +#[cfg(not(test))] fn create_runtime() -> runtime::Runtime { runtime::Builder::new_multi_thread() .enable_all() @@ -124,9 +154,68 @@ fn create_runtime() -> runtime::Runtime { .expect("Failed to build tokio runtime") } +#[cfg(test)] +fn create_runtime() -> runtime::Runtime { + let mut builder = runtime::Builder::new_multi_thread(); + builder.enable_all().thread_name("lancedb-tokio-worker"); + // Fork tests hold two runtimes open at once. Keeping their worker count + // small avoids turning an unrelated parallel build on the same host into + // an apparent hang when the process thread limit is close to full. + let worker_threads = TEST_WORKER_THREADS.load(Ordering::Relaxed); + if worker_threads != 0 { + builder.worker_threads(worker_threads); + } + builder.build().expect("Failed to build tokio runtime") +} + +/// Register the fork-child handler once, before any generation-scoped state +/// is created. +/// +/// The first top-level call deliberately installs the hook before it starts +/// counting itself. Otherwise a fork between taking that first counter and +/// `get_runtime()` installing the hook would leave the child sharing the +/// parent's counter with no generation change to separate them. +fn ensure_atfork_installed() { + if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) { + install_atfork(); + } +} + +/// Get the in-flight counter for the current fork generation, creating it on +/// the first top-level call after a fork. +fn current_calls() -> Arc { + ensure_atfork_installed(); + let current_gen = GENERATION.load(Ordering::SeqCst); + loop { + let existing = CALLS.load_full(); + if let Some(existing) = &existing + && existing.generation == current_gen + { + return Arc::clone(existing); + } + let candidate = Arc::new(GenerationCalls { + generation: current_gen, + outstanding: AtomicUsize::new(0), + }); + let previous = CALLS.compare_and_swap(&existing, Some(Arc::clone(&candidate))); + let won = match (&*previous, &existing) { + (None, None) => true, + (Some(prev), Some(exist)) => Arc::ptr_eq(prev, exist), + _ => false, + }; + if won { + // A stale counter is only an integer: unlike a runtime it has no + // worker threads to join, so letting the slot's old reference go + // here is safe even in a forked child. + return candidate; + } + } +} + /// Get a live, owned handle to the shared runtime, rebuilding it if the /// installed one predates the most recent `fork()`. fn get_runtime() -> Arc { + ensure_atfork_installed(); let current_gen = GENERATION.load(Ordering::SeqCst); loop { let existing = RUNTIME.load_full(); @@ -135,9 +224,6 @@ fn get_runtime() -> Arc { { return Arc::clone(existing); } - if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) { - install_atfork(); - } // Built optimistically, outside any lock: on the rare race where two // threads both find the slot empty (or stale), one candidate wins // the compare-and-swap below and the other is simply dropped here, @@ -167,23 +253,26 @@ fn get_runtime() -> Arc { } } -/// RAII token tracked by [`OUTSTANDING`]. Held for the duration of a -/// top-level `block_on` call, or moved into a top-level `spawn`/ -/// `spawn_blocking` task so it decrements only once that task's *entire* -/// body -- including anything it nested-spawns and awaits -- has run to -/// completion or been dropped without completing. -struct OutstandingGuard; +/// RAII token tracked by the current [`GenerationCalls`] counter. Held for +/// the duration of a top-level `block_on` call, or moved into a top-level +/// `spawn`/`spawn_blocking` task so it decrements only once that task's +/// *entire* body -- including anything it nested-spawns and awaits -- has run +/// to completion or been dropped without completing. +struct OutstandingGuard { + calls: Arc, +} impl OutstandingGuard { fn new() -> Self { - OUTSTANDING.fetch_add(1, Ordering::SeqCst); - Self + let calls = current_calls(); + calls.outstanding.fetch_add(1, Ordering::SeqCst); + Self { calls } } } impl Drop for OutstandingGuard { fn drop(&mut self) { - OUTSTANDING.fetch_sub(1, Ordering::SeqCst); + self.calls.outstanding.fetch_sub(1, Ordering::SeqCst); } } @@ -197,6 +286,111 @@ pub fn block_on(fut: F) -> F::Output { get_runtime().block_on(fut) } +/// How often an interruptible wait returns to the Python caller for signal checks. +const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(25); + +/// Block on `fut` while keeping the Python caller responsive to signals. +/// +/// The query task lives on the shared runtime and carries an [`OutstandingGuard`]. +/// The caller waits on the result channel without holding the GIL and periodically +/// reacquires it to run CPython's signal handlers on the same thread. A signal +/// exception aborts the task and drops the result receiver. +/// +/// A synchronous callback already running on a multi-threaded Tokio worker uses +/// [`tokio::task::block_in_place`] so the core can be handed off while the callback +/// waits. Current-thread runtimes and contexts that reject blocking are returned as +/// Python errors instead of falling back to the Python event loop. +pub fn block_on_interruptible(fut: F) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, +{ + block_on_interruptible_with(fut, || Python::attach(|py| py.check_signals())) +} + +fn block_on_interruptible_with(fut: F, check: C) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, + C: FnMut() -> PyResult<()>, +{ + match runtime::Handle::try_current() { + Ok(handle) => match handle.runtime_flavor() { + runtime::RuntimeFlavor::MultiThread => { + let result = catch_unwind(AssertUnwindSafe(|| { + task::block_in_place(|| block_on_interruptible_inner(fut, check)) + })); + match result { + Ok(result) => result, + Err(payload) => Err(PyRuntimeError::new_err(format!( + "synchronous query cannot block in this Tokio context: {}", + panic_message(payload.as_ref()) + ))), + } + } + _ => Err(PyRuntimeError::new_err( + "synchronous query execution cannot block on a current-thread Tokio runtime; use the async API", + )), + }, + Err(_) => block_on_interruptible_inner(fut, check), + } +} + +fn block_on_interruptible_inner(fut: F, mut check: C) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, + C: FnMut() -> PyResult<()>, +{ + let guard = OutstandingGuard::new(); + let (tx, rx) = mpsc::sync_channel(1); + let task = async move { + let _guard = guard; + let result = AssertUnwindSafe(fut).catch_unwind().await; + // Dropping a completed result is enough when the caller has already + // returned on an interrupt; the task's guard is dropped with it. + let _ = tx.send(result); + }; + let handle = get_runtime().spawn(task); + + loop { + match rx.recv_timeout(SIGNAL_CHECK_INTERVAL) { + Ok(Ok(result)) => { + check()?; + return result; + } + Ok(Err(payload)) => { + check()?; + return Err(RustPanic::new_err(format!( + "rust future panicked: {}", + panic_message(payload.as_ref()) + ))); + } + Err(RecvTimeoutError::Timeout) => { + if let Err(error) = check() { + handle.abort(); + return Err(error); + } + } + Err(RecvTimeoutError::Disconnected) => { + return Err(PyRuntimeError::new_err( + "query task stopped before producing a result", + )); + } + } + } +} + +fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str { + if let Some(message) = payload.downcast_ref::<&str>() { + message + } else if let Some(message) = payload.downcast_ref::() { + message.as_str() + } else { + "unknown error" + } +} + /// Run a detached task, including when the caller is already on a runtime worker. /// Keep it visible to [`shutdown`] until it finishes. pub fn spawn_background(fut: F) @@ -219,13 +413,15 @@ where /// Gracefully quiesce the shared runtime, meant to run at normal process exit. /// -/// Waits (bounded by `timeout`) for [`OUTSTANDING`] to reach zero -- i.e. -/// for every top-level call already under way to actually finish, not just -/// for `Arc::strong_count` to look low -- before ever touching the runtime. -/// If the bound elapses first, it stops waiting and attempts retirement -/// anyway: leaving the runtime and its worker threads untouched would just -/// recreate the exact race this function exists to close, for any call -/// slower than the grace period. +/// Waits (bounded by `timeout`) for the current generation's +/// [`GenerationCalls`] counter to reach zero -- i.e. for every top-level call +/// already under way in *this* process to actually finish, not just for +/// `Arc::strong_count` to look low -- before ever touching the runtime. Work +/// inherited from a parent process at `fork()` belongs to an older +/// generation and is never waited on. If the bound elapses first, it stops +/// waiting and attempts retirement anyway: leaving the runtime and its worker +/// threads untouched would just recreate the exact race this function exists +/// to close, for any call slower than the grace period. /// /// Retirement itself removes the runtime from the slot and calls /// `shutdown_timeout` rather than a bare `drop`: dropping a tokio `Runtime` @@ -238,14 +434,22 @@ where /// the slot and finishing its own call, this abandons the runtime instead /// of forcing the issue -- the same trade `atfork_child` already makes. /// +/// A runtime tagged with a generation older than the live counter was +/// inherited through `fork()` and is never retired here; see the module docs. +/// /// Neither of the two ways this can fail to cleanly retire the runtime -- /// the wait timing out, or `try_unwrap` losing that race -- has any other /// signal to report through (`shutdown_timeout` itself returns nothing), /// so both log a warning instead of failing silently. pub fn shutdown(timeout: Duration) { let deadline = Instant::now() + timeout; + let generation = GENERATION.load(Ordering::SeqCst); + let calls = CALLS.load_full(); + let calls = calls + .as_ref() + .filter(|calls| calls.generation == generation); loop { - let outstanding = OUTSTANDING.load(Ordering::SeqCst); + let outstanding = calls.map_or(0, |calls| calls.outstanding.load(Ordering::SeqCst)); if outstanding == 0 { break; } @@ -260,6 +464,18 @@ pub fn shutdown(timeout: Duration) { let Some(current) = RUNTIME.load_full() else { return; }; + if current.generation != generation { + // The child inherited the parent's installed runtime. Its worker + // threads do not exist here, so waiting on its counter or calling + // `shutdown_timeout` would wait for work that can never finish and + // join threads that can never exit. Remove the slot in ordinary + // context and deliberately leak the instance: inherited `Arc` clones + // may still be dropped in this process, and the leaked reference + // keeps a dropped clone from becoming the final owner. + RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None); + std::mem::forget(current); + return; + } RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None); match Arc::try_unwrap(current) { Ok(tagged) => { @@ -320,7 +536,7 @@ impl Runtime for LanceRuntime { /// awaits its `JoinHandle`. `Handle::try_current` pins that nested call /// to whatever runtime is already executing it, so only the first, /// outermost call of a chain -- one running on a thread outside any - /// runtime -- ever consults [`get_runtime`] or [`OUTSTANDING`]. + /// runtime -- ever consults [`get_runtime`] or [`OutstandingGuard`]. fn spawn(fut: F) -> Self::JoinHandle where F: Future + Send + 'static, @@ -391,14 +607,14 @@ where mod tests { use super::*; - // RUNTIME, GENERATION, OUTSTANDING, and ATFORK_INSTALLED are process-wide + // RUNTIME, CALLS, GENERATION, and ATFORK_INSTALLED are process-wide // statics, and Rust's test harness runs tests in parallel by default, // so separate test functions below would otherwise race each other // through this shared state (this reproduced in CI: one test's // in-flight task got reclaimed by a *different* test's concurrent - // `shutdown()` call, and another observed `OUTSTANDING` left non-zero - // by a still-running sibling). Every test takes this lock first so - // only one of them touches the shared runtime state at a time; a + // `shutdown()` call, and another observed the in-flight counter left + // non-zero by a still-running sibling). Every test takes this lock first + // so only one of them touches the shared runtime state at a time; a // poisoned lock (a previous test's genuine failure) is still honored // rather than cascading into every later test as an unrelated panic. static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -464,6 +680,95 @@ mod tests { shutdown(Duration::from_secs(5)); } + #[test] + fn test_block_on_interruptible_aborts_and_drops_future() { + use std::sync::mpsc; + + Python::initialize(); + let _lock = lock_runtime_state_for_test(); + let (started_tx, started_rx) = mpsc::channel(); + let (dropped_tx, dropped_rx) = mpsc::channel(); + + struct DropNotify(Option>); + impl Drop for DropNotify { + fn drop(&mut self) { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + } + } + } + + let fut = async move { + started_tx.send(()).unwrap(); + let _notify = DropNotify(Some(dropped_tx)); + std::future::pending::<()>().await; + #[allow(unreachable_code)] + Ok::<(), pyo3::PyErr>(()) + }; + let result = block_on_interruptible_with(fut, || { + Err(pyo3::exceptions::PyRuntimeError::new_err("interrupted")) + }); + + assert!(result.is_err()); + started_rx + .recv_timeout(Duration::from_secs(2)) + .expect("query task never started"); + dropped_rx + .recv_timeout(Duration::from_secs(2)) + .expect("interrupted query future was not dropped"); + shutdown(Duration::from_secs(5)); + } + + #[test] + fn test_block_on_interruptible_maps_panic() { + Python::initialize(); + let result = block_on_interruptible(async { + panic!("boom"); + #[allow(unreachable_code)] + Ok::<(), pyo3::PyErr>(()) + }); + assert!( + result + .expect_err("panic must become a Python exception") + .to_string() + .contains("rust future panicked: boom") + ); + } + + #[test] + fn test_block_on_interruptible_rejects_current_thread_runtime() { + Python::initialize(); + let runtime = runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("current-thread runtime"); + let error = runtime + .block_on(async { block_on_interruptible(async { Ok::<_, pyo3::PyErr>(1) }) }) + .expect_err("current-thread runtime must be rejected"); + assert!(error.to_string().contains("current-thread")); + } + + #[cfg(target_os = "linux")] + #[test] + fn test_block_on_interruptible_from_single_worker_runtime() { + Python::initialize(); + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(1); + shutdown(Duration::from_secs(5)); + + let (done_tx, done_rx) = mpsc::channel(); + drop(get_runtime().spawn(async move { + let result = block_on_interruptible(async { Ok::<_, pyo3::PyErr>(42) }); + let _ = done_tx.send(result.map_err(|error| error.to_string())); + })); + + let result = done_rx + .recv_timeout(Duration::from_secs(10)) + .expect("single-worker runtime made no progress"); + assert_eq!(result.expect("single-worker query failed"), 42); + shutdown(Duration::from_secs(5)); + } + // Adapted from the concurrent reproducer that found the original bug: // many threads hammering the runtime while shutdown races them, not // just the sequential rebuild path above. Before every reader held its @@ -570,7 +875,7 @@ mod tests { use std::sync::mpsc; let _lock = lock_runtime_state_for_test(); - // Clean slate: no runtime installed, OUTSTANDING at zero. + // Clean slate: no runtime installed, no in-flight calls. shutdown(Duration::from_secs(5)); let (installer_ready_tx, installer_ready_rx) = mpsc::channel::<()>(); @@ -596,6 +901,312 @@ mod tests { // shutdown must have waited for the install to finish and then // retired it, not returned early and left it stranded. assert!(RUNTIME.load_full().is_none()); - assert_eq!(OUTSTANDING.load(Ordering::SeqCst), 0); + let calls = CALLS + .load_full() + .expect("install race left no generation counter"); + assert_eq!(calls.outstanding.load(Ordering::SeqCst), 0); + } + + /// Keep fork-test runtimes small; see [`TEST_WORKER_THREADS`]. + #[cfg(target_os = "linux")] + struct TestWorkerThreads(usize); + + #[cfg(target_os = "linux")] + impl TestWorkerThreads { + fn new(worker_threads: usize) -> Self { + Self(TEST_WORKER_THREADS.swap(worker_threads, Ordering::SeqCst)) + } + } + + #[cfg(target_os = "linux")] + impl Drop for TestWorkerThreads { + fn drop(&mut self) { + TEST_WORKER_THREADS.store(self.0, Ordering::SeqCst); + } + } + + /// Run `f` in a forked child and return the `i32` it reports, or `None` + /// if the child did not report within the bound. The child leaves with + /// `_exit` so it never runs destructors inherited from the test process. + #[cfg(target_os = "linux")] + fn run_in_forked_child(f: F) -> Option + where + F: FnOnce() -> i32, + { + let mut pipe = [0; 2]; + assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0, "pipe failed"); + let (read_fd, write_fd) = (pipe[0], pipe[1]); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { libc::close(read_fd) }; + let result = f(); + let bytes = result.to_ne_bytes(); + let written = unsafe { libc::write(write_fd, bytes.as_ptr().cast(), bytes.len()) }; + unsafe { libc::close(write_fd) }; + unsafe { + libc::_exit(if written == bytes.len() as isize { + 0 + } else { + 1 + }) + }; + } + + unsafe { libc::close(write_fd) }; + let mut poll_fd = libc::pollfd { + fd: read_fd, + events: libc::POLLIN, + revents: 0, + }; + let ready = loop { + let ready = unsafe { libc::poll(&mut poll_fd, 1, 10_000) }; + if ready >= 0 { + break ready; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "poll failed: {error}" + ); + }; + if ready == 0 { + unsafe { libc::kill(pid, libc::SIGKILL) }; + } + + let mut result = None; + if ready == 1 { + let mut bytes = [0u8; std::mem::size_of::()]; + let read = loop { + let read = unsafe { libc::read(read_fd, bytes.as_mut_ptr().cast(), bytes.len()) }; + if read >= 0 { + break read; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "read failed: {error}" + ); + }; + if read == bytes.len() as isize { + result = Some(i32::from_ne_bytes(bytes)); + } + } + unsafe { libc::close(read_fd) }; + + let mut status = 0; + loop { + let waited = unsafe { libc::waitpid(pid, &mut status, 0) }; + if waited == pid { + break; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "waitpid failed: {error}" + ); + } + if ready == 0 { + return None; + } + assert_eq!(status, 0, "forked child did not exit successfully"); + result + } + + // The child inherits the parent's installed runtime and its outstanding + // count, but not the worker thread that would ever release that count. + // Its exit-time shutdown must therefore ignore both: waiting for parent + // work would burn the whole grace period, and retiring the inherited + // runtime would try to join worker threads that do not exist here. + #[cfg(target_os = "linux")] + #[test] + fn test_forked_child_shutdown_does_not_wait_for_parent_work() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + drop(LanceRuntime::spawn(async move { + started_tx.send(()).unwrap(); + let _ = release_rx.await; + let _ = done_tx.send(()); + })); + started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task did not start"); + + let child_result = run_in_forked_child(|| { + // Much longer than the watchdog: if this waits for inherited + // parent work at all, the child fails to report in time instead + // of the test comparing two elapsed durations. + shutdown(Duration::from_secs(30)); + i32::from(RUNTIME.load_full().is_some()) + }); + assert_eq!( + child_result, + Some(0), + "child shutdown waited for parent work or retired the inherited runtime" + ); + + release_tx.send(()).unwrap(); + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task was disturbed by the forked child"); + shutdown(Duration::from_secs(5)); + } + + // A child that builds its own runtime must drain that runtime's own + // work, and only that work: the parent's held task is still outstanding + // in the inherited copy of the counter but can never finish here. + #[cfg(target_os = "linux")] + #[test] + fn test_forked_child_drains_its_own_runtime_without_waiting_for_parent_work() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + drop(LanceRuntime::spawn(async move { + started_tx.send(()).unwrap(); + let _ = release_rx.await; + let _ = done_tx.send(()); + })); + started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task did not start"); + + let child_result = run_in_forked_child(|| { + let child_done = Arc::new(AtomicBool::new(false)); + let child_done_flag = Arc::clone(&child_done); + let (task_started_tx, task_started_rx) = mpsc::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + let (child_tx, child_rx) = mpsc::channel(); + drop(LanceRuntime::spawn(async move { + task_started_tx.send(()).unwrap(); + let _ = release_rx.await; + child_done_flag.store(true, Ordering::SeqCst); + let _ = child_tx.send(()); + })); + task_started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("child task did not start"); + + // Keep the child's own task outstanding while shutdown starts, + // then release it once the shutdown thread is about to enter. + let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel(); + let shutdown_thread = std::thread::spawn(move || { + shutdown_ready_tx.send(()).unwrap(); + shutdown(Duration::from_secs(30)); + }); + shutdown_ready_rx.recv().unwrap(); + release_tx.send(()).unwrap(); + shutdown_thread.join().unwrap(); + + let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok() + && child_done.load(Ordering::SeqCst); + let retired = RUNTIME.load_full().is_none(); + let rebuilt = block_on(async { 40 + 2 }) == 42; + shutdown(Duration::from_secs(30)); + i32::from(!(drained && retired && rebuilt)) + }); + assert_eq!( + child_result, + Some(0), + "child did not drain its own runtime or waited for parent work" + ); + + release_tx.send(()).unwrap(); + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task was disturbed by the forked child"); + shutdown(Duration::from_secs(5)); + } + + // A guard created before `fork()` belongs to the parent generation. If + // the child drops that inherited guard, it must decrement the counter it + // was created against, not the child's fresh counter (a naive reset in + // the child would underflow here and make shutdown wait forever). The + // second parent guard stays held across the fork without being dropped + // in the child, so this also proves the child does not wait for work + // that can only finish in the parent. + #[cfg(target_os = "linux")] + #[test] + fn test_inherited_guard_does_not_corrupt_child_generation_counter() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + // This test forks before any runtime exists, so make the hook + // initialization explicit through the same path the first top-level + // call uses; otherwise this test only works after a preceding test + // has installed the process-wide hook. + ensure_atfork_installed(); + // Stands in for a top-level call that was in progress when the + // parent forked and is dropped by the child after it starts work. + let inherited_guard = OutstandingGuard::new(); + // Stays outstanding in the parent for the whole fork, as parent work + // that no child task can ever complete. + let parent_guard = OutstandingGuard::new(); + + let child_result = run_in_forked_child(move || { + let child_done = Arc::new(AtomicBool::new(false)); + let child_done_flag = Arc::clone(&child_done); + let (task_started_tx, task_started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (child_tx, child_rx) = mpsc::channel(); + drop(LanceRuntime::spawn(async move { + task_started_tx.send(()).unwrap(); + let _ = release_rx.await; + child_done_flag.store(true, Ordering::SeqCst); + let _ = child_tx.send(()); + })); + task_started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("child task did not start"); + + // Drop the inherited guard while the child has its own task + // outstanding, so a shared or reset counter would visibly + // perturb the child's accounting. + drop(inherited_guard); + + let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel(); + let shutdown_thread = std::thread::spawn(move || { + shutdown_ready_tx.send(()).unwrap(); + shutdown(Duration::from_secs(30)); + }); + shutdown_ready_rx.recv().unwrap(); + release_tx.send(()).unwrap(); + shutdown_thread.join().unwrap(); + + let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok() + && child_done.load(Ordering::SeqCst); + let retired = RUNTIME.load_full().is_none(); + i32::from(!(drained && retired)) + }); + assert_eq!( + child_result, + Some(0), + "inherited guard corrupted the child generation counter" + ); + + drop(parent_guard); + shutdown(Duration::from_secs(5)); } } diff --git a/python/src/sql.rs b/python/src/sql.rs index 612521207..166cf0df5 100644 --- a/python/src/sql.rs +++ b/python/src/sql.rs @@ -31,6 +31,11 @@ impl Query { self.inner.id() } + #[getter] + pub fn job_id(&self) -> Option { + self.inner.job_id() + } + pub fn describe(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -63,6 +68,7 @@ impl Query { #[derive(Clone)] pub struct QueryDescription { id: Uuid, + job_id: Option, status: String, progress: Option, expires_at: Option>, @@ -72,8 +78,8 @@ pub struct QueryDescription { impl QueryDescription { fn __repr__(&self) -> String { format!( - "QueryDescription(id={:?}, status={:?}, progress={:?}, expires_at={:?})", - self.id, self.status, self.progress, self.expires_at + "QueryDescription(id={:?}, job_id={:?}, status={:?}, progress={:?}, expires_at={:?})", + self.id, self.job_id, self.status, self.progress, self.expires_at ) } } @@ -82,6 +88,7 @@ impl From for QueryDescription { fn from(description: lancedb::sql::QueryDescription) -> Self { Self { id: description.id, + job_id: description.job_id, status: description.status.to_string(), progress: description.progress, expires_at: description.expires_at, diff --git a/python/src/sync_stream.rs b/python/src/sync_stream.rs new file mode 100644 index 000000000..5180f7a73 --- /dev/null +++ b/python/src/sync_stream.rs @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! A pull-driven synchronous reader over a query's record batch stream. +//! +//! The synchronous Python API used to drive one future per batch through the +//! shared background event loop. This reader keeps the stream in Rust and +//! fetches exactly one batch from the caller's thread for each `__next__`, +//! while the caller's GIL is released. +//! +//! The stream is stored only while the reader is idle. Taking it out for a +//! poll means an error, EOF, interrupt, or a dropped last owner releases the +//! execution plan immediately instead of leaving a reader task behind. A +//! successful batch puts the stream back so an early `break` can resume +//! reading from the same cursor. + +use std::sync::Mutex; + +use arrow::datatypes::SchemaRef; +use arrow::pyarrow::{IntoPyArrow, ToPyArrow}; +use arrow::record_batch::RecordBatch; +use futures::StreamExt; +use lancedb::arrow::SendableRecordBatchStream; +use pyo3::{Py, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; + +use crate::error::PythonErrorExt; +use crate::runtime::block_on_interruptible; + +/// Synchronous iterator over the batches of one query execution. +/// +/// Python wraps this in [`pyarrow.RecordBatchReader.from_batches`] so the +/// public return type, schema capsule, and exception types stay the same as +/// the existing sync reader. Creating the iterator does not poll the stream; +/// the first `__next__` starts any configured query timeout. +#[pyclass] +pub struct SyncRecordBatchStream { + schema: SchemaRef, + stream: Mutex>, +} + +impl SyncRecordBatchStream { + pub fn new(stream: SendableRecordBatchStream) -> Self { + let schema = stream.schema(); + Self { + schema, + stream: Mutex::new(Some(stream)), + } + } + + /// Take the stream and hand it to one owned, one-shot read future. + /// + /// The future owns the stream so an interrupt aborts it and drops the + /// execution plan with the future. A successful batch returns the stream + /// to the slot, which keeps an early `break` resumable. EOF and read + /// errors drop the stream before returning. The lock is held only while + /// taking or storing the stream, never while waiting, so another Python + /// thread cannot deadlock against a read that needs the GIL. + fn pull(&mut self) -> PyResult> { + match self.pull_with(|mut stream| { + block_on_interruptible(async move { + let next = stream.next().await; + Ok::<_, pyo3::PyErr>((stream, next)) + }) + })? { + Some(Ok(batch)) => Ok(Some(batch)), + Some(Err(error)) => Err(into_py_error(error)), + None => Ok(None), + } + } + + /// Shared state machine for one pull, with the wait injected for tests. + fn pull_with( + &mut self, + fetch: F, + ) -> Result>, pyo3::PyErr> + where + F: FnOnce( + SendableRecordBatchStream, + ) -> PyResult<( + SendableRecordBatchStream, + Option>, + )>, + { + let Some(stream) = self + .stream + .lock() + .expect("sync reader mutex poisoned") + .take() + else { + return Ok(None); + }; + let (stream, next) = fetch(stream)?; + match next { + Some(Ok(batch)) => { + *self.stream.lock().expect("sync reader mutex poisoned") = Some(stream); + Ok(Some(Ok(batch))) + } + Some(Err(error)) => { + drop(stream); + Ok(Some(Err(error))) + } + None => { + drop(stream); + Ok(None) + } + } + } + + fn release(&self) { + *self.stream.lock().expect("sync reader mutex poisoned") = None; + } +} + +#[pymethods] +impl SyncRecordBatchStream { + #[getter] + pub fn schema(&self, py: Python<'_>) -> PyResult> { + (*self.schema) + .clone() + .into_pyarrow(py) + .map(|obj| obj.unbind()) + } + + fn __iter__(self_: PyRef<'_, Self>) -> PyRef<'_, Self> { + self_ + } + + fn __next__(&mut self, py: Python<'_>) -> PyResult>> { + let batch = py.detach(|| self.pull())?; + let Some(batch) = batch else { + return Ok(None); + }; + let batch = match batch.to_pyarrow(py) { + Ok(batch) => batch, + Err(error) => { + self.release(); + return Err(error); + } + }; + // A signal arriving after the fetch still terminates the reader, so + // no execution plan outlives the KeyboardInterrupt. + if let Err(error) = py.check_signals() { + self.release(); + return Err(error); + } + Ok(Some(batch.unbind())) + } +} + +fn into_py_error(error: lancedb::Error) -> pyo3::PyErr { + match Err::<(), _>(error).infer_error() { + Ok(()) => unreachable!("infer_error returned Ok for an Err value"), + Err(error) => error, + } +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::pin::Pin; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::task::{Context, Poll}; + + use arrow::array::Int32Array; + use arrow::datatypes::{DataType, Field, Schema}; + use futures::Stream; + use lancedb::arrow::RecordBatchStream as LanceRecordBatchStream; + + use super::*; + + struct TestStream { + schema: SchemaRef, + batches: VecDeque>, + polls: Arc, + dropped: Arc, + } + + impl TestStream { + fn new(batches: Vec>) -> Self { + let schema = test_schema(); + Self { + schema, + batches: batches.into(), + polls: Arc::new(AtomicUsize::new(0)), + dropped: Arc::new(AtomicBool::new(false)), + } + } + } + + impl Stream for TestStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + self.polls.fetch_add(1, Ordering::SeqCst); + Poll::Ready(self.batches.pop_front()) + } + } + + impl LanceRecordBatchStream for TestStream { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } + } + + impl Drop for TestStream { + fn drop(&mut self) { + self.dropped.store(true, Ordering::SeqCst); + } + } + + fn test_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])) + } + + fn test_batch(value: i32) -> RecordBatch { + RecordBatch::try_new(test_schema(), vec![Arc::new(Int32Array::from(vec![value]))]).unwrap() + } + + fn boxed(stream: TestStream) -> SendableRecordBatchStream { + Box::pin(stream) + } + + fn pull_fake( + reader: &mut SyncRecordBatchStream, + ) -> Result>, pyo3::PyErr> { + reader.pull_with(|mut stream| { + let next = futures::executor::block_on(stream.next()); + Ok((stream, next)) + }) + } + + #[test] + fn creation_does_not_poll() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let polls = Arc::clone(&stream.polls); + let _reader = SyncRecordBatchStream::new(boxed(stream)); + assert_eq!(polls.load(Ordering::SeqCst), 0); + } + + #[test] + fn one_pull_reads_one_batch_and_keeps_the_stream_resumable() { + let stream = TestStream::new(vec![ + Ok(test_batch(1)), + Ok(test_batch(2)), + Ok(test_batch(3)), + ]); + let polls = Arc::clone(&stream.polls); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert_eq!(polls.load(Ordering::SeqCst), 1); + assert!(!dropped.load(Ordering::SeqCst)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert!(!dropped.load(Ordering::SeqCst)); + } + + #[test] + fn eof_drops_the_stream_before_returning() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok()); + assert!(!dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + assert!(dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + } + + #[test] + fn error_drops_the_stream_before_returning() { + let stream = TestStream::new(vec![Err(lancedb::Error::Runtime { + message: "read failed".to_string(), + })]); + let dropped = Arc::clone(&stream.dropped); + let mut reader = SyncRecordBatchStream::new(boxed(stream)); + + assert!(pull_fake(&mut reader).unwrap().unwrap().is_err()); + assert!(dropped.load(Ordering::SeqCst)); + assert!(pull_fake(&mut reader).unwrap().is_none()); + } + + #[test] + fn dropping_an_unread_reader_drops_the_stream_without_polling() { + let stream = TestStream::new(vec![Ok(test_batch(1))]); + let polls = Arc::clone(&stream.polls); + let dropped = Arc::clone(&stream.dropped); + let reader = SyncRecordBatchStream::new(boxed(stream)); + + drop(reader); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert!(dropped.load(Ordering::SeqCst)); + } +} diff --git a/python/src/table.rs b/python/src/table.rs index 6ef524310..9e1ef3821 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -9,12 +9,13 @@ use std::{ }, }; -use crate::runtime::{block_on, future_into_py, spawn_background}; +use crate::runtime::{block_on, block_on_interruptible, future_into_py, spawn_background}; use crate::{ connection::Connection, error::PythonErrorExt, expr::PyExpr, index::{CodeAnalyzerOptions, IndexConfig, extract_index_params}, + job::JobFailureInfo, query::{Query, TakeQuery}, table::scannable::PyScannable, }; @@ -28,41 +29,271 @@ use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest}; use lancedb::connection::LanceFileVersion; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ - AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration, - FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, Ref, - RefreshColumnOptions, Table as LanceDbTable, + AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, DeltaRef, Duration, + FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig, + FunctionRefreshPodResources, IndexRemapMode, NewColumnTransform, Ref, RefreshColumnOptions, + Table as LanceDbTable, TableDelta as LanceDbTableDelta, }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ - Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, + Bound, FromPyObject, Py, PyAny, PyErr, PyRef, PyResult, Python, exceptions::{PyRuntimeError, PyValueError}, pyclass, pyfunction, pymethods, - types::{IntoPyDict, PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods}, + types::{ + IntoPyDict, PyAnyMethods, PyBool, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods, + }, }; mod scannable; -fn refresh_column_options( +/// Keyword arguments shared by `refresh_column` and `refresh_column_async`. +struct RefreshColumnArgs { + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, + where_clause: Option, batch_size: Option, + max_concurrency: Option, + max_job_attempts: Option, + publication_interval_rows: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + supervisor_resources: Option, + planning_workers: Option, gpu_class: Option, - gpu_count: Option, -) -> PyResult { + gpu_count: Option, + total_gpu_count: Option, + retry_policy: Option, + error_policy: Option, + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, +} + +fn positive_count>(value: Option, name: &str) -> PyResult> { + value + .map(|v| { + T::try_from(v) + .ok() + .filter(|_| v > 0) + .ok_or_else(|| PyValueError::new_err(format!("{name} must be greater than zero"))) + }) + .transpose() +} + +fn positive_u32_integer(value: Option<&Bound<'_, PyAny>>, name: &str) -> PyResult> { + let Some(value) = value else { + return Ok(None); + }; + if value.is_none() || value.is_instance_of::() { + return Err(PyValueError::new_err(format!( + "{name} must be an integer between 1 and 4294967295" + ))); + } + let parsed = value.extract::().map_err(|_| { + PyValueError::new_err(format!( + "{name} must be an integer between 1 and 4294967295" + )) + })?; + u32::try_from(parsed) + .ok() + .filter(|parsed| *parsed > 0) + .map(Some) + .ok_or_else(|| { + PyValueError::new_err(format!( + "{name} must be an integer between 1 and 4294967295" + )) + }) +} + +fn structured_integer(value: &Bound<'_, PyAny>, name: &str) -> PyResult { + if value.is_none() || value.is_instance_of::() { + return Err(PyValueError::new_err(format!("{name} must be an integer"))); + } + let parsed = value + .extract::() + .map_err(|_| PyValueError::new_err(format!("{name} must be an integer")))?; + if parsed == 0 { + return Err(PyValueError::new_err(format!( + "{name} must be greater than zero" + ))); + } + Ok(parsed) +} + +fn parse_pod_resources( + resources: &Bound<'_, PyDict>, + prefix: &str, +) -> PyResult { + for key in resources.keys() { + let key = key + .extract::() + .map_err(|_| PyValueError::new_err(format!("{prefix} keys must be strings")))?; + if !matches!( + key.as_str(), + "cpu_millis" | "memory_bytes" | "ephemeral_storage_bytes" + ) { + return Err(PyValueError::new_err(format!( + "{prefix} contains unsupported key '{key}'" + ))); + } + } + let get = |name: &str| -> PyResult { + let value = resources + .get_item(name)? + .ok_or_else(|| PyValueError::new_err(format!("{prefix}.{name} is required")))?; + structured_integer(&value, &format!("{prefix}.{name}")) + }; + Ok(FunctionRefreshPodResources::new( + get("cpu_millis")?, + get("memory_bytes")?, + get("ephemeral_storage_bytes")?, + )) +} + +fn parse_supervisor_resources( + resources: Option<&Bound<'_, PyDict>>, +) -> PyResult> { + resources + .map(|resources| parse_pod_resources(resources, "supervisor_resources")) + .transpose() +} + +fn parse_planning_workers( + planning: Option<&Bound<'_, PyDict>>, +) -> PyResult> { + let Some(planning) = planning else { + return Ok(None); + }; + for key in planning.keys() { + let key = key + .extract::() + .map_err(|_| PyValueError::new_err("planning_workers keys must be strings"))?; + if !matches!( + key.as_str(), + "resources" | "max_workers" | "rows_per_worker" | "fragments_per_worker" + ) { + return Err(PyValueError::new_err(format!( + "planning_workers contains unsupported key '{key}'" + ))); + } + } + let resources = planning + .get_item("resources")? + .ok_or_else(|| PyValueError::new_err("planning_workers.resources is required"))?; + let resources = resources + .cast::() + .map_err(|_| PyValueError::new_err("planning_workers.resources must be a dict"))?; + let resources = parse_pod_resources(resources, "planning_workers.resources")?; + let get = |name: &str| -> PyResult { + let value = planning + .get_item(name)? + .ok_or_else(|| PyValueError::new_err(format!("planning_workers.{name} is required")))?; + structured_integer(&value, &format!("planning_workers.{name}")) + }; + let max_workers = usize::try_from(get("max_workers")?) + .map_err(|_| PyValueError::new_err("planning_workers.max_workers is too large"))?; + Ok(Some(FunctionRefreshPlanningConfig::new( + resources, + max_workers, + get("rows_per_worker")?, + get("fragments_per_worker")?, + ))) +} + +fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { + let RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, + where_clause, + batch_size, + max_concurrency, + max_job_attempts, + publication_interval_rows, + total_cpu_millis, + total_memory_bytes, + supervisor_resources, + planning_workers, + gpu_class, + gpu_count, + total_gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + } = args; let mut options = RefreshColumnOptions::default(); + options.retry_errors = retry_errors.then_some(true); + options.retry_job_id = retry_job_id; + options.retry_error_type = retry_error_type; + options.include_quarantined = include_quarantined.then_some(true); + options.function_version = function_version; + options.recompute = recompute + .map(|value| { + serde_json::from_value(serde_json::Value::String(value)) + .map_err(|_| PyValueError::new_err("recompute must be failed, all, or none")) + }) + .transpose()?; + options.where_clause = where_clause; + options.max_failed_fraction = max_failed_fraction; + options.max_failed_rows = max_failed_rows + .map(u64::try_from) + .transpose() + .map_err(|_| PyValueError::new_err("max_failed_rows must be a non-negative integer"))?; + options.row_timeout_seconds = row_timeout_seconds; + options.init_timeout_seconds = init_timeout_seconds; + options.max_job_attempts = max_job_attempts; + options.num_workers = positive_count(num_workers, "num_workers")?; + options.max_executor_processes_per_worker = positive_count( + max_executor_processes_per_worker, + "max_executor_processes_per_worker", + )?; + options.retry_policy = retry_policy + .map(|json| { + serde_json::from_str(&json) + .map_err(|error| PyValueError::new_err(format!("invalid retry_policy: {error}"))) + }) + .transpose()?; + options.error_policy = error_policy + .map(|value| { + serde_json::from_value(serde_json::Value::String(value)) + .map_err(|error| PyValueError::new_err(format!("invalid error_policy: {error}"))) + }) + .transpose()?; options.batch_size = batch_size .map(usize::try_from) .transpose() .map_err(|_| PyValueError::new_err("batch_size must be greater than zero"))?; + options.max_concurrency = max_concurrency; + options.publication_interval_rows = + positive_count(publication_interval_rows, "publication_interval_rows")?; + options.total_cpu_millis = total_cpu_millis; + options.total_memory_bytes = total_memory_bytes; + options.supervisor_resources = supervisor_resources; + options.planning_workers = planning_workers; options.gpu_class = gpu_class; - options.gpu_count = gpu_count + options.gpu_count = gpu_count; + options.total_gpu_count = total_gpu_count .map(|count| { - u32::try_from(count) - .ok() - .filter(|count| *count > 0) - .ok_or_else(|| { - PyValueError::new_err( - "gpu_count must be a positive integer no greater than u32::MAX", - ) - }) + u32::try_from(count).ok().ok_or_else(|| { + PyValueError::new_err( + "total_gpu_count must be a nonnegative integer no greater than u32::MAX", + ) + }) }) .transpose()?; options.validate().infer_error()?; @@ -211,6 +442,16 @@ fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult() + { + return Err(PyValueError::new_err(format!( + "{key} must be an integer, not a bool" + ))); + } match key.as_str() { "target_rows_per_fragment" => { parsed.target_rows_per_fragment = positive_u32(&value, &key)? @@ -611,9 +852,15 @@ impl From for RefreshColumnResult { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrorRecord { + pub first_seen_at_millis: Option, + pub last_seen_at_millis: Option, + pub quarantined: bool, + pub input: Option, + pub attempts: Option, pub job_id: String, pub fragment_id: u64, pub row_offset: Option, + pub row_id: Option, pub row_address: Option, pub column: String, pub function: String, @@ -621,6 +868,8 @@ pub struct FunctionErrorRecord { pub table_version: u64, pub error_type: String, pub error_message: String, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub created_at_millis: i64, } @@ -650,9 +899,15 @@ impl FunctionErrorRecord { impl From for FunctionErrorRecord { fn from(record: lancedb::function::FunctionErrorRecord) -> Self { Self { + first_seen_at_millis: record.first_seen_at_millis, + last_seen_at_millis: record.last_seen_at_millis, + quarantined: record.quarantined, + input: record.input.map(|value| value.to_string()), + attempts: record.attempts, job_id: record.job_id, fragment_id: record.fragment_id, row_offset: record.row_offset, + row_id: record.row_id, row_address: record.row_address, column: record.column, function: record.function, @@ -660,6 +915,7 @@ impl From for FunctionErrorRecord { table_version: record.table_version, error_type: record.error_type, error_message: record.error_message, + traceback: record.traceback, created_at_millis: record.created_at_millis, } } @@ -700,9 +956,12 @@ impl From for FunctionErrorFragment { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrors { + pub workflow_version: Option, + pub error_groups_json: String, pub records: Vec, pub fragments: Vec, pub truncated: bool, + pub page_token: Option, } #[pymethods] @@ -720,9 +979,147 @@ impl FunctionErrors { impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { Self { + workflow_version: errors.workflow_version, + error_groups_json: serde_json::to_string(&errors.error_groups) + .expect("serializable Function error groups"), records: errors.records.into_iter().map(Into::into).collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, + page_token: errors.page_token, + } + } +} + +/// Exact immutable Function revision attached to a table output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnVersionStatus { + pub name: String, + pub namespace_path: Vec, + pub object_id: String, + pub location: String, + pub version: String, + pub manifest_digest: String, +} + +impl From for FunctionColumnVersionStatus { + fn from(function: lancedb::function::FunctionVersionRef) -> Self { + Self { + name: function.name, + namespace_path: function.namespace_path, + object_id: function.object_id, + location: function.location, + version: function.version, + manifest_digest: function.manifest_digest, + } + } +} + +/// Latest matching refresh Job projected for a Function output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + pub automatic: Option, + pub completed_at_millis: Option, + pub failure: Option, +} + +impl From for FunctionColumnLastRefreshJob { + fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self { + Self { + job_id: job.job_id, + state: job.state, + automatic: job.automatic, + completed_at_millis: job.completed_at_millis, + failure: job.failure.map(Into::into), + } + } +} + +/// Automatic-refresh projection for a Function output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + pub interval_seconds: Option, + pub active_job_id: Option, + pub state: String, + pub failure_streak: u32, + pub effective_cooldown_millis: Option, + pub blocked_reason: Option, + pub next_run_at_millis: Option, + pub next_run_at_reason: Option, +} + +impl From for FunctionColumnAutoRefreshStatus { + fn from(status: lancedb::table::FunctionColumnAutoRefreshStatus) -> Self { + Self { + enabled: status.enabled, + interval_seconds: status.interval_seconds, + active_job_id: status.active_job_id, + state: status.state.as_str().to_string(), + failure_streak: status.failure_streak, + effective_cooldown_millis: status.effective_cooldown_millis, + blocked_reason: status + .blocked_reason + .map(|reason| reason.as_str().to_string()), + next_run_at_millis: status.next_run_at_millis, + next_run_at_reason: status.next_run_at_reason, + } + } +} + +/// Exact four-way status of one Function output at one table version. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: u64, + pub rows: u64, + pub fresh: u64, + pub stale: u64, + pub never_computed: u64, + pub failed: u64, + pub last_refresh_job: Option, + pub last_failure_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +#[pymethods] +impl FunctionColumnStatus { + pub fn __repr__(&self) -> String { + format!( + "FunctionColumnStatus(column={:?}, table_version={}, rows={}, fresh={}, stale={}, never_computed={}, failed={})", + self.column, + self.table_version, + self.rows, + self.fresh, + self.stale, + self.never_computed, + self.failed + ) + } +} + +impl From for FunctionColumnStatus { + fn from(status: lancedb::table::FunctionColumnStatus) -> Self { + Self { + column: status.column, + binding_id: status.binding_id, + function: status.function.into(), + table_version: status.table_version, + rows: status.rows, + fresh: status.fresh, + stale: status.stale, + never_computed: status.never_computed, + failed: status.failed, + last_refresh_job: status.last_refresh_job.map(Into::into), + last_failure_job: status.last_failure_job.map(Into::into), + auto_refresh: status.auto_refresh.into(), } } } @@ -943,6 +1340,15 @@ impl PyBlobFile { .map_err(|e| blob_file_error("tell", e)) } + fn set_buffer_size(self_: PyRef<'_, Self>, size: usize) -> PyResult<()> { + self_.ensure_open()?; + let inner = self_.inner.clone(); + self_ + .py() + .detach(move || block_on(async move { inner.set_buffer_size(size).await })) + .map_err(|e| blob_file_error("set_buffer_size", e)) + } + fn size(self_: PyRef<'_, Self>) -> u64 { self_.inner.size() } @@ -1162,7 +1568,15 @@ impl Table { }) } - #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false))] + pub fn schema_sync(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let schema = self_.py().detach(move || { + block_on_interruptible(async move { inner.schema().await.infer_error() }) + })?; + Python::attach(|py| schema.to_pyarrow(py).map(|obj| obj.unbind())) + } + + #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))] pub fn add<'a>( self_: PyRef<'a, Self>, data: PyScannable, @@ -1170,6 +1584,7 @@ impl Table { progress: Option>, write_parallelism: Option, allow_external_blob_outside_bases: bool, + retries: Option, ) -> PyResult> { let mut op = self_ .inner_ref()? @@ -1182,6 +1597,9 @@ impl Table { } else { return Err(PyValueError::new_err(format!("Invalid mode: {}", mode))); } + if let Some(retries) = retries { + op = op.retries(retries); + } if let Some(write_parallelism) = write_parallelism { op = op.write_parallelism(write_parallelism); } @@ -1315,7 +1733,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index<'a>( self_: PyRef<'a, Self>, column: String, @@ -1324,6 +1743,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1332,6 +1752,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } @@ -1348,7 +1769,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index_async<'a>( self_: PyRef<'a, Self>, column: String, @@ -1357,6 +1779,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1365,6 +1788,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } @@ -1428,6 +1852,46 @@ impl Table { }) } + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None, parameters=None))] + pub fn prewarm_data_async<'py>( + self_: PyRef<'py, Self>, + columns: Option>, + filter: Option, + concurrency: Option<&Bound<'py, PyAny>>, + parameters: Option>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); + options.filter = filter; + options.parameters = parameters.map(|parameters| parameters.0); + options.concurrency = positive_u32_integer(concurrency, "concurrency")?; + future_into_py(self_.py(), async move { + let job = inner.prewarm_data_async(options).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None, parameters=None))] + pub fn explain_prewarm_data<'py>( + self_: PyRef<'py, Self>, + columns: Option>, + filter: Option, + concurrency: Option<&Bound<'py, PyAny>>, + parameters: Option>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); + options.filter = filter; + options.parameters = parameters.map(|parameters| parameters.0); + options.concurrency = positive_u32_integer(concurrency, "concurrency")?; + future_into_py(self_.py(), async move { + let plan = inner.explain_prewarm_data(options).await.infer_error()?; + serde_json::to_string(&plan).map_err(|error| PyRuntimeError::new_err(error.to_string())) + }) + } + pub fn list_indices(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -1560,6 +2024,22 @@ impl Table { ) } + #[pyo3(signature = (from_version, to_version=None))] + pub fn delta( + self_: PyRef<'_, Self>, + from_version: LanceVersion, + to_version: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let delta = inner + .delta(from_version, to_version.map(Into::into)) + .await + .infer_error()?; + Ok(TableDelta::new(delta)) + }) + } + pub fn list_versions(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -1605,6 +2085,15 @@ impl Table { }) } + /// Return an independent handle pinned to the currently selected snapshot. + pub fn _checkout_current(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let current = inner.checkout_current().await.infer_error()?; + Ok(Self::new(current)) + }) + } + #[pyo3(signature = (version=None))] pub fn restore( self_: PyRef<'_, Self>, @@ -1665,14 +2154,28 @@ impl Table { } /// Read blob bytes for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids))] + #[pyo3(signature = (column, row_ids, *, version=None, snapshot_identity=None))] pub fn fetch_blobs( self_: PyRef<'_, Self>, column: String, row_ids: Vec, + version: Option, + snapshot_identity: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { + let inner = match (version, snapshot_identity) { + (None, None) => inner, + (Some(version), Some(identity)) => inner + .query_snapshot_with_identity(version, &identity) + .await + .infer_error()?, + _ => { + return Err(PyValueError::new_err( + "deferred blob reads require both query version and snapshot identity", + )); + } + }; let blobs: LargeBinaryArray = inner .fetch_blobs(column.as_str(), &row_ids) .await @@ -1719,18 +2222,40 @@ impl Table { } /// Open lazy blob handles for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids))] + #[pyo3(signature = (column, row_ids, buffer_size=None, *, version=None, snapshot_identity=None))] pub fn fetch_blob_files( self_: PyRef<'_, Self>, column: String, row_ids: Vec, + buffer_size: Option, + version: Option, + snapshot_identity: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { + let inner = match (version, snapshot_identity) { + (None, None) => inner, + (Some(version), Some(identity)) => inner + .query_snapshot_with_identity(version, &identity) + .await + .infer_error()?, + _ => { + return Err(PyValueError::new_err( + "deferred blob reads require both query version and snapshot identity", + )); + } + }; let handles = inner .fetch_blob_files(column.as_str(), &row_ids) .await .infer_error()?; + if let Some(size) = buffer_size { + for file in handles.iter().flatten() { + file.set_buffer_size(size) + .await + .map_err(|e| blob_file_error("set_buffer_size", e))?; + } + } Ok(handles .into_iter() .map(|handle| { @@ -1743,16 +2268,22 @@ impl Table { }) } - #[pyo3(signature = (descriptor))] + #[pyo3(signature = (descriptor, buffer_size=None))] pub fn open_blob_file<'py>( self_: PyRef<'py, Self>, descriptor: &str, + buffer_size: Option, ) -> PyResult> { let descriptor: BlobDescriptor = serde_json::from_str(descriptor) .map_err(|error| PyValueError::new_err(format!("invalid blob descriptor: {error}")))?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let file = inner.open_blob_file(&descriptor).await.infer_error()?; + if let Some(size) = buffer_size { + file.set_buffer_size(size) + .await + .map_err(|e| blob_file_error("set_buffer_size", e))?; + } Ok(PyBlobFile { inner: Arc::new(file), closed: AtomicBool::new(false), @@ -1760,6 +2291,60 @@ impl Table { }) } + /// Explain Enterprise version cleanup without submitting a job. + #[pyo3(signature = (min_age_seconds=None))] + pub fn explain_cleanup<'py>( + self_: PyRef<'py, Self>, + min_age_seconds: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = lancedb::table::CleanupOptions::new(); + options.min_age_seconds = min_age_seconds; + future_into_py(self_.py(), async move { + let plan = inner.explain_cleanup(options).await.infer_error()?; + serde_json::to_string(&plan) + .map_err(|error| pyo3::exceptions::PyRuntimeError::new_err(error.to_string())) + }) + } + + /// Submit Enterprise version cleanup and retain its durable job and result. + #[pyo3(signature = (min_age_seconds=None))] + pub fn cleanup_async<'py>( + self_: PyRef<'py, Self>, + min_age_seconds: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = lancedb::table::CleanupOptions::new(); + options.min_age_seconds = min_age_seconds; + future_into_py(self_.py(), async move { + let job = inner.cleanup_async(options).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + + /// Submit remote compaction and retain its durable job and actual result. + #[pyo3(signature = (compaction_options=None))] + pub fn compact_async<'py>( + self_: PyRef<'py, Self>, + compaction_options: Option<&Bound<'py, PyDict>>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let target_specified = compaction_options + .map(|options| options.contains("target_rows_per_fragment")) + .transpose()? + .unwrap_or(false); + let options = parse_compaction_options(compaction_options)?; + let mut overrides = + lancedb::table::optimize::CompactionOverrides::try_from(options).infer_error()?; + if !target_specified { + overrides.target_rows_per_fragment = None; + } + future_into_py(self_.py(), async move { + let job = inner.compact_async(overrides).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + /// Optimize the on-disk data by compacting and pruning old data, for better performance. #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))] pub fn optimize<'py>( @@ -1769,6 +2354,10 @@ impl Table { compaction_options: Option<&Bound<'py, PyDict>>, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); + let target_specified = compaction_options + .map(|options| options.contains("target_rows_per_fragment")) + .transpose()? + .unwrap_or(false); let compaction_options = parse_compaction_options(compaction_options)?; let older_than = if let Some(ms) = cleanup_since_ms { if ms > i64::MAX as u64 { @@ -1783,10 +2372,22 @@ impl Table { None }; future_into_py(self_.py(), async move { - let stats = inner - .optimize_full(compaction_options, older_than, None, delete_unverified) - .await - .infer_error()?; + let stats = if inner.as_native().is_some() { + inner + .optimize_full(compaction_options, older_than, None, delete_unverified) + .await + } else { + let mut overrides = + lancedb::table::optimize::CompactionOverrides::try_from(compaction_options) + .infer_error()?; + if !target_specified { + overrides.target_rows_per_fragment = None; + } + inner + .optimize_full_with_overrides(overrides, older_than, None, delete_unverified) + .await + } + .infer_error()?; let compaction_stats = stats.compaction.unwrap(); let prune_stats = stats.prune.unwrap(); Ok(OptimizeStats { @@ -1804,10 +2405,12 @@ impl Table { }) } + #[pyo3(signature = (data, parameters, retries=None))] pub fn execute_merge_insert<'a>( self_: PyRef<'a, Self>, data: Bound<'a, PyAny>, parameters: MergeInsertParams, + retries: Option, ) -> PyResult> { let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; let on = parameters.on.iter().map(|s| s.as_str()).collect::>(); @@ -1830,6 +2433,9 @@ impl Table { if let Some(timeout) = parameters.timeout { builder.timeout(timeout); } + if let Some(retries) = retries { + builder.retries(retries); + } if let Some(use_index) = parameters.use_index { builder.use_index(use_index); } @@ -2064,17 +2670,28 @@ impl Table { }) } - #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] - pub fn add_computed_columns( - self_: PyRef<'_, Self>, + #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] + #[allow(clippy::too_many_arguments)] + pub fn add_computed_columns<'py>( + self_: PyRef<'py, Self>, columns: Vec<(String, String)>, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, - ) -> PyResult> { + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, + ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let options = ComputedColumnOptions { auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), auto_refresh_interval_seconds, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, }; options.validate().infer_error()?; future_into_py(self_.py(), async move { @@ -2091,28 +2708,43 @@ impl Table { }) } - #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] - pub fn add_function_columns( - self_: PyRef<'_, Self>, - application_json: String, - output_name: Option, + #[pyo3(signature = (bindings, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] + #[allow(clippy::too_many_arguments)] + pub fn add_function_columns<'py>( + self_: PyRef<'py, Self>, + bindings: Vec<(String, Option)>, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, - ) -> PyResult> { - let application = - lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?; + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, + ) -> PyResult> { + let bindings = bindings + .into_iter() + .map(|(json, name)| { + Ok(( + lancedb::function::FunctionApplication::from_json(&json).infer_error()?, + name, + )) + }) + .collect::>>()?; let inner = self_.inner_ref()?.clone(); let options = ComputedColumnOptions { auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), auto_refresh_interval_seconds, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, }; options.validate().infer_error()?; future_into_py(self_.py(), async move { - let builder = match output_name { - Some(name) => inner.add_columns().function_as(name, application), - None => inner.add_columns().function(application), - }; - let result = builder + let result = inner + .add_columns() + .function_bindings(bindings) .computed_options(options) .execute() .await @@ -2121,15 +2753,66 @@ impl Table { }) } - #[pyo3(signature = (column, *, batch_size=None, gpu_class=None, gpu_count=None))] - pub fn refresh_column( - self_: PyRef<'_, Self>, + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, total_cpu_millis=None, total_memory_bytes=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, total_gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, max_job_attempts=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] + #[allow(clippy::too_many_arguments)] + pub fn refresh_column<'py>( + self_: PyRef<'py, Self>, column: String, + r#where: Option, batch_size: Option, + max_concurrency: Option>, + publication_interval_rows: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + supervisor_resources: Option>, + planning_workers: Option>, gpu_class: Option, - gpu_count: Option, - ) -> PyResult> { - let options = refresh_column_options(batch_size, gpu_class, gpu_count)?; + gpu_count: Option, + total_gpu_count: Option, + retry_policy: Option, + error_policy: Option, + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, + max_job_attempts: Option>, + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, + ) -> PyResult> { + let options = refresh_column_options(RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, + where_clause: r#where, + batch_size, + max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, + publication_interval_rows, + total_cpu_millis, + total_memory_bytes, + supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?, + planning_workers: parse_planning_workers(planning_workers.as_ref())?, + gpu_class, + gpu_count, + total_gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + max_job_attempts: positive_u32_integer(max_job_attempts.as_ref(), "max_job_attempts")?, + })?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let result = inner @@ -2140,15 +2823,66 @@ impl Table { }) } - #[pyo3(signature = (column, *, batch_size=None, gpu_class=None, gpu_count=None))] - pub fn refresh_column_async( - self_: PyRef<'_, Self>, + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, total_cpu_millis=None, total_memory_bytes=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, total_gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, max_job_attempts=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] + #[allow(clippy::too_many_arguments)] + pub fn refresh_column_async<'py>( + self_: PyRef<'py, Self>, column: String, + r#where: Option, batch_size: Option, + max_concurrency: Option>, + publication_interval_rows: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + supervisor_resources: Option>, + planning_workers: Option>, gpu_class: Option, - gpu_count: Option, - ) -> PyResult> { - let options = refresh_column_options(batch_size, gpu_class, gpu_count)?; + gpu_count: Option, + total_gpu_count: Option, + retry_policy: Option, + error_policy: Option, + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, + max_job_attempts: Option>, + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, + ) -> PyResult> { + let options = refresh_column_options(RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, + where_clause: r#where, + batch_size, + max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, + publication_interval_rows, + total_cpu_millis, + total_memory_bytes, + supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?, + planning_workers: parse_planning_workers(planning_workers.as_ref())?, + gpu_class, + gpu_count, + total_gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + max_job_attempts: positive_u32_integer(max_job_attempts.as_ref(), "max_job_attempts")?, + })?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let job = inner @@ -2159,18 +2893,30 @@ impl Table { }) } - #[pyo3(signature = (job_id=None, column=None, limit=None))] + pub fn resume_refresh(self_: PyRef<'_, Self>, job_id: String) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let job = inner.resume_refresh(job_id).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + + #[pyo3(signature = (job_id=None, column=None, limit=None, history=false, page_token=None))] pub fn function_errors( self_: PyRef<'_, Self>, job_id: Option, column: Option, limit: Option, + history: bool, + page_token: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let request = lancedb::function::FunctionErrorsRequest { job_id, column, limit, + history, + page_token, }; future_into_py(self_.py(), async move { let errors = inner.function_errors(request).await.infer_error()?; @@ -2178,11 +2924,109 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false))] + #[pyo3(signature = (column, *, quarantined=true, job_id=None, error_type=None, after_attempts=None))] + pub fn quarantine_function_errors( + self_: PyRef<'_, Self>, + column: String, + quarantined: bool, + job_id: Option, + error_type: Option, + after_attempts: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + inner + .quarantine_function_errors( + &column, + lancedb::function::FunctionQuarantineOptions { + quarantined, + job_id, + error_type, + after_attempts, + }, + ) + .await + .infer_error() + }) + } + + #[pyo3(signature = (column, *, limit=None, version=None))] + pub fn function_provenance( + self_: PyRef<'_, Self>, + column: String, + limit: Option, + version: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let result = inner + .function_provenance( + &column, + lancedb::function::FunctionProvenanceOptions { limit, version }, + ) + .await + .infer_error()?; + serde_json::to_string(&result) + .map_err(|error| PyRuntimeError::new_err(error.to_string())) + }) + } + + #[pyo3(signature = (column=None))] + pub fn column_statuses( + self_: PyRef<'_, Self>, + column: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let statuses = inner + .function_column_statuses(column.as_deref()) + .await + .infer_error()?; + Ok(statuses + .into_iter() + .map(FunctionColumnStatus::from) + .collect::>()) + }) + } + + pub fn column_status(self_: PyRef<'_, Self>, column: String) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let status = inner.function_column_status(&column).await.infer_error()?; + Ok(FunctionColumnStatus::from(status)) + }) + } + + #[pyo3(signature = (column, timeout=None))] + pub fn wait_column_fresh<'py>( + self_: PyRef<'py, Self>, + column: String, + timeout: Option>, + ) -> PyResult> { + let timeout = timeout + .map(|timeout| timeout.extract::()) + .transpose()?; + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let status = inner + .wait_for_function_column(&column, timeout) + .await + .infer_error()?; + Ok(FunctionColumnStatus::from(status)) + }) + } + + #[pyo3(signature = (source_version=None, *, full=false, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] + #[allow(clippy::too_many_arguments)] pub fn refresh_materialized_view( self_: PyRef<'_, Self>, source_version: Option, full: bool, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2190,6 +3034,21 @@ impl Table { .await .infer_error()?; let mut builder = view.refresh().full(full); + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); + } + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); + } + if let Some(value) = total_gpu_count { + builder = builder.total_gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } if let Some(version) = source_version { builder = builder.source_version(version); } @@ -2198,11 +3057,17 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false))] + #[pyo3(signature = (source_version=None, *, full=false, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))] + #[allow(clippy::too_many_arguments)] pub fn refresh_materialized_view_async( self_: PyRef<'_, Self>, source_version: Option, full: bool, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2210,6 +3075,21 @@ impl Table { .await .infer_error()?; let mut builder = view.refresh().full(full); + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); + } + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); + } + if let Some(value) = total_gpu_count { + builder = builder.total_gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } if let Some(version) = source_version { builder = builder.source_version(version); } @@ -2377,6 +3257,103 @@ pub enum LanceVersion { Tag(String), } +impl From for DeltaRef { + fn from(version: LanceVersion) -> Self { + match version { + LanceVersion::Version(version) => Self::Version(version), + LanceVersion::Tag(tag) => Self::Tag(tag), + } + } +} + +/// Streaming row changes between two table versions. +#[pyclass] +pub struct TableDelta { + inner: Arc, +} + +impl TableDelta { + fn new(inner: LanceDbTableDelta) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + +#[pymethods] +impl TableDelta { + /// The version this delta starts from (exclusive). + pub fn begin_version(&self) -> u64 { + self.inner.begin_version() + } + + /// The version this delta ends at (inclusive). + pub fn end_version(&self) -> u64 { + self.inner.end_version() + } + + pub fn inserted_rows(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.inserted_rows().await.infer_error()?; + Ok(crate::arrow::RecordBatchStream::new(stream.into())) + }) + } + + pub fn updated_rows(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.updated_rows().await.infer_error()?; + Ok(crate::arrow::RecordBatchStream::new(stream.into())) + }) + } + + pub fn upserted_rows(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.upserted_rows().await.infer_error()?; + Ok(crate::arrow::RecordBatchStream::new(stream.into())) + }) + } + + pub fn deleted_row_ids(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.deleted_row_ids().await.infer_error()?; + Ok(crate::arrow::RecordBatchStream::new(stream.into())) + }) + } + + pub fn list_transactions(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let transactions = inner.list_transactions().await.infer_error()?; + Python::attach(|py| { + let output = PyList::empty(py); + for transaction in transactions { + let item = PyDict::new(py); + item.set_item("read_version", transaction.read_version)?; + item.set_item("uuid", transaction.uuid)?; + item.set_item("operation", transaction.operation.name())?; + item.set_item("tag", transaction.tag)?; + match transaction.transaction_properties { + Some(properties) => { + let py_properties = PyDict::new(py); + for (key, value) in properties.iter() { + py_properties.set_item(key, value)?; + } + item.set_item("transaction_properties", py_properties)?; + } + None => item.set_item("transaction_properties", py.None())?, + } + output.append(item)?; + } + Ok(output.unbind()) + }) + }) + } +} + #[derive(FromPyObject)] #[pyo3(from_item_all)] pub struct MergeInsertParams { @@ -2434,9 +3411,14 @@ impl Tags { }) } - pub fn create(self_: PyRef, tag: String, version: u64) -> PyResult> { + #[pyo3(signature = (tag, version=None))] + pub fn create(self_: PyRef, tag: String, version: Option) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { + let version = match version { + Some(version) => version, + None => inner.version().await.infer_error()?, + }; let mut tags = inner.tags().await.infer_error()?; tags.create(tag.as_str(), version).await.infer_error()?; Ok(()) @@ -2473,6 +3455,35 @@ impl Branches { } } +/// Add the from_tag hint to a native branch lookup failure. +/// +/// The caller only invokes this for a native `NotFound`, which identifies an +/// unresolved branch path. A missing version is `VersionNotFound`, and a REST +/// 404 is an ambiguous `TableNotFound`, so neither gets the hint. The original +/// exception class and message are preserved apart from the added note. +fn add_from_tag_hint(error: PyErr, branch: &str) -> PyErr { + let hint = format!("If '{branch}' is a tag, pass from_tag='{branch}' instead of from_ref."); + Python::attach(|py| { + let value = error.value(py); + if value.hasattr("add_note").unwrap_or(false) + && value.call_method1("add_note", (hint.clone(),)).is_ok() + { + return error; + } + // Python 3.10 has no BaseException.add_note. Native branch lookup + // failures are runtime errors with one string argument, so append the + // hint to that message without changing the exception class. + let Ok(args) = value.getattr("args") else { + return error; + }; + let Ok(original) = args.get_item(0).and_then(|arg| arg.extract::()) else { + return error; + }; + let _ = value.setattr("args", (format!("{original}\n{hint}"),)); + error + }) +} + #[pymethods] impl Branches { pub fn list(self_: PyRef<'_, Self>) -> PyResult> { @@ -2493,18 +3504,42 @@ impl Branches { }) } - #[pyo3(signature = (name, from_ref=None, from_version=None))] + #[pyo3(signature = (name, from_ref=None, from_version=None, *, from_tag=None))] pub fn create( self_: PyRef<'_, Self>, name: String, from_ref: Option, from_version: Option, + from_tag: Option, ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let from = Ref::Version(from_ref, from_version); - let table = inner.create_branch(&name, from).await.infer_error()?; - Ok(Table::new(table)) + let from_branch = if from_tag.is_none() { + from_ref.clone() + } else { + None + }; + let from = match from_tag { + Some(tag) => Ref::Tag(tag), + None => Ref::Version(from_ref, from_version), + }; + match inner.create_branch(&name, from).await { + Ok(table) => Ok(Table::new(table)), + Err(error) => { + // A missing branch is a native NotFound. A missing version + // is VersionNotFound, and a remote 404 is an ambiguous + // TableNotFound, so only the native branch case hints. + let missing_branch = matches!( + &error, + lancedb::Error::Lance { source } if source.is_not_found() + ); + let error = Err::<(), _>(error).infer_error().unwrap_err(); + match from_branch { + Some(branch) if missing_branch => Err(add_from_tag_hint(error, &branch)), + _ => Err(error), + } + } + } }) } diff --git a/python/src/util.rs b/python/src/util.rs index 2145c0f14..44efa165a 100644 --- a/python/src/util.rs +++ b/python/src/util.rs @@ -9,6 +9,7 @@ use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, pyfunction, }; +use rattler_conda_types::{MatchSpec, ParseStrictness}; /// A wrapper around a rust builder /// @@ -61,6 +62,13 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> { .map_err(|e| PyValueError::new_err(e.to_string())) } +#[pyfunction(name = "_validate_conda_requirement")] +pub fn validate_conda_requirement(requirement: &str) -> PyResult<()> { + MatchSpec::from_str(requirement, ParseStrictness::Lenient) + .map(|_| ()) + .map_err(|error| PyValueError::new_err(error.to_string())) +} + /// Parse field references with the same identifier syntax as Lance writes. #[pyfunction(name = "_parse_field_path")] pub fn parse_field_path(path: &str) -> PyResult> { @@ -70,3 +78,14 @@ pub fn parse_field_path(path: &str) -> PyResult> { /// A wrapper around a LanceDB type to allow it to be used in Python #[derive(Debug, Clone)] pub struct PyLanceDB(pub T); +/// Validate the Function retry wire contract using the same rules as Rust APIs. +#[pyo3::pyfunction] +pub fn validate_function_retry_policy(json: &str) -> pyo3::PyResult<()> { + let policy: lancedb::function::FunctionRetryPolicy = + serde_json::from_str(json).map_err(|error| { + pyo3::exceptions::PyValueError::new_err(format!("invalid retry_policy: {error}")) + })?; + policy + .validate() + .map_err(|error| pyo3::exceptions::PyValueError::new_err(error.to_string())) +} diff --git a/python/uv.lock b/python/uv.lock index 2bc641cca..90b13bcb2 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1,21 +1,12 @@ version = 1 -revision = 3 -requires-python = ">=3.10" +revision = 5 +requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.12' and python_full_version < '3.14'", + "python_full_version < '3.12'", ] [[package]] @@ -24,8 +15,7 @@ version = "1.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "huggingface-hub" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "packaging" }, { name = "psutil" }, @@ -69,7 +59,6 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "aiohappyeyeballs" }, { name = "aiosignal" }, - { name = "async-timeout", marker = "python_full_version < '3.11'" }, { name = "attrs" }, { name = "frozenlist" }, { name = "multidict" }, @@ -79,24 +68,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/82/78/8ea7308cac6934de8c74a14f3d5f65d1c89287426688be79538d0e5c013d/aiohttp-3.14.1.tar.gz", hash = "sha256:307f2cff90a764d329e77040603fa032db89c5c24fdad50c4c15334cba744035", size = 7955794, upload-time = "2026-06-07T21:09:35.529Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6d/67/58ded4b3f2e10f94972d8928050c85330e249a31dd45a0e5f3c0e9c3fa05/aiohttp-3.14.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:8f6bb621e5863cfe8fe5ff5468002d200ec31f30f1280b259dc505b02595099e", size = 766140, upload-time = "2026-06-07T21:05:37.471Z" }, - { url = "https://files.pythonhosted.org/packages/18/68/4ae5b4e08943f316594bb68da89957d3baf5760588fa09509594bd777e4b/aiohttp-3.14.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:4f7215cb3933784f79ed20e5f050e15984f390424339b22375d5a53c933a0491", size = 519430, upload-time = "2026-06-07T21:05:40.751Z" }, - { url = "https://files.pythonhosted.org/packages/cb/c1/316c8f3549dbe5245f92bfd523ec6f32dd4d98cafe21df3f6a19b1184c75/aiohttp-3.14.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d9d4e294455b23a68c9b8f042d0e8e377a265bcb15332753695f6e5b6819e0ce", size = 514406, upload-time = "2026-06-07T21:05:42.111Z" }, - { url = "https://files.pythonhosted.org/packages/5a/ee/fb0ac28684e8d753b83c8a4eebc19a5846912aa0a4daaabb6a9936363840/aiohttp-3.14.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b238af795833d5731d049d82bc84b768ae6f8f97f0495963b3ed9935c5901cc3", size = 1703649, upload-time = "2026-06-07T21:05:43.427Z" }, - { url = "https://files.pythonhosted.org/packages/3b/57/aa2beab673331f111885db8a7b69dfe3ab0e53e446a0ace18ca694b4dc58/aiohttp-3.14.1-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e4e5e0ae56914ecdbf446493addefc0159053dd53962cef37d7839f37f73d505", size = 1675126, upload-time = "2026-06-07T21:05:44.897Z" }, - { url = "https://files.pythonhosted.org/packages/47/ea/dad128abe365e79be03b16ed464198ac73e0d257e8260c6f7d6f31cbef26/aiohttp-3.14.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:092e4ce3619a7c6dee52a6bdabda973d9b34b66781f840ce93c7e0cec30cf521", size = 1771558, upload-time = "2026-06-07T21:05:46.405Z" }, - { url = "https://files.pythonhosted.org/packages/63/f3/b5b4e10327cb85d34d24232c6b71b64602f190b3ccb238a043ac6b187dac/aiohttp-3.14.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bb33777ea21e8b7ecde0e6fc84f598be0a1192eab1a63bc746d75aa75d38e7bd", size = 1856631, upload-time = "2026-06-07T21:05:47.844Z" }, - { url = "https://files.pythonhosted.org/packages/2b/9d/93294c3045775c708ac8310eb3d3622a11d2951345ad590d532d62a1faa4/aiohttp-3.14.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23119f8fd4f5d16902ed459b63b100bcd269628075162bddac56cc7b5273b3fb", size = 1714139, upload-time = "2026-06-07T21:05:49.982Z" }, - { url = "https://files.pythonhosted.org/packages/29/c4/93067c85a0373492ce8e577435203c5947c454af074ac48ed4f3a1b9dd4a/aiohttp-3.14.1-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:57fc6745a4b7d0f5a9eb4f40a69718be6c0bc1b8368cc9fe89e90118719f4f42", size = 1588321, upload-time = "2026-06-07T21:05:51.431Z" }, - { url = "https://files.pythonhosted.org/packages/c4/39/9ff91aaf02af8b7b8222a987466da539f154c3e01732c22b5f5a20a8ee66/aiohttp-3.14.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:6fd35beba67c4183b09375c5fff9accb47524191a244a99f95fd4472f5402c2b", size = 1670375, upload-time = "2026-06-07T21:05:53.109Z" }, - { url = "https://files.pythonhosted.org/packages/aa/e4/77452a3676b8d99ac1375f77691d6bf65ea6e9f4b201b82ef77c916dc767/aiohttp-3.14.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:672b9d65f42eb877f5c3f234a4547e4e1a226ca8c2eed879bb34670a0ce51192", size = 1690933, upload-time = "2026-06-07T21:05:54.902Z" }, - { url = "https://files.pythonhosted.org/packages/7d/84/b0059a7c7fc05ea23f3bc1596ba91c12f79588b9450564a24cac37536d0a/aiohttp-3.14.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:24ba13339fed9251d9b1a1bec8c7ab84c0d1675d79d33501e11f94f8b9a84e05", size = 1740798, upload-time = "2026-06-07T21:05:56.458Z" }, - { url = "https://files.pythonhosted.org/packages/8f/3a/e2a513ecbfc362591caa51a7f7e011b3bfc8938b388ae44cd95560d36999/aiohttp-3.14.1-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:94da27378da0610e341c4d30de29a191672683cc82b8f9556e8f7c7212a020fe", size = 1576412, upload-time = "2026-06-07T21:05:57.953Z" }, - { url = "https://files.pythonhosted.org/packages/a1/10/08f1654f538f93d36dcac66310a06eefce4641cdafca83f9f0a5317be254/aiohttp-3.14.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:52cdac9432d8b4a719f35094a818d95adcae0f0b4fe9b9b921909e0c87de9e7d", size = 1750199, upload-time = "2026-06-07T21:05:59.488Z" }, - { url = "https://files.pythonhosted.org/packages/99/e4/d91b70c57d8b8e9611e4a2e52238ca3698d3dc1c2efe25b7a9bf594ac584/aiohttp-3.14.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:672ac254412a24d0d0cf00a9e6c238877e4be5e5fa2d188832c1244f45f31966", size = 1699356, upload-time = "2026-06-07T21:06:01.131Z" }, - { url = "https://files.pythonhosted.org/packages/3d/f1/15340176f35ff61b95dbe34020bcf43f9e624a2d7bbac934715ff97d2033/aiohttp-3.14.1-cp310-cp310-win32.whl", hash = "sha256:2fe3607e71acc6ebb0ec8e492a247bf7a291226192dc0084236dfc12478916f6", size = 458939, upload-time = "2026-06-07T21:06:02.86Z" }, - { url = "https://files.pythonhosted.org/packages/c3/c2/a2f1ec5b37f903109e43ae2862268cfe4a67a60c1b2cf43169fcdff5995f/aiohttp-3.14.1-cp310-cp310-win_amd64.whl", hash = "sha256:30099eda75a53c32efb0920e9c33c195314d2cc1c680fbfd30894932ac5f27df", size = 482583, upload-time = "2026-06-07T21:06:04.666Z" }, - { url = "https://files.pythonhosted.org/packages/d0/7a/7b56f6732ef79530afaa72aa335d41b67c8d79b946995f0b11ad72985435/aiohttp-3.14.1-cp310-cp310-win_arm64.whl", hash = "sha256:5a837f49d901f9e368651b676912bff1104ed8c1a83b280bcd7b29adccef5c9c", size = 453470, upload-time = "2026-06-07T21:06:06.322Z" }, { url = "https://files.pythonhosted.org/packages/26/dd/bf526e6f0a1120dd6f2df2e97bacfe4d358f13d17a0ff5847301a1375a51/aiohttp-3.14.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:aa00140699487bd435fde4342d85c94cb256b7cd3a5b9c3396c67f19922afda2", size = 765225, upload-time = "2026-06-07T21:06:07.957Z" }, { url = "https://files.pythonhosted.org/packages/8f/e1/a2872aa55495a70f61310d411541c6ee23812d9a884e000c716e1bc3edbf/aiohttp-3.14.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1c1af67559445498b502030c35c59db59966f47041ca9de5b4e707f86bd10b5f", size = 518743, upload-time = "2026-06-07T21:06:09.749Z" }, { url = "https://files.pythonhosted.org/packages/5b/e7/c60c7b209e509cc787de3cea0550a518538cfc08003e1c1e14c1c63fff71/aiohttp-3.14.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d44ec478e713ee7f29b439f7eb8dc2b9d4079e11ae114d2c2ac3d5daf30516c8", size = 514139, upload-time = "2026-06-07T21:06:11.26Z" }, @@ -232,16 +203,15 @@ wheels = [ [[package]] name = "anyio" -version = "4.14.1" +version = "4.16.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3b/72/5562aabb8dd7181e8e860622a38bea08d17842b99ecd4c91f84ac95251b0/anyio-4.14.1.tar.gz", hash = "sha256:8d648a3544c1a700e3ff78615cd679e4c5c3f149904287e73687b2596963629e", size = 254831, upload-time = "2026-06-24T20:56:06.017Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/7b/90df4a0a816d98d6ea26f559d87836d494a2cf1fcf063be67df50a7bcc30/anyio-4.14.1-py3-none-any.whl", hash = "sha256:4e5533c5b8ff0a24f5d7a176cbe6877129cd183893f66b537f8f227d10527d72", size = 124875, upload-time = "2026-06-24T20:56:04.413Z" }, + { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" }, ] [[package]] @@ -271,15 +241,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/39/e7eaf1799466a4aef85b6a4fe7bd175ad2b1c6345066aa33f1f58d4b18d0/asttokens-3.0.1-py3-none-any.whl", hash = "sha256:15a3ebc0f43c2d0a50eeafea25e19046c68398e487b9f1f5b517f7c0f40f976a", size = 27047, upload-time = "2025-11-15T16:43:16.109Z" }, ] -[[package]] -name = "async-timeout" -version = "5.0.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a5/ae/136395dfbfe00dfc94da3f3e136d0b13f394cba8f4841120e34226265780/async_timeout-5.0.1.tar.gz", hash = "sha256:d9321a7a3d5a6a5e187e824d2fa0793ce379a202935782d555d6e9d2735677d3", size = 9274, upload-time = "2024-11-06T16:41:39.6Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/ba/e2081de779ca30d473f21f5b30e0e737c438205440784c7dfc81efc2b029/async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c", size = 6233, upload-time = "2024-11-06T16:41:37.9Z" }, -] - [[package]] name = "attrs" version = "26.1.0" @@ -369,15 +330,6 @@ 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 = "backports-asyncio-runner" -version = "1.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/8e/ff/70dca7d7cb1cbc0edb2c6cc0c38b65cba36cccc491eca64cabd5fe7f8670/backports_asyncio_runner-1.2.0.tar.gz", hash = "sha256:a5aa7b2b7d8f8bfcaa2b57313f70792df84e32a2a746f585213373f900b42162", size = 69893, upload-time = "2025-07-02T02:27:15.685Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/59/76ab57e3fe74484f48a53f8e337171b4a2349e506eabe136d7e01d059086/backports_asyncio_runner-1.2.0-py3-none-any.whl", hash = "sha256:0da0a936a8aeb554eccb426dc55af3ba63bcdc69fa1a600b5bb305413a4477b5", size = 12313, upload-time = "2025-07-02T02:27:14.263Z" }, -] - [[package]] name = "backrefs" version = "7.0" @@ -476,18 +428,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/57/5f/ff100cae70ebe9d8df1c01a00e510e45d9adb5c1fdda84791b199141de97/cffi-2.1.0.tar.gz", hash = "sha256:efc1cdd798b1aaf39b4610bba7aad28c9bea9b910f25c784ccf9ec1fa719d1f9", size = 531036, upload-time = "2026-07-06T21:34:30.382Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c0/e9/6d7724983b3d5a0908dbf74f64038ade77c18646ff6636ec7894fd392ce1/cffi-2.1.0-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:b65f590ef2a44640f9a05dbb548a429b4ade77913ce683ac8b1480777658a6c0", size = 183837, upload-time = "2026-07-06T21:32:09.655Z" }, - { url = "https://files.pythonhosted.org/packages/69/aa/24580a278de21fd7322635556334d9b535f1cbc00b0a3919447cdf464c65/cffi-2.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:164bff1657b2a74f0b6d54e11c9b375bc97b931f2ca9c43fcf875838da1570dd", size = 184226, upload-time = "2026-07-06T21:32:11.196Z" }, - { url = "https://files.pythonhosted.org/packages/88/a9/02cae418ec4beb282ace11958d9d4737793439d561fadc7e6d56f2e2b354/cffi-2.1.0-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:c941bb58d5a6e1c3892d86e42927ed6c180302f07e6d395d08c416e594b98b46", size = 211107, upload-time = "2026-07-06T21:32:12.328Z" }, - { url = "https://files.pythonhosted.org/packages/3b/30/c806937ed5e4c2c7ac30d9d6b76b5dc57ff8b75d83800d9bb11a8253cf2a/cffi-2.1.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a016194dbe13d14ee9556e734b772d8d67b947092b268d757fd4290e3ba2dfc2", size = 218733, upload-time = "2026-07-06T21:32:13.67Z" }, - { url = "https://files.pythonhosted.org/packages/f9/cf/398272b8bbfd58aa314fda5a7f1cdbb26d1d78ae324a11211521315dd1f0/cffi-2.1.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:03e9810d18c646077e501f661b682fbf5dee4676048527ca3cffe66faa9960dd", size = 205543, upload-time = "2026-07-06T21:32:15.148Z" }, - { url = "https://files.pythonhosted.org/packages/45/ca/f91641185cdd90c36d317a9dc7f85e88ef8682d8b300977baff5e23c35d8/cffi-2.1.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:19c54ac121cad98450b4896fa9a43ee0180d57bc4bc911a33db6cab1efab6cd3", size = 205460, upload-time = "2026-07-06T21:32:16.479Z" }, - { url = "https://files.pythonhosted.org/packages/38/66/04781a77b411f0bb5b234d62c1814754ab75ebe455ccff1b08e8d7aae98f/cffi-2.1.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4d433a51f1870e43a13b6732f92aaf540ff77c2015097c78556f75a2d6c030e0", size = 218760, upload-time = "2026-07-06T21:32:17.98Z" }, - { url = "https://files.pythonhosted.org/packages/d0/9a/bb1d5ed9c3fcae158e9f6391bf309c95d98c2ac37ed56573228471d0af5e/cffi-2.1.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3d7f118b5adbfdfead90c25822690b02bc8074fba949bb7858bec4ebd55adb43", size = 221230, upload-time = "2026-07-06T21:32:19.407Z" }, - { url = "https://files.pythonhosted.org/packages/41/aa/3c1409cdd26094efacd1c36c66e0a6eb9d4296e4fd4f9901b8b2042f4323/cffi-2.1.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:c5f5df567f6eb216de69be06ce55c8b714090fae02b18a3b40da8163b8c5fa9c", size = 213524, upload-time = "2026-07-06T21:32:20.828Z" }, - { url = "https://files.pythonhosted.org/packages/fa/75/74dfb7c3fc6ebbd408038476bd4c1d7e925c62614e7b9c534ecc34218288/cffi-2.1.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:11b3fb55f4f8ad92274ed26705f65d8f91457de71f5380061eb6d125a768fecd", size = 220341, upload-time = "2026-07-06T21:32:21.9Z" }, - { url = "https://files.pythonhosted.org/packages/70/b6/9003c33a3e7d2c1306f5962e646457dcfe5a8cd8fce6bbe02d7af25db783/cffi-2.1.0-cp310-cp310-win32.whl", hash = "sha256:9d72af0cf10a76a600a9690078fe31c63b9588c8e86bf9fd353f713c84b5db0f", size = 174578, upload-time = "2026-07-06T21:32:23.073Z" }, - { url = "https://files.pythonhosted.org/packages/8a/26/710688310447531c7a22f857c7f79d9855ec18b03e04494ced723fb37e2f/cffi-2.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:fb62edb5bb52cca65fab91a63afa7561607120d26090a7e8fda6fb9f064726da", size = 185071, upload-time = "2026-07-06T21:32:24.671Z" }, { url = "https://files.pythonhosted.org/packages/d3/67/85c89a59ba36a671e79638f44d466749f08179266a57e4f2ffdf92174072/cffi-2.1.0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:02cb7ff33ded4f1532476731f89ede53e2e488a8e6205515a82144246ffa7dcc", size = 183845, upload-time = "2026-07-06T21:32:26.32Z" }, { url = "https://files.pythonhosted.org/packages/ea/dd/e3b0baa2d3d6a857ac72b7efbf18e32e487c9cdafcc13049ad765495b15e/cffi-2.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f5bce581e6b8c235e566a14768a943b172ada3ed73537bb0c0be1edee312d4e7", size = 184186, upload-time = "2026-07-06T21:32:28.025Z" }, { url = "https://files.pythonhosted.org/packages/65/68/9f3ef890cf3c6ab97bd531c5677f67613d302165d16f8142b2811782a614/cffi-2.1.0-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:30b65779d598c370374fefabf138d456fd6f3216bfa7bedfab1ba82025b0cd93", size = 211892, upload-time = "2026-07-06T21:32:29.565Z" }, @@ -592,19 +532,6 @@ version = "3.4.8" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/20/56/10a88e00039537d74bd420f0457c52ab8f58a1af56126e3b9f1b1c8c4724/charset_normalizer-3.4.8.tar.gz", hash = "sha256:d9bf144d6faf12c70d58e47f7512992ae2882b820031d6cef68152deb645bf2d", size = 151790, upload-time = "2026-07-06T15:27:58.477Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/55/f7590fd3a3b9c80b7106876bc868827304462cbf9b40b0f3d664c04c4e67/charset_normalizer-3.4.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:ad320cccde0bbe430fe3a0e5ef3f17b16ef7cfe496603d7b3a153aa204e093e5", size = 321984, upload-time = "2026-07-06T15:25:42.469Z" }, - { url = "https://files.pythonhosted.org/packages/08/b2/1d6ebdf9dfb4f3be6777bee1589eb6c3784a5fb7389ebc511b5ca649f540/charset_normalizer-3.4.8-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:825e5c2fb57d2065250e12dfeb414d780e7da242b371d5a78814d3ef40d63fde", size = 216216, upload-time = "2026-07-06T15:25:44.047Z" }, - { url = "https://files.pythonhosted.org/packages/91/b3/be7c7a3d28ae7ccbf9c51641337114457f507005474f0caee4b26abe2be4/charset_normalizer-3.4.8-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:98a91c8dce056a858385cf147eb196ae4d2b35315c2bfc8151ff4027707247e1", size = 238408, upload-time = "2026-07-06T15:25:45.19Z" }, - { url = "https://files.pythonhosted.org/packages/e8/cf/f6bfb15e3feeb47a180d0dffdaa81ff119c5380d86733a35c0e5a31de503/charset_normalizer-3.4.8-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f2bd1869ae6cd2793e51bfacebd1495595c1c007c2dfcfd6874b4a804f29bc7c", size = 233221, upload-time = "2026-07-06T15:25:46.608Z" }, - { url = "https://files.pythonhosted.org/packages/39/f8/a9af1b0e78a4d2a3974eac8289d97f83526346571f5ef3edda13bcff262d/charset_normalizer-3.4.8-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:511851c35e4ec8f4be773acd2c0222a7ec6b63971fea8988103632896f174b4b", size = 223559, upload-time = "2026-07-06T15:25:47.896Z" }, - { url = "https://files.pythonhosted.org/packages/b3/d9/5b8d04939351d4b17047fb6a7fcb44460ccce66663759a1a17fad6d5c250/charset_normalizer-3.4.8-cp310-cp310-manylinux_2_31_armv7l.whl", hash = "sha256:bae1f52a68a5dcc1fcb65db69895638654be9a45716c47a5a192552a52925662", size = 207714, upload-time = "2026-07-06T15:25:49.034Z" }, - { url = "https://files.pythonhosted.org/packages/1c/a1/5b691a5a3cfbc0696ec7be6a438ace83ead88a57024845593eb25fb1a39c/charset_normalizer-3.4.8-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f44633a518ef0889dc7e28dde2e18616f8e932e2d17d9c9ccdbbef40aa3a6794", size = 221394, upload-time = "2026-07-06T15:25:50.177Z" }, - { url = "https://files.pythonhosted.org/packages/d3/d2/6d34df842bf58e0ecd0a5c71ded2596f32b506e606856faf7b8d88ba6c91/charset_normalizer-3.4.8-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0d08f2b7171517aa86ddf0eaba25bc7ac8576d401f2da8764403cf0e876f796b", size = 218970, upload-time = "2026-07-06T15:25:51.317Z" }, - { url = "https://files.pythonhosted.org/packages/d3/2d/a13e5faa0de1cc86a001d1e6b5547688c1a0ca4f8858ff8803516d14ac73/charset_normalizer-3.4.8-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:bde2fd87539f4a023ae8d699f51cd3d359ba79a42953fc03afde80bedf52ffc0", size = 209442, upload-time = "2026-07-06T15:25:52.507Z" }, - { url = "https://files.pythonhosted.org/packages/a9/67/8f2bb932f518d444ad75ca17ce6192c4324b95ee8b4c73072387eb2c96e5/charset_normalizer-3.4.8-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:ba191a019f567339cff1cf861e311a5c442477d91f2ece3ad683f7b004976aae", size = 225986, upload-time = "2026-07-06T15:25:53.911Z" }, - { url = "https://files.pythonhosted.org/packages/84/8d/39ecee39ee858b0a07a3cff1f36c72a632b2fb70f46117042adbf675bdc5/charset_normalizer-3.4.8-cp310-cp310-win32.whl", hash = "sha256:dfce5e536054cf15a14576ecb08913e2e9ceff4cc1da2919694cdb2b45b5c64f", size = 150674, upload-time = "2026-07-06T15:25:55.09Z" }, - { url = "https://files.pythonhosted.org/packages/c0/38/bd10fa06f989f65e9b7e4868179e31ffb5e473049bbbf37e22256ad7503f/charset_normalizer-3.4.8-cp310-cp310-win_amd64.whl", hash = "sha256:06238276da3d880d858a4221d6b968bccc18ca3cbe71f6c5c2de86abb7929ffe", size = 162057, upload-time = "2026-07-06T15:25:56.259Z" }, - { url = "https://files.pythonhosted.org/packages/07/2f/16ff1dc626483a27ac40ca1ae350d01891db496eb574a26a9738e16052db/charset_normalizer-3.4.8-cp310-cp310-win_arm64.whl", hash = "sha256:3731936f612754018aeb99fafc4381b6d80ed9165f2dba719c4e1afca0177048", size = 152815, upload-time = "2026-07-06T15:25:57.389Z" }, { url = "https://files.pythonhosted.org/packages/94/b5/7f10929c45e2d0d0dc78bead98458c271af3e028e66b16441de88829a8b7/charset_normalizer-3.4.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ca832d525a2a52542048111cb44e0dea595b9ad53ad542020aa770f308427b92", size = 316812, upload-time = "2026-07-06T15:25:58.71Z" }, { url = "https://files.pythonhosted.org/packages/2a/b4/8e936a5e19d7e7b19db29aeed0988b481dc745eed3437829780f6ec98ce9/charset_normalizer-3.4.8-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ab07eb7b564635602734c3ef0e8d2db9d59cbbce54f5dc42b8f11aa1f56ce364", size = 213580, upload-time = "2026-07-06T15:26:00.121Z" }, { url = "https://files.pythonhosted.org/packages/27/b8/dbc3b3c4796e4e29e193c5d7e100bb8ebfa66267994c01ba1eaaa3ebc474/charset_normalizer-3.4.8-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6e88da593ea098194ea08f58924b716a9ae0c39058edad8c5c9b0bafa39fbd56", size = 235244, upload-time = "2026-07-06T15:26:01.402Z" }, @@ -736,14 +663,12 @@ name = "colpali-engine" version = "0.3.17" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "peft" }, { name = "pillow" }, { name = "requests" }, - { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "scipy", version = "1.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "torch" }, { name = "torchvision" }, @@ -769,15 +694,6 @@ version = "2.8" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/e3/66/7e97aa77af7cf6afbff26e3651b564fe41932599bc2d3dce0b2f73d4829a/crc32c-2.8.tar.gz", hash = "sha256:578728964e59c47c356aeeedee6220e021e124b9d3e8631d95d9a5e5f06e261c", size = 48179, upload-time = "2025-10-17T06:20:13.61Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/a0/28b4686a8db0bb0f77970f4c6ccede90d1d5740a1d4b4703bd54c3e75655/crc32c-2.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:2c0f4eb01fe7c0a3e3f973a418e04d52101bb077dd77626fd80c658ec60aaf95", size = 66321, upload-time = "2025-10-17T06:18:53.543Z" }, - { url = "https://files.pythonhosted.org/packages/76/1f/1697f5b8b770f715ed9b264d79e36b4f77ae0527f81f3c749ef08937a32e/crc32c-2.8-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6baefcfbca82b1a9678455416da24f18629769a76920c640d5a538620a7d12bb", size = 62985, upload-time = "2025-10-17T06:18:54.97Z" }, - { url = "https://files.pythonhosted.org/packages/e0/e5/333cfa5ffa8d5779733aced2b984b5e5139b4a8ceaa2c6bc563e9a1092f3/crc32c-2.8-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d7f959fcf6c5aad1c4a653ee1a50f05760dab1d1c35d98ec4d7f0f68643f7612", size = 61517, upload-time = "2025-10-17T06:18:55.795Z" }, - { url = "https://files.pythonhosted.org/packages/e1/d8/362a009e8140dd926a153b44d56753e3aa7cb50aca243779a84adadbff11/crc32c-2.8-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9bb678507a4e4cf3f0506607b046ecc4ed1c58a19e08a3fb3c2d25441c480bf1", size = 79385, upload-time = "2025-10-17T06:18:56.598Z" }, - { url = "https://files.pythonhosted.org/packages/4a/9f/0d4ea3aa71ffb15f1285669d23024cc40779388ce32157d339dc2584491c/crc32c-2.8-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1a16f7ffa4c242a909558565567cbba95148603717b53538ea299c98da68e7a9", size = 80965, upload-time = "2025-10-17T06:18:57.384Z" }, - { url = "https://files.pythonhosted.org/packages/20/44/d77657aaca4a2c0283f2356a3da6f8e91b003567bb8f09daaf540cbf192f/crc32c-2.8-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0184369aad562d801f91f454c81f56b9ecb966f6b96684c4d6cf82fc8741d2ad", size = 79993, upload-time = "2025-10-17T06:18:58.503Z" }, - { url = "https://files.pythonhosted.org/packages/ab/c0/07017a93ebf85d9408028b7e03ef96d5c6bfb14cb77cfe90d35eedcc1501/crc32c-2.8-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:86d2eeb5f0189bd803720abe7387019328ea34c4acde62999e5723f789bc316b", size = 79243, upload-time = "2025-10-17T06:18:59.273Z" }, - { url = "https://files.pythonhosted.org/packages/c7/1a/b3c5ac4cf2fd1f82395173d0bd8e1a15d09f0bc1eccdf10ea7f8caaccd67/crc32c-2.8-cp310-cp310-win32.whl", hash = "sha256:51da61904a9e753780a2e6011885677d601db1fa840be4b68799643a113e6f08", size = 64888, upload-time = "2025-10-17T06:19:00.089Z" }, - { url = "https://files.pythonhosted.org/packages/b6/f2/60c45fc7bb2221d3c93c7a872e921be591f40d45228fe46f879b1d8c0424/crc32c-2.8-cp310-cp310-win_amd64.whl", hash = "sha256:b2d6a1f2500daaf2e4b08f97ad0349aa2eff5faaaa5fd3350314a26eade334cd", size = 66639, upload-time = "2025-10-17T06:19:00.974Z" }, { url = "https://files.pythonhosted.org/packages/dc/0b/5e03b22d913698e9cc563f39b9f6bbd508606bf6b8e9122cd6bf196b87ea/crc32c-2.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:e560a97fbb96c9897cb1d9b5076ef12fc12e2e25622530a1afd0de4240f17e1f", size = 66329, upload-time = "2025-10-17T06:19:01.771Z" }, { url = "https://files.pythonhosted.org/packages/6b/38/2fe0051ffe8c6a650c8b1ac0da31b8802d1dbe5fa40a84e4b6b6f5583db5/crc32c-2.8-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6762d276d90331a490ef7e71ffee53b9c0eb053bd75a272d786f3b08d3fe3671", size = 62988, upload-time = "2025-10-17T06:19:02.953Z" }, { url = "https://files.pythonhosted.org/packages/3e/30/5837a71c014be83aba1469c58820d287fc836512a0cad6b8fdd43868accd/crc32c-2.8-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:60670569f5ede91e39f48fb0cb4060e05b8d8704dd9e17ede930bf441b2f73ef", size = 61522, upload-time = "2025-10-17T06:19:03.796Z" }, @@ -841,59 +757,71 @@ wheels = [ [[package]] name = "cryptography" -version = "49.0.0" +version = "50.0.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1f/99/d1c90d6041656cc6ee229dc99cd67fd0cd5aec3c5f7d72fffc27cc750054/cryptography-49.0.0.tar.gz", hash = "sha256:f89660a348f4f78a92366240a61404e337586ef7f5909a2fef59ca88ef505493", size = 854345, upload-time = "2026-06-12T20:02:30.512Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9b/22/adf66990e63584a68dfb50c24f48a125c07b1699899381c8151e63ed458c/cryptography-49.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:966fe0e9c67490071f14c0d2b1cb2dfb3023c5ce39457343931415f08382f2db", size = 4032100, upload-time = "2026-06-12T20:02:32.143Z" }, - { url = "https://files.pythonhosted.org/packages/09/41/3797cfaf69cae04a13ee78ebd83f0678d9c02b4779d21ce24445326f1a69/cryptography-49.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:36d1709f992593689b45bda411498d62c6e365f2ca00b84657d4dadd24de16db", size = 4692978, upload-time = "2026-06-12T20:01:21.305Z" }, - { url = "https://files.pythonhosted.org/packages/e6/8b/43011f7ebe515a8aa20d61f290a326cd890c2e738e16e59eaff8d9c3a412/cryptography-49.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0e959b578856a3924bc0cbb710fc12c387b9412a951389f3ca61704a9e25f325", size = 4716422, upload-time = "2026-06-12T20:01:48.566Z" }, - { url = "https://files.pythonhosted.org/packages/4a/91/01ce7303a4579e6d3a6abef01bd322848e9ea7a219adcabc5048b9033571/cryptography-49.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:53ecee2e23f7169b6117e99fc8a944e5e50f79e69758a83b52a00cb98ab2b2d2", size = 4700503, upload-time = "2026-06-12T20:02:47.091Z" }, - { url = "https://files.pythonhosted.org/packages/62/99/a2c95cf8293f07491e9e27c20cc4dcd18176d944e674679adeb1d0173fd6/cryptography-49.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:2eda353d8a27bcbcaa4cbed18994a74ab4d19a2ca897db188ea269ab9b71419b", size = 5309779, upload-time = "2026-06-12T20:02:08.987Z" }, - { url = "https://files.pythonhosted.org/packages/20/2c/0622f20ff02b2ef32558733443805dc82fd4c275be01b2d19d14676f3a1b/cryptography-49.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2afe9051da7ae7bd5905da5a949280c7d2bb75682e188f650a9d0f2756b834c6", size = 4749683, upload-time = "2026-06-12T20:02:03.335Z" }, - { url = "https://files.pythonhosted.org/packages/a3/5b/c5246635d5fd3b64e0d45ae10e99fd32fe9676a79915ccfe5a61ba9af1a5/cryptography-49.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:0b82e28ee398a386f0807bba7884d30f25218855690f45115831bcce5d90822c", size = 4337874, upload-time = "2026-06-12T20:02:54.323Z" }, - { url = "https://files.pythonhosted.org/packages/6d/88/05563c7fe2e914e87d1a536d06fe83e66b4e1d95cb593e05aea375531da8/cryptography-49.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:ccac2bfebc306b862133e3bb71f3f6ee8bb525240089b2d952e4144b3a6d5da7", size = 4700283, upload-time = "2026-06-12T20:01:34.822Z" }, - { url = "https://files.pythonhosted.org/packages/c4/b6/d7696e4e890d6ae1469935164c9e5215c557671cb78d6e3f458ccceaa632/cryptography-49.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:d0527ce944105f257f605a827d6ebead966c752038b6e8656abb9c5edee6fc68", size = 5265844, upload-time = "2026-06-12T20:01:24.09Z" }, - { url = "https://files.pythonhosted.org/packages/a9/3c/f3ad17eecc1a57b0ba236dc01f90e783c51f4a2f35f64777cc4f47a184b2/cryptography-49.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:cbc77da8c523d5abd028635ba850a6966fcee2c82e2bf65a41d1d8afe0f98be9", size = 4749290, upload-time = "2026-06-12T20:01:30.848Z" }, - { url = "https://files.pythonhosted.org/packages/4f/01/339573cf1023163a400b0b5d16f6d507de413b9f60be6fd1b77feeaf6737/cryptography-49.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b87e65d263b3e5d3bb92a57e2a6638e2f31110fa7aa890c7b2dbba42248d0a3f", size = 4834612, upload-time = "2026-06-12T20:01:29.246Z" }, - { url = "https://files.pythonhosted.org/packages/71/fd/577302e213a1be9468f92d1afef66fcf1ef83d516819d9992ca547f592bd/cryptography-49.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:66ec79c3904820572d7e987abdf304281f141d37ad9a489b8e97066e7b9b6459", size = 4980804, upload-time = "2026-06-12T20:01:42.853Z" }, - { url = "https://files.pythonhosted.org/packages/1f/09/f42b1d190c5ba75f72062a387f8030d1d75f6ab035788f1d9c4b01de6525/cryptography-49.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:e5dfc1e64de5677cec922ffa8da89c546d0415bf6efdf081842e5d44c84e1f0e", size = 3810026, upload-time = "2026-06-12T20:02:39.262Z" }, - { url = "https://files.pythonhosted.org/packages/ec/9e/db72b3ae7fc9cfad53e630e56c6ae83b9b6ff0bf3718ffb8012d20b3aabf/cryptography-49.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:73a205dce83953d131a4aa1e0fd917a2fd1c5b1eef251e9d7152efefcbf5caf7", size = 4013892, upload-time = "2026-06-12T20:02:10.735Z" }, - { url = "https://files.pythonhosted.org/packages/86/12/c48a424f38db03027be9f7ed5c7dc5de9933dbee992865f98b13727a009d/cryptography-49.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:196ecd6a36e4e9aa10270393bb98d8df88fccee0bf1e5128b91ae4eb4375896d", size = 4678835, upload-time = "2026-06-12T20:02:48.743Z" }, - { url = "https://files.pythonhosted.org/packages/68/28/8a3ad4653662c93fc44dc4e5d8fd374c25c42e07b34bbfbadf49cf57a5a8/cryptography-49.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7abcee80084cda3f7691f3eb1ce480d8df49cec637b429aa35986c1de71738aa", size = 4697239, upload-time = "2026-06-12T20:02:56.03Z" }, - { url = "https://files.pythonhosted.org/packages/a8/b2/2193fc74f81aee4f9b62733133b73b5176718932ed8f2e4b03fa040480a6/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:4ae387c9cb68ea569ca17e490d66d8142b81c3cc814bf179974b7d146e490bbb", size = 4685593, upload-time = "2026-06-12T20:02:50.666Z" }, - { url = "https://files.pythonhosted.org/packages/47/f1/1d3eaa243bfc5de4a187b22aa8c048b3e4980bfbe830ac46e6bac2e66947/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:f37d847238971164fdbc68ade6f6574aecc9c0af714190e2083429ff68f4ce9d", size = 5289961, upload-time = "2026-06-12T20:01:46.468Z" }, - { url = "https://files.pythonhosted.org/packages/58/39/2d51306721330c486495853eda1c567880ff036de15a14c4b74f399934af/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:c2bc30226390d60ea19d9f82b19db005fe0452154a23c1c410c12ea801e43561", size = 4731145, upload-time = "2026-06-12T20:02:16.832Z" }, - { url = "https://files.pythonhosted.org/packages/17/50/983e838c7fd0d87fd8c969bcdd328edaf5f756e38df5281637424c155873/cryptography-49.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:07cab27cc7b7e0fd28e5e26bb9eeedde5c135c868b46de4a27845abe94af6122", size = 4321719, upload-time = "2026-06-12T20:02:52.611Z" }, - { url = "https://files.pythonhosted.org/packages/a7/f5/8f571d7e27c55bce9f76f026143bcb1e040a4233149ecca0bea5fa5dd5f7/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:b20133d204d2bb56ba047642199603876c872026ca53e79c35b83772ab2cc505", size = 4685209, upload-time = "2026-06-12T20:02:07.282Z" }, - { url = "https://files.pythonhosted.org/packages/e7/84/0e27016a6fc5a0886f797018b26aa42f40c09a82332bff77822a451deaaa/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:b970c6da94d5bb18629db453d14f2a1300f6bf59b61e9b82377931ef95504866", size = 5246285, upload-time = "2026-06-12T20:01:32.439Z" }, - { url = "https://files.pythonhosted.org/packages/11/2d/5e1fb307cb5931881516b464c98774b3f2c36b5d4bb9a2830253cf553cad/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:d8ecde755e2e91bf773fc94e8c9d730cd7f2007004cb492263a794ec3899a1c8", size = 4730441, upload-time = "2026-06-12T20:02:01.469Z" }, - { url = "https://files.pythonhosted.org/packages/e4/c0/bff5a02ee731d207d6a1ed51732549d8c53d2bc8da1d10ec6f2844201d68/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e3fb64c420688e5319ae25113a354015abbd8dffbfbc41781a1ea66fc7622ac3", size = 4815869, upload-time = "2026-06-12T20:01:36.574Z" }, - { url = "https://files.pythonhosted.org/packages/b9/26/814681d14248d95d73d5c3eea0c39a94eb8302df966f670a2c60de90974b/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:32703d93296f5c1f4b53349ad3a250c2cae0fdecd3a3dd5d47e616d8d616af27", size = 4960948, upload-time = "2026-06-12T20:02:18.688Z" }, - { url = "https://files.pythonhosted.org/packages/4c/fe/93ecac273d3738939d023612ad12cca9a3740a5345d69fda04134c43fd96/cryptography-49.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:33cd0565932807baddb67b96dbee92f2c374b5c89dee09fd74079aeb8c8dba61", size = 3799153, upload-time = "2026-06-12T20:01:39.059Z" }, - { url = "https://files.pythonhosted.org/packages/19/2a/5bb823f5bedcf80718cea7fbc95ec5515cca3769633c4b01a32be7f30e7c/cryptography-49.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ec5e529fb80935c94fe7b729f9972b50e351a0e6b50aa294fd5cabb109fcc29a", size = 4025947, upload-time = "2026-06-12T20:01:25.745Z" }, - { url = "https://files.pythonhosted.org/packages/3d/df/40577043ca124e17012f408ddddaeb213b856336ac82ddb3bc915f39e29f/cryptography-49.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f78ff2c9ed8dc2d036b0f4d640e22522213d047c1b14e61205a7e55c80a494d4", size = 4692429, upload-time = "2026-06-12T20:01:53.628Z" }, - { url = "https://files.pythonhosted.org/packages/2c/99/2d13299eb3dd27b02dcfaafcc91d6b5cb3329f7cbd6d8f51921acd566c1a/cryptography-49.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:35b151772baff2c74cba7fa290ceaff4c3b11c0c881eb93eb5dbc05a7cfbba18", size = 4700968, upload-time = "2026-06-12T20:02:45.383Z" }, - { url = "https://files.pythonhosted.org/packages/a5/4d/9c0cd02f95e2602dd5e563da149ee0830abef3537be8b34dc56281ebe27a/cryptography-49.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0f21641cf4b30fca7aee061ced0ec7ad7b073518088b7c9969a297c0ae796c69", size = 4697758, upload-time = "2026-06-12T20:01:41.13Z" }, - { url = "https://files.pythonhosted.org/packages/24/01/186c825898477d77e2324d5360fefe622ff1d8d1963ec0554e2cada8ec77/cryptography-49.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:9e82dcc8e56052715fb18b2429e3bca4823b1629136a2084fc45a9a5cecb9b64", size = 5298863, upload-time = "2026-06-12T20:02:24.579Z" }, - { url = "https://files.pythonhosted.org/packages/b8/7b/62cbbab75d0659865bf0273790031544a0b16c8072d258f9428dcd8190dc/cryptography-49.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:6f2debedf9ca60cf1d5bd466475638af5130f89965605cd818484d19987d3a21", size = 4735983, upload-time = "2026-06-12T20:01:50.14Z" }, - { url = "https://files.pythonhosted.org/packages/6c/72/3e798c064bc39e471008075d0f9bc9daf77a80879c092e4a8e170c585ed4/cryptography-49.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:8c25ceb16df5b9435f3f6a9829204985b0e0cbee3b48aacd432c7d2c850b44d9", size = 4334173, upload-time = "2026-06-12T20:01:44.743Z" }, - { url = "https://files.pythonhosted.org/packages/f0/ee/6fca21d1ac73e06f8bef71940abfd4d2f6472b4bca284d770f32bd4086f6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:28d8b15e6275f12c8a207dc309dfa957903c927d08d0cc937ee3f63f200693cc", size = 4697298, upload-time = "2026-06-12T20:02:20.918Z" }, - { url = "https://files.pythonhosted.org/packages/67/d0/a5fcd3515f0bae49a7b6d0413cc1bdccdcc1fc0047037a0d480642cdc5d6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6fc361c34fb6aac015ce19435876635e5c6d21db31998b0920f675f131e043b8", size = 5254338, upload-time = "2026-06-12T20:02:22.737Z" }, - { url = "https://files.pythonhosted.org/packages/a0/84/84fe36f19caf857d61cb7fc9c63035a47ffabd84ea12d1d393148efa3615/cryptography-49.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:2400ef9c9e2299a25614eb1dea3db54a69b1349efd043bfac9c67630d136df36", size = 4735650, upload-time = "2026-06-12T20:02:41.389Z" }, - { url = "https://files.pythonhosted.org/packages/6c/a0/db537264e234f7273a73ec020873d6d6b39dfd8a53db78b550ca8320440e/cryptography-49.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:67e1d20ad9ef3a563c59ef22e7a8a0b8210bd26604369ea4a30a7c66aefe504e", size = 4834820, upload-time = "2026-06-12T20:01:51.847Z" }, - { url = "https://files.pythonhosted.org/packages/93/77/8df9eb486495979bccecd1062e2eaf435250e84437040295b57d09048b0b/cryptography-49.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:42b0684e0e40cf26122427802486f6d93aea593612603a94fbf260c7eb1e9c1b", size = 4967968, upload-time = "2026-06-12T20:02:12.524Z" }, - { url = "https://files.pythonhosted.org/packages/c2/e6/f60198ea8d9dfa15fff9ed4ca02ce362f6eadd9ba757dcc50634c4257b63/cryptography-49.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:026ac7423e6fa66872d3bf889be5974507da3944f866f704fa200eadacd00001", size = 3785547, upload-time = "2026-06-12T20:02:26.847Z" }, - { url = "https://files.pythonhosted.org/packages/63/d3/4a83af35d65e3fad632c926fad684c193ea4398569ccb0bbbc7fe8f5dc9a/cryptography-49.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:fc1e275c2f1d97b1a6450b8b0ea3ebfa6e087a611c2b26cb2404d48588abab7b", size = 3993685, upload-time = "2026-06-12T20:02:14.883Z" }, - { url = "https://files.pythonhosted.org/packages/d6/a7/f9dac0ab7f80368c56993a7bf638ef9935f825c91902798481fac0898138/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:c83782480a4a9da4d0feb51950131ba32e12e70813848b3343f6e18c28a66838", size = 4676239, upload-time = "2026-06-12T20:02:28.793Z" }, - { url = "https://files.pythonhosted.org/packages/d7/70/2ba3769dd0ae167e2f33dfa9592d45db6ff9a61d62ca1a5b3d1bdd09068f/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b39efa323140595abd3ecca8529d321ae50f55f3aa3ba9cc81ea56a6011953d5", size = 4715584, upload-time = "2026-06-12T20:01:27.495Z" }, - { url = "https://files.pythonhosted.org/packages/94/64/2923570ac1c0bd3a737aa366ac3abbbbde273042308b8cde95e2364a6e6a/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:b47db11c2c3525083296069b98ac5221907455e989ae0c2e3008bde851921615", size = 4675885, upload-time = "2026-06-12T20:01:55.49Z" }, - { url = "https://files.pythonhosted.org/packages/ab/f8/614dc7e051418cfe53d55173c1e24c6b0085e89996fe90508c2fdf769aef/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:084ef1af862eb07ec46d25f68689f2102a9fc0e05ce7b80f14f5fe51e4eef0f6", size = 4715449, upload-time = "2026-06-12T20:02:05.469Z" }, - { url = "https://files.pythonhosted.org/packages/aa/50/a9caea39ad19c431c1a3f8a31114df65b260cdfe67786b6c7e7c040c4c44/cryptography-49.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:be9fcb48a55f023493482827d4f459bd263cc20efde64f204b97c123201850c6", size = 3783731, upload-time = "2026-06-12T20:02:43.319Z" }, + { url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" }, + { url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" }, + { url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" }, + { url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" }, + { url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" }, + { url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" }, + { url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" }, + { url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" }, + { url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" }, + { url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" }, + { url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" }, + { url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" }, + { url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" }, + { url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" }, + { url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" }, + { url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" }, + { url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" }, + { url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" }, + { url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" }, + { url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" }, + { url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" }, + { url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" }, + { url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" }, + { url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" }, + { url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" }, + { url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" }, + { url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" }, + { url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" }, + { url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" }, + { url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" }, + { url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" }, + { url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" }, + { url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" }, + { url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" }, + { url = "https://files.pythonhosted.org/packages/36/8b/e6d153808bf353e152abd2fd4d8f09670d956ac78379ac46e60d7efbf04c/cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81", size = 3873097, upload-time = "2026-09-30T15:29:56.097Z" }, + { url = "https://files.pythonhosted.org/packages/ca/1d/1271f287ff7170ddafc2aad36260c4eec20ccd2fea70f38455e9d56d427b/cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452", size = 3805376, upload-time = "2026-09-30T15:29:58.729Z" }, ] [[package]] @@ -901,11 +829,9 @@ name = "cuda-bindings" version = "13.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder", marker = "sys_platform == 'linux'" }, + { name = "cuda-pathfinder" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/a9/21/8464d133752951c154feafb3b65c297e7d80f301183d220bec4c830f1441/cuda_bindings-13.3.1-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:120fcc53d57903df529c3486962c56528cba5b7d6c57c99537320ed9922c8b86", size = 6073403, upload-time = "2026-05-29T23:11:36.22Z" }, - { url = "https://files.pythonhosted.org/packages/a8/1f/5ef51f5fbaa5d4d3201bb3d7555af028ec1aa4416275ccbf73c9e34e3d2d/cuda_bindings-13.3.1-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9851b0caa8bfd3bc6fa054eaf57bea7c8e9c3a62db2d2621224677f49f3c53d0", size = 6675244, upload-time = "2026-05-29T23:11:38.664Z" }, { url = "https://files.pythonhosted.org/packages/51/6b/457ca12dad3ee9bfcc9a545cfd6b64b359ba49de40f776f6e028e678f262/cuda_bindings-13.3.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5879712accf6e14bb01aa5e67440eb84998b8d104b509cc7a6dc0b8f656a474", size = 6053539, upload-time = "2026-05-29T23:11:43.19Z" }, { url = "https://files.pythonhosted.org/packages/95/7a/c5e3c34a409b148f5c0f5a4ea374158f95d488862c1dffedf9aa5c639df9/cuda_bindings-13.3.1-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:04436a9364059c84b8f9636f359eccda1cf814341f5b670c71d80d2f79dbc708", size = 6674166, upload-time = "2026-05-29T23:11:45.478Z" }, { url = "https://files.pythonhosted.org/packages/ce/67/5e7dba1ba576dd73da5dee894ca076ca5e959450dfff66d6d510a255d1f7/cuda_bindings-13.3.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7855c4868aabc0cfae28abbe83d56734bdfbd08f08fc234ac1912a12858bf49", size = 6025351, upload-time = "2026-05-29T23:11:49.685Z" }, @@ -936,37 +862,37 @@ wheels = [ [package.optional-dependencies] cublas = [ - { name = "nvidia-cublas", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cublas" }, ] cudart = [ - { name = "nvidia-cuda-runtime", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-runtime" }, ] cufft = [ - { name = "nvidia-cufft", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cufft" }, ] cufile = [ - { name = "nvidia-cufile", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cufile" }, ] cupti = [ - { name = "nvidia-cuda-cupti", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-cupti" }, ] curand = [ - { name = "nvidia-curand", marker = "sys_platform == 'linux'" }, + { name = "nvidia-curand" }, ] cusolver = [ - { name = "nvidia-cusolver", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusolver" }, ] cusparse = [ - { name = "nvidia-cusparse", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusparse" }, ] nvjitlink = [ - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink" }, ] nvrtc = [ - { name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-nvrtc" }, ] nvtx = [ - { name = "nvidia-nvtx", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvtx" }, ] [[package]] @@ -998,10 +924,6 @@ 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/fc/f3/6b1d4c71f4cbb5360009f928934a03b42906f28fc7b3f7f35f04e58acead/debugpy-1.8.21-cp310-cp310-macosx_15_0_x86_64.whl", hash = "sha256:8eeab7b5462f683452c57c0126aaa5ec4e974ddb705f39ba87dff8818c8e08f9", size = 2113873, upload-time = "2026-06-01T19:30:37.148Z" }, - { url = "https://files.pythonhosted.org/packages/1c/f2/17c3bf91cebc173bfbf5734cd2669723d0a35c0cf9d2fd2124546efeae83/debugpy-1.8.21-cp310-cp310-manylinux_2_34_x86_64.whl", hash = "sha256:0fddfdc130ac6d8bfc0415b0409822fa901c8f310e5c945ac5653a0352532344", size = 3004715, upload-time = "2026-06-01T19:30:38.888Z" }, - { url = "https://files.pythonhosted.org/packages/5a/22/1f8efd80c7b5909e760f9cfd0c9e8681d2d35d532f7c0a40760cd4da4a19/debugpy-1.8.21-cp310-cp310-win32.whl", hash = "sha256:72b5d676c4cbfac3bac5bb01c138a4656e843f93f03ce2a5f4e394ad49fbee73", size = 5303455, upload-time = "2026-06-01T19:30:40.52Z" }, - { url = "https://files.pythonhosted.org/packages/da/ce/54c79abd6cccef92fa7b43d97e3acafedf4d645557267ece05e948b5e4b8/debugpy-1.8.21-cp310-cp310-win_amd64.whl", hash = "sha256:a7fe47fd23da57b9e0bec3f4a8ee65a2dc55782455ed7f2141d75ab5d2eaeef5", size = 5331751, upload-time = "2026-06-01T19:30:42.146Z" }, { url = "https://files.pythonhosted.org/packages/89/fb/cbf306d6e07a313a91e7171a98669054502840931432c227cfd505ee367f/debugpy-1.8.21-cp311-cp311-macosx_15_0_universal2.whl", hash = "sha256:da456226c7b4c69e35dbe35dcee6623d912000a77816db7856a41af1c72a0264", size = 2203120, upload-time = "2026-06-01T19:30:43.964Z" }, { url = "https://files.pythonhosted.org/packages/aa/57/aa739bd4ad2cbf96aeb1b20b56918ddd5ae4c28b68709bfcd327f02123ee/debugpy-1.8.21-cp311-cp311-manylinux_2_34_x86_64.whl", hash = "sha256:f68b891688e61bdc08b8d364d919ff0051e0b94657b39dcd027bc3173edb7cdc", size = 3059958, upload-time = "2026-06-01T19:30:45.622Z" }, { url = "https://files.pythonhosted.org/packages/a8/31/453d2c9a23d133fe2c8ec7ca1d816ded52a913487fe3ffef7c01b4b706af/debugpy-1.8.21-cp311-cp311-win32.whl", hash = "sha256:f843a8b08c2edeaf9b1582eed4f25441af21a297c22ff16bf76a662557aa9c9e", size = 5236515, upload-time = "2026-06-01T19:30:47.461Z" }, @@ -1084,12 +1006,6 @@ version = "1.5.4" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/31/29/9bad86ed7aa812d8c822a27c15c355b6d5423b991feeec86ed18027b6daa/duckdb-1.5.4.tar.gz", hash = "sha256:f9e32f1cdd106793d79d190186bed9e75289d51e68bd9174e47c04bffedeab6f", size = 18046634, upload-time = "2026-06-17T10:48:52.499Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3c/ee/69340af74a3aa21838f14c16a0dd3e58461896ccba41f6bc7f0a01536e23/duckdb-1.5.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:3ddd9533ce80f9b851bdd6276960a9286166514a9ceca43d5bc2f0d5842c490d", size = 32656177, upload-time = "2026-06-17T10:47:31.044Z" }, - { url = "https://files.pythonhosted.org/packages/73/18/9da267ade389d4e7e533ac0c77b3a7041513a66efab93beb84f27627b0b8/duckdb-1.5.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:360f2542d09759c3739400f8b787e29b43ba0da665c21756216291458bf6fc59", size = 17318966, upload-time = "2026-06-17T10:47:33.688Z" }, - { url = "https://files.pythonhosted.org/packages/76/b4/ad73c1a396288e443b18af50819448060b318c1e933305167c1d7f98a507/duckdb-1.5.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0cf932055061e544d3fa27cc6c147da25f3f681ee5980157fb55e77d6c2d9c63", size = 15467572, upload-time = "2026-06-17T10:47:36.071Z" }, - { url = "https://files.pythonhosted.org/packages/6f/06/2c52ce3b97c3f21111f3c98a2121ed002e33f86488f55098a37825af6d4a/duckdb-1.5.4-cp310-cp310-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c2d58d39f5e65419cdc27e3875cba4a729a3bbf6bf4016aefb4a2a65335a1d42", size = 19344044, upload-time = "2026-06-17T10:47:38.174Z" }, - { url = "https://files.pythonhosted.org/packages/5a/7d/5c0cc66fb90a1b14474eebb5ab535eacc51cb20b0e45358348b51c07abc9/duckdb-1.5.4-cp310-cp310-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a9a10dc40469b9c0e458625d2a8359461a982c6151bb53ff259fea00c4695ad4", size = 21448215, upload-time = "2026-06-17T10:47:40.617Z" }, - { url = "https://files.pythonhosted.org/packages/3c/2c/16c3ea201855cdfb7dde52ea3678d0536861cb485ffad46cf345436d658d/duckdb-1.5.4-cp310-cp310-win_amd64.whl", hash = "sha256:3565550adbf160ef7a2ee3395470570182f11233983ad818bd7d5f9e349f92b2", size = 13132138, upload-time = "2026-06-17T10:47:43.085Z" }, { url = "https://files.pythonhosted.org/packages/56/bb/7921dabd50daef3969f14cd8a5a14c24eee337db7914a462f2defa8add92/duckdb-1.5.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3fb41d9cfccb7e44511eeeed263ae98143ca63bdb1ef84631ba637c314efa1b5", size = 32663142, upload-time = "2026-06-17T10:47:45.471Z" }, { url = "https://files.pythonhosted.org/packages/a6/83/2137765eaba6a9aefe3bb9848ddaac7407fe3ba19b292f98b31f3b7ab27f/duckdb-1.5.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8ba7b666bc9c78d6a930ee9f469024149f0c6a23fb7d2c3418aad6774339bec0", size = 17321485, upload-time = "2026-06-17T10:47:47.778Z" }, { url = "https://files.pythonhosted.org/packages/0e/b2/a02c1ee43fd7e8cf1fc2e3d377f3dcf9d4a3e58a4549557516e1866ff0da/duckdb-1.5.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9d9e6817fcbc09d2605a2c8c041ac7824d738d917c35a4d427e977647e1d7944", size = 15470820, upload-time = "2026-06-17T10:47:49.977Z" }, @@ -1120,18 +1036,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/dc/82/4d52f3f9f9703a226b26b80bdae3f6905aeefe5221bf1815fc93ff02ca25/duckdb-1.5.4-cp314-cp314-win_arm64.whl", hash = "sha256:0f8722346024e5d9f02b58bf7b0491a629f97fdc8a04a10e432940f471ee387a", size = 14449863, upload-time = "2026-06-17T10:48:50.18Z" }, ] -[[package]] -name = "exceptiongroup" -version = "1.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" }, -] - [[package]] name = "executing" version = "2.2.1" @@ -1147,12 +1051,6 @@ version = "1.12.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/6e/5b/ccb338db71f347e3bc031d268bf6dc41e5ead63b6997b8e72af92f05e18e/fastavro-1.12.2.tar.gz", hash = "sha256:3c79502d56cf6b76210032e1c53494ddfbc73c140bccf2ef4092b3f0825323ab", size = 1030127, upload-time = "2026-04-24T14:36:01.269Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3c/91/16c3508447e7cf9f413a6a01792a990ed94d17505fc80a7fb76027078aed/fastavro-1.12.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:c7c6d26c731a0e1e8e7d4ae8f13ae524eb6ec0e90d99c8147a19fdbae14eb807", size = 976824, upload-time = "2026-04-24T14:36:04.233Z" }, - { url = "https://files.pythonhosted.org/packages/2d/3a/97534561a1b4615366345ac066ad1f54698a59aa510eece3153c3a603d29/fastavro-1.12.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7caeecf519eff50f007ca4bee16b6e0a8252e5fe682c94432192a20867239888", size = 3185186, upload-time = "2026-04-24T14:36:06.395Z" }, - { url = "https://files.pythonhosted.org/packages/ee/e4/26512b52f58305b9d2194169de2e82c16d5131f0a0b6359e50d34faf4021/fastavro-1.12.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:731aefe6c4bf2bafa0798ef83927676d06e44d1d18202cfb56d63b40422ab900", size = 3196799, upload-time = "2026-04-24T14:36:09.028Z" }, - { url = "https://files.pythonhosted.org/packages/58/69/22f3b29a4555eb805a26f209f12532df8aafa48685d1cd1879aa42758d04/fastavro-1.12.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:f089f24225a28ddafa5cfad7c41cfa84db1a55f2d473370769a95c0e3bac60c9", size = 3112396, upload-time = "2026-04-24T14:36:11.401Z" }, - { url = "https://files.pythonhosted.org/packages/e9/2a/fc61ef522050e1079ccf1aee07192881f3b11129f5e2b76811fd4fc3bb2f/fastavro-1.12.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:653c4f90dd21d8a1e74309919e08934e420d9aef51d051d14bf5a1c0e8293c22", size = 3180452, upload-time = "2026-04-24T14:36:13.634Z" }, - { url = "https://files.pythonhosted.org/packages/a6/6a/43ce9d713e9f1122e19c80d94d0dc0a356b8562d33eea90081dac781dd97/fastavro-1.12.2-cp310-cp310-win_amd64.whl", hash = "sha256:030f17eb4c7978538a31b55dea451ceace851a88dc9816b1923f8fb8a260db4c", size = 445396, upload-time = "2026-04-24T14:36:15.243Z" }, { url = "https://files.pythonhosted.org/packages/89/77/058f3c93348624cb695399b27f3f0c1c3d1190586065797e4a48f75d4147/fastavro-1.12.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d48cd7094598a7e9d4297e8bf4bbe0dc9dc2ba4367d83dbb603e3b3c6aa35566", size = 974559, upload-time = "2026-04-24T14:36:17.172Z" }, { url = "https://files.pythonhosted.org/packages/a5/ef/08bbfa643addd2b98a9ce536613e2098928aa5e3ca098fd5b74f3c03b96a/fastavro-1.12.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:070c6134604bd7b6fd44409406ac50445339682b2e872885db2e859f92d22e93", size = 3352777, upload-time = "2026-04-24T14:36:19.679Z" }, { url = "https://files.pythonhosted.org/packages/d3/ec/55c11108529bdb59e635899f737651f729485ea5af36e128fb6560969c3d/fastavro-1.12.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2b73d50978d5e57416fa68461f9f3c8f39ea39e761cb1e12f919745adefe26a7", size = 3387036, upload-time = "2026-04-24T14:36:21.794Z" }, @@ -1217,22 +1115,6 @@ 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/83/4a/557715d5047da48d54e659203b9335be7bfaafda2c3f627b7c47e0b3aaf3/frozenlist-1.8.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b37f6d31b3dcea7deb5e9696e529a6aa4a898adc33db82da12e4c60a7c4d2011", size = 86230, upload-time = "2025-10-06T05:35:23.699Z" }, - { url = "https://files.pythonhosted.org/packages/a2/fb/c85f9fed3ea8fe8740e5b46a59cc141c23b842eca617da8876cfce5f760e/frozenlist-1.8.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ef2b7b394f208233e471abc541cc6991f907ffd47dc72584acee3147899d6565", size = 49621, upload-time = "2025-10-06T05:35:25.341Z" }, - { url = "https://files.pythonhosted.org/packages/63/70/26ca3f06aace16f2352796b08704338d74b6d1a24ca38f2771afbb7ed915/frozenlist-1.8.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a88f062f072d1589b7b46e951698950e7da00442fc1cacbe17e19e025dc327ad", size = 49889, upload-time = "2025-10-06T05:35:26.797Z" }, - { url = "https://files.pythonhosted.org/packages/5d/ed/c7895fd2fde7f3ee70d248175f9b6cdf792fb741ab92dc59cd9ef3bd241b/frozenlist-1.8.0-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f57fb59d9f385710aa7060e89410aeb5058b99e62f4d16b08b91986b9a2140c2", size = 219464, upload-time = "2025-10-06T05:35:28.254Z" }, - { url = "https://files.pythonhosted.org/packages/6b/83/4d587dccbfca74cb8b810472392ad62bfa100bf8108c7223eb4c4fa2f7b3/frozenlist-1.8.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:799345ab092bee59f01a915620b5d014698547afd011e691a208637312db9186", size = 221649, upload-time = "2025-10-06T05:35:29.454Z" }, - { url = "https://files.pythonhosted.org/packages/6a/c6/fd3b9cd046ec5fff9dab66831083bc2077006a874a2d3d9247dea93ddf7e/frozenlist-1.8.0-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c23c3ff005322a6e16f71bf8692fcf4d5a304aaafe1e262c98c6d4adc7be863e", size = 219188, upload-time = "2025-10-06T05:35:30.951Z" }, - { url = "https://files.pythonhosted.org/packages/ce/80/6693f55eb2e085fc8afb28cf611448fb5b90e98e068fa1d1b8d8e66e5c7d/frozenlist-1.8.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8a76ea0f0b9dfa06f254ee06053d93a600865b3274358ca48a352ce4f0798450", size = 231748, upload-time = "2025-10-06T05:35:32.101Z" }, - { url = "https://files.pythonhosted.org/packages/97/d6/e9459f7c5183854abd989ba384fe0cc1a0fb795a83c033f0571ec5933ca4/frozenlist-1.8.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c7366fe1418a6133d5aa824ee53d406550110984de7637d65a178010f759c6ef", size = 236351, upload-time = "2025-10-06T05:35:33.834Z" }, - { url = "https://files.pythonhosted.org/packages/97/92/24e97474b65c0262e9ecd076e826bfd1d3074adcc165a256e42e7b8a7249/frozenlist-1.8.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:13d23a45c4cebade99340c4165bd90eeb4a56c6d8a9d8aa49568cac19a6d0dc4", size = 218767, upload-time = "2025-10-06T05:35:35.205Z" }, - { url = "https://files.pythonhosted.org/packages/ee/bf/dc394a097508f15abff383c5108cb8ad880d1f64a725ed3b90d5c2fbf0bb/frozenlist-1.8.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:e4a3408834f65da56c83528fb52ce7911484f0d1eaf7b761fc66001db1646eff", size = 235887, upload-time = "2025-10-06T05:35:36.354Z" }, - { url = "https://files.pythonhosted.org/packages/40/90/25b201b9c015dbc999a5baf475a257010471a1fa8c200c843fd4abbee725/frozenlist-1.8.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:42145cd2748ca39f32801dad54aeea10039da6f86e303659db90db1c4b614c8c", size = 228785, upload-time = "2025-10-06T05:35:37.949Z" }, - { url = "https://files.pythonhosted.org/packages/84/f4/b5bc148df03082f05d2dd30c089e269acdbe251ac9a9cf4e727b2dbb8a3d/frozenlist-1.8.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:e2de870d16a7a53901e41b64ffdf26f2fbb8917b3e6ebf398098d72c5b20bd7f", size = 230312, upload-time = "2025-10-06T05:35:39.178Z" }, - { url = "https://files.pythonhosted.org/packages/db/4b/87e95b5d15097c302430e647136b7d7ab2398a702390cf4c8601975709e7/frozenlist-1.8.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:20e63c9493d33ee48536600d1a5c95eefc870cd71e7ab037763d1fbb89cc51e7", size = 217650, upload-time = "2025-10-06T05:35:40.377Z" }, - { url = "https://files.pythonhosted.org/packages/e5/70/78a0315d1fea97120591a83e0acd644da638c872f142fd72a6cebee825f3/frozenlist-1.8.0-cp310-cp310-win32.whl", hash = "sha256:adbeebaebae3526afc3c96fad434367cafbfd1b25d72369a9e5858453b1bb71a", size = 39659, upload-time = "2025-10-06T05:35:41.863Z" }, - { url = "https://files.pythonhosted.org/packages/66/aa/3f04523fb189a00e147e60c5b2205126118f216b0aa908035c45336e27e4/frozenlist-1.8.0-cp310-cp310-win_amd64.whl", hash = "sha256:667c3777ca571e5dbeb76f331562ff98b957431df140b54c85fd4d52eea8d8f6", size = 43837, upload-time = "2025-10-06T05:35:43.205Z" }, - { url = "https://files.pythonhosted.org/packages/39/75/1135feecdd7c336938bd55b4dc3b0dfc46d85b9be12ef2628574b28de776/frozenlist-1.8.0-cp310-cp310-win_arm64.whl", hash = "sha256:80f85f0a7cc86e7a54c46d99c9e1318ff01f4687c172ede30fd52d19d1da1c8e", size = 39989, upload-time = "2025-10-06T05:35:44.596Z" }, { url = "https://files.pythonhosted.org/packages/bc/03/077f869d540370db12165c0aa51640a873fb661d8b315d1d4d67b284d7ac/frozenlist-1.8.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84", size = 86912, upload-time = "2025-10-06T05:35:45.98Z" }, { url = "https://files.pythonhosted.org/packages/df/b5/7610b6bd13e4ae77b96ba85abea1c8cb249683217ef09ac9e0ae93f25a91/frozenlist-1.8.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9", size = 50046, upload-time = "2025-10-06T05:35:47.009Z" }, { url = "https://files.pythonhosted.org/packages/6e/ef/0e8f1fe32f8a53dd26bdd1f9347efe0778b0fddf62789ea683f4cc7d787d/frozenlist-1.8.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93", size = 50119, upload-time = "2025-10-06T05:35:48.38Z" }, @@ -1534,61 +1416,22 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/f3/ff/c9baf0997266d398ae08347951a2970e5e96ed6232ed0252f649f2b9a7eb/ibm_cos_sdk_s3transfer-2.14.3.tar.gz", hash = "sha256:2251ebfc4a46144401e431f4a5d9f04c262a0d6f95c88a8e71071da056e55f72", size = 139594, upload-time = "2025-08-01T06:35:46.403Z" } -[[package]] -name = "ibm-watsonx-ai" -version = "1.3.42" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] -dependencies = [ - { name = "cachetools", marker = "python_full_version < '3.11'" }, - { name = "certifi", marker = "python_full_version < '3.11'" }, - { name = "httpx", marker = "python_full_version < '3.11'" }, - { name = "ibm-cos-sdk", marker = "python_full_version < '3.11'" }, - { name = "lomond", marker = "python_full_version < '3.11'" }, - { name = "packaging", marker = "python_full_version < '3.11'" }, - { name = "pandas", version = "2.2.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "requests", marker = "python_full_version < '3.11'" }, - { name = "tabulate", marker = "python_full_version < '3.11'" }, - { name = "urllib3", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c7/56/2e3df38a1f13062095d7bde23c87a92f3898982993a15186b1bfecbd206f/ibm_watsonx_ai-1.3.42.tar.gz", hash = "sha256:ee5be59009004245d957ce97d1227355516df95a2640189749487614fef674ff", size = 688651, upload-time = "2025-10-01T13:35:41.527Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/36/b2/d9ab090ea3f4c01d76b54774ba4729e7c35926d507b4c2e259e009f4f247/ibm_watsonx_ai-1.3.42-py3-none-any.whl", hash = "sha256:339055853e56717d765025217eb9ba2380988e89bedf41d96618affdb7edb64a", size = 1052677, upload-time = "2025-10-01T13:35:38.741Z" }, -] - [[package]] name = "ibm-watsonx-ai" version = "1.5.14" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", -] dependencies = [ - { name = "cachetools", marker = "python_full_version >= '3.11'" }, - { name = "certifi", marker = "python_full_version >= '3.11'" }, - { name = "httpx", marker = "python_full_version >= '3.11'" }, - { name = "ibm-cos-sdk", marker = "python_full_version >= '3.11'" }, - { name = "lomond", marker = "python_full_version >= '3.11'" }, - { name = "packaging", marker = "python_full_version >= '3.11'" }, - { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, + { name = "cachetools" }, + { name = "certifi" }, + { name = "httpx" }, + { name = "ibm-cos-sdk" }, + { name = "lomond" }, + { name = "packaging" }, + { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" }, { name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, - { name = "requests", marker = "python_full_version >= '3.11'" }, - { name = "tabulate", marker = "python_full_version >= '3.11'" }, - { name = "urllib3", marker = "python_full_version >= '3.11'" }, + { name = "requests" }, + { name = "tabulate" }, + { name = "urllib3" }, ] sdist = { url = "https://files.pythonhosted.org/packages/29/a3/c756b534696ab2f3f29882fdb7ca7198b7a5c94e10c0a3a327853d6d6b79/ibm_watsonx_ai-1.5.14.tar.gz", hash = "sha256:a756488bd57e87c0fc51be42dcba871143cfe0ac1e805c497c5047e1e4f13e9d", size = 735804, upload-time = "2026-06-22T12:32:43.85Z" } wheels = [ @@ -1639,8 +1482,7 @@ dependencies = [ { name = "appnope", marker = "sys_platform == 'darwin'" }, { name = "comm" }, { name = "debugpy" }, - { name = "ipython", version = "8.39.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "ipython", version = "9.15.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "ipython" }, { name = "jupyter-client" }, { name = "jupyter-core" }, { name = "matplotlib-inline" }, @@ -1656,63 +1498,23 @@ 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 = "8.39.0" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] -dependencies = [ - { name = "colorama", marker = "python_full_version < '3.11' and sys_platform == 'win32'" }, - { name = "decorator", marker = "python_full_version < '3.11'" }, - { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, - { name = "jedi", marker = "python_full_version < '3.11'" }, - { name = "matplotlib-inline", marker = "python_full_version < '3.11'" }, - { name = "pexpect", marker = "python_full_version < '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit", marker = "python_full_version < '3.11'" }, - { name = "pygments", marker = "python_full_version < '3.11'" }, - { name = "stack-data", marker = "python_full_version < '3.11'" }, - { name = "traitlets", marker = "python_full_version < '3.11'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/40/18/f8598d287006885e7136451fdea0755af4ebcbfe342836f24deefaed1164/ipython-8.39.0.tar.gz", hash = "sha256:4110ae96012c379b8b6db898a07e186c40a2a1ef5d57a7fa83166047d9da7624", size = 5513971, upload-time = "2026-03-27T10:02:13.94Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c0/56/4cc7fc9e9e3f38fd324f24f8afe0ad8bb5fa41283f37f1aaf9de0612c968/ipython-8.39.0-py3-none-any.whl", hash = "sha256:bb3c51c4fa8148ab1dea07a79584d1c854e234ea44aa1283bcb37bc75054651f", size = 831849, upload-time = "2026-03-27T10:02:07.846Z" }, -] - [[package]] name = "ipython" version = "9.15.0" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", -] dependencies = [ - { name = "colorama", marker = "python_full_version >= '3.11' and sys_platform == 'win32'" }, - { name = "decorator", marker = "python_full_version >= '3.11'" }, - { name = "ipython-pygments-lexers", marker = "python_full_version >= '3.11'" }, - { name = "jedi", marker = "python_full_version >= '3.11'" }, - { name = "matplotlib-inline", marker = "python_full_version >= '3.11'" }, - { name = "pexpect", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit", marker = "python_full_version >= '3.11'" }, - { name = "psutil", marker = "python_full_version >= '3.11' and sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, - { name = "pygments", marker = "python_full_version >= '3.11'" }, - { name = "stack-data", marker = "python_full_version >= '3.11'" }, - { name = "traitlets", marker = "python_full_version >= '3.11'" }, - { name = "typing-extensions", marker = "python_full_version == '3.11.*'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "decorator" }, + { 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" }, + { name = "typing-extensions", marker = "python_full_version < '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/53/59/165d3b4d75cc34add3122c4417ecb229085140ac573103c223cd01dde96f/ipython-9.15.0.tar.gz", hash = "sha256:da2819ce2aa83135257df830660b1176d986c3d2876db24df01974fa955b2756", size = 4442580, upload-time = "2026-06-26T11:03:35.913Z" } wheels = [ @@ -1724,7 +1526,7 @@ name = "ipython-pygments-lexers" version = "1.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pygments", marker = "python_full_version >= '3.11'" }, + { 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 = [ @@ -1770,19 +1572,6 @@ version = "0.16.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/1d/1f/10936e16d8860c70698a1aa939a46aa0224813b782bce4e000e637da0b2d/jiter-0.16.0.tar.gz", hash = "sha256:7b24c3492c5f4f84a37946ad9cf504910cf6a782d6a4e0689b6673c5894b4a1c", size = 176431, upload-time = "2026-06-29T13:05:13.657Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/76/d8/b959609e44012a42b1f3e5ba98ea3b33c7e41e6d4b77cd8f00fd19b1d3ad/jiter-0.16.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:c5fc4f8def331036a7b8e981b4347ebe409981edbc8308a5ea842b8c3614fa6c", size = 310082, upload-time = "2026-06-29T13:02:31.356Z" }, - { url = "https://files.pythonhosted.org/packages/c6/3d/4d7f5667ea0e0548534ba880b84bb3d12924fd133aa83ad6c6c80fca3d76/jiter-0.16.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:5a71d0d2014c3275043e1170bf3d4e771493cb0dcf07be54c567155f4d8ee64b", size = 315643, upload-time = "2026-06-29T13:02:33.204Z" }, - { url = "https://files.pythonhosted.org/packages/9b/83/bed2dcb5c9f3e1ccfcbc67dda48265fe7d5ad0c9cadda5fe95f6e3b87f94/jiter-0.16.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:741eed508c233a76313a1c7b001f8f21b82f14327e9196ae8bd29a2cc164ae84", size = 341363, upload-time = "2026-06-29T13:02:34.853Z" }, - { url = "https://files.pythonhosted.org/packages/f4/2f/6bb3c3dda668ebc0445689c81a2b0f26a82b10843d67ed9c9b2c3edc177f/jiter-0.16.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3fb7bc819187b56dc48aa5c833aaf92257da8e07efdb9306156667bd2eeb491c", size = 365483, upload-time = "2026-06-29T13:02:36.295Z" }, - { url = "https://files.pythonhosted.org/packages/92/35/8a045ccb39164e70dcdae696413b661771f148b68b12b175c3a04d901937/jiter-0.16.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7c9610fd25ebccb43fca584136f5c2fbb26802447eccd430dfdbab95a0fd5126", size = 461219, upload-time = "2026-06-29T13:02:38.116Z" }, - { url = "https://files.pythonhosted.org/packages/e7/99/22292dbbf0ed0c610cfe5ddc7f3bd67237a412f121318f865196e62a07bd/jiter-0.16.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4a1d68ff7ca1d3b5dee20a97a3decda7d5f15003823bf6d140c81f8561d3bc5c", size = 374905, upload-time = "2026-06-29T13:02:40.357Z" }, - { url = "https://files.pythonhosted.org/packages/29/ac/2f55ccb1f0eeafa6d89d24caf52f6f0944a59290ee199e9ade62177dca42/jiter-0.16.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fb08c276dd02dac3a284acdd02cacc630d2e3cd6572a4b85519f35cbd133c3de", size = 348320, upload-time = "2026-06-29T13:02:41.923Z" }, - { url = "https://files.pythonhosted.org/packages/50/e3/7d88b9174c40064fabc07c84a9b62e6b10f5644562ec0e0a29392edbe978/jiter-0.16.0-cp310-cp310-manylinux_2_31_riscv64.whl", hash = "sha256:8fc4d94713c4697347e38faf7d6ef91547c142219bdcfc7220c4870879974244", size = 356519, upload-time = "2026-06-29T13:02:43.436Z" }, - { url = "https://files.pythonhosted.org/packages/27/57/c4a33aeef513a9d5e26e31534e0bcc752d6ea0e54c94ddb7b68bade669c2/jiter-0.16.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1a0f05e229edb29e68cdd0ccb83cea13b64263416120cf943767a6fd72e6787f", size = 394204, upload-time = "2026-06-29T13:02:44.987Z" }, - { url = "https://files.pythonhosted.org/packages/9d/70/c6c23e76ebb3766b111bc399437bbc9f870a76e2a92e10b2a5f561d57372/jiter-0.16.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:2c842cbf374a8daf50b2c04212995bee34ca2ac2cdc29a901b4cdb072c9c4131", size = 521477, upload-time = "2026-06-29T13:02:46.724Z" }, - { url = "https://files.pythonhosted.org/packages/2a/d3/0001c8c0c5976af2625bb1cfb1895e8ec693b6589fe4574b8e6fc2c85501/jiter-0.16.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:5ed466aee31294d7cdcd4d37dfe5c42c97bc29d9a5f00eacf24504358309cb9b", size = 552187, upload-time = "2026-06-29T13:02:48.144Z" }, - { url = "https://files.pythonhosted.org/packages/f6/76/311b718e07e85740e48619c0632b36f7e0b8d113984499e436452ed13a9a/jiter-0.16.0-cp310-cp310-win32.whl", hash = "sha256:b42e9ff5376819c053da25809a8d4b6fa6e473b4856ebe42e298ac958be3d7f9", size = 206513, upload-time = "2026-06-29T13:02:49.515Z" }, - { url = "https://files.pythonhosted.org/packages/db/7f/ac680eeb0777dc0eb7dc824800ba27880d7f6bc712e362d34ad8ee559f36/jiter-0.16.0-cp310-cp310-win_amd64.whl", hash = "sha256:10438939205546132189c8e74a2d536a707841f3a25cd7c74ee91fe503407a26", size = 199505, upload-time = "2026-06-29T13:02:50.829Z" }, { url = "https://files.pythonhosted.org/packages/4e/3f/fae6cc967d120ec89e31c5418a51176d8278b3087fbb384a9176754f353c/jiter-0.16.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:67fddeda1688f0cce2d2ae83ccf8a80f79936f2d2997d6cc2261f82fdb54a4d3", size = 309289, upload-time = "2026-06-29T13:02:52.301Z" }, { url = "https://files.pythonhosted.org/packages/c8/e3/97c6c3562c077f6247d6e6ce5c82562500b6316c0d928e97e106b7a1321a/jiter-0.16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c90c0f63df322be920eda6ce622e3083d8906ba267f8220fe7873213b8b4430e", size = 315181, upload-time = "2026-06-29T13:02:53.964Z" }, { url = "https://files.pythonhosted.org/packages/7b/89/d8d073f8aa2667e46c6c0873f86fe4a512bba4293cc730f626a076211a62/jiter-0.16.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:64c0203212098470032aabcde9356fc168f377aade3e43def61dfe17e92f2037", size = 340939, upload-time = "2026-06-29T13:02:55.412Z" }, @@ -1889,8 +1678,7 @@ dependencies = [ { name = "attrs" }, { name = "jsonschema-specifications" }, { name = "referencing" }, - { name = "rpds-py", version = "0.30.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "rpds-py", version = "2026.6.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { 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 = [ @@ -1958,7 +1746,6 @@ dependencies = [ { name = "nbformat" }, { name = "packaging" }, { name = "pyyaml" }, - { name = "tomli", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/3b/52/e014296ac8f40ca783aeb73dae52e65edbb0eaae0dcdc1ea41bfaa8aebf7/jupytext-1.19.4.tar.gz", hash = "sha256:739bcd4bc12aa4fe298a38017cdb5ae27b08a6ba3a5470728d2fe9e04b155db1", size = 4581977, upload-time = "2026-06-21T21:48:58.32Z" } wheels = [ @@ -1998,8 +1785,7 @@ source = { editable = "." } dependencies = [ { name = "deprecation" }, { name = "lance-namespace" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "overrides", marker = "python_full_version < '3.12'" }, { name = "packaging" }, @@ -2022,13 +1808,12 @@ dev = [ { name = "pre-commit" }, { name = "pyright" }, { name = "ruff" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] docs = [ { name = "mkdocs" }, { name = "mkdocs-jupyter" }, { name = "mkdocs-material" }, - { name = "mkdocstrings-python" }, + { name = "mkdocstrings", extra = ["python"] }, ] embeddings = [ { name = "awscli" }, @@ -2038,8 +1823,7 @@ embeddings = [ { name = "colpali-engine" }, { name = "google-genai" }, { name = "huggingface-hub" }, - { name = "ibm-watsonx-ai", version = "1.3.42", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "ibm-watsonx-ai", version = "1.5.14", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "ibm-watsonx-ai" }, { name = "instructorembedding" }, { name = "oci" }, { name = "ollama" }, @@ -2055,8 +1839,7 @@ otel = [ { name = "opentelemetry-api" }, ] pylance = [ - { name = "pylance", version = "15.0.0b4", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform == 'darwin'" }, - { name = "pylance", version = "15.0.0b9", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform != 'darwin'" }, + { name = "pylance" }, ] siglip = [ { name = "pillow" }, @@ -2070,14 +1853,13 @@ tests = [ { name = "datafusion" }, { name = "duckdb" }, { name = "opentelemetry-sdk" }, - { name = "pandas", version = "2.2.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, + { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" }, { name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, + { name = "pillow" }, { name = "polars" }, { name = "pyarrow" }, { name = "pyarrow-stubs" }, - { name = "pylance", version = "15.0.0b4", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform == 'darwin'" }, - { name = "pylance", version = "15.0.0b9", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform != 'darwin'" }, + { name = "pylance" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-mock" }, @@ -2106,8 +1888,8 @@ requires-dist = [ { name = "maturin", marker = "extra == 'dev'", specifier = ">=1.10" }, { name = "mkdocs", marker = "extra == 'docs'" }, { name = "mkdocs-jupyter", marker = "extra == 'docs'" }, - { name = "mkdocs-material", marker = "extra == 'docs'" }, - { name = "mkdocstrings-python", marker = "extra == 'docs'" }, + { name = "mkdocs-material", marker = "extra == 'docs'", specifier = ">=9.8.2" }, + { name = "mkdocstrings", extras = ["python"], marker = "extra == 'docs'", specifier = ">=1.0.7,<2" }, { name = "numpy", specifier = ">=1.24.0" }, { name = "oci", marker = "extra == 'embeddings'", specifier = ">=2.165.1" }, { name = "ollama", marker = "extra == 'embeddings'", specifier = ">=0.3.0" }, @@ -2119,18 +1901,18 @@ requires-dist = [ { name = "overrides", marker = "python_full_version < '3.12'", specifier = ">=0.7" }, { name = "packaging", specifier = ">=23.0" }, { name = "pandas", marker = "extra == 'tests'", specifier = ">=1.4" }, - { name = "pillow", marker = "extra == 'clip'", specifier = ">=12.1.1" }, - { name = "pillow", marker = "extra == 'embeddings'", specifier = ">=12.1.1" }, - { name = "pillow", marker = "extra == 'siglip'", specifier = ">=12.1.1" }, + { name = "pillow", marker = "extra == 'clip'", specifier = ">=13.0.0" }, + { name = "pillow", marker = "extra == 'embeddings'", specifier = ">=13.0.0" }, + { name = "pillow", marker = "extra == 'siglip'", specifier = ">=13.0.0" }, + { name = "pillow", marker = "extra == 'tests'", specifier = ">=13.0.0" }, { name = "polars", marker = "extra == 'tests'", specifier = ">=0.19,<=1.32.3" }, { name = "pre-commit", marker = "extra == 'dev'", specifier = ">=3.5.0" }, { name = "pyarrow", specifier = ">=16" }, - { name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" }, + { name = "pyarrow", marker = "extra == 'tests'", specifier = ">=16" }, { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, - { name = "pylance", marker = "sys_platform == 'darwin' and extra == 'tests'", specifier = "==15.0.0b4" }, - { name = "pylance", marker = "sys_platform != 'darwin' and extra == 'tests'", specifier = "==15.0.0b9" }, - { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, + { name = "pylance", marker = "extra == 'pylance'", specifier = ">=16.0.0b2" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==16.0.0b4" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -2147,7 +1929,6 @@ requires-dist = [ { name = "torch", marker = "extra == 'siglip'" }, { name = "tqdm", specifier = ">=4.27.0" }, { name = "transformers", marker = "extra == 'siglip'", specifier = ">=4.41.0" }, - { name = "typing-extensions", marker = "python_full_version < '3.11' and extra == 'dev'", specifier = ">=4.0.0" }, ] provides-extras = ["azure", "clip", "dev", "docs", "embeddings", "otel", "pylance", "siglip", "tests"] @@ -2190,17 +1971,6 @@ 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/e8/4b/3541d44f3937ba468b75da9eebcae497dcf67adb65caa16760b0a6807ebb/markupsafe-3.0.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2f981d352f04553a7171b8e44369f2af4055f888dfb147d55e42d29e29e74559", size = 11631, upload-time = "2025-09-27T18:36:05.558Z" }, - { url = "https://files.pythonhosted.org/packages/98/1b/fbd8eed11021cabd9226c37342fa6ca4e8a98d8188a8d9b66740494960e4/markupsafe-3.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e1c1493fb6e50ab01d20a22826e57520f1284df32f2d8601fdd90b6304601419", size = 12057, upload-time = "2025-09-27T18:36:07.165Z" }, - { url = "https://files.pythonhosted.org/packages/40/01/e560d658dc0bb8ab762670ece35281dec7b6c1b33f5fbc09ebb57a185519/markupsafe-3.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ba88449deb3de88bd40044603fafffb7bc2b055d626a330323a9ed736661695", size = 22050, upload-time = "2025-09-27T18:36:08.005Z" }, - { url = "https://files.pythonhosted.org/packages/af/cd/ce6e848bbf2c32314c9b237839119c5a564a59725b53157c856e90937b7a/markupsafe-3.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f42d0984e947b8adf7dd6dde396e720934d12c506ce84eea8476409563607591", size = 20681, upload-time = "2025-09-27T18:36:08.881Z" }, - { url = "https://files.pythonhosted.org/packages/c9/2a/b5c12c809f1c3045c4d580b035a743d12fcde53cf685dbc44660826308da/markupsafe-3.0.3-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c0c0b3ade1c0b13b936d7970b1d37a57acde9199dc2aecc4c336773e1d86049c", size = 20705, upload-time = "2025-09-27T18:36:10.131Z" }, - { url = "https://files.pythonhosted.org/packages/cf/e3/9427a68c82728d0a88c50f890d0fc072a1484de2f3ac1ad0bfc1a7214fd5/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0303439a41979d9e74d18ff5e2dd8c43ed6c6001fd40e5bf2e43f7bd9bbc523f", size = 21524, upload-time = "2025-09-27T18:36:11.324Z" }, - { url = "https://files.pythonhosted.org/packages/bc/36/23578f29e9e582a4d0278e009b38081dbe363c5e7165113fad546918a232/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:d2ee202e79d8ed691ceebae8e0486bd9a2cd4794cec4824e1c99b6f5009502f6", size = 20282, upload-time = "2025-09-27T18:36:12.573Z" }, - { url = "https://files.pythonhosted.org/packages/56/21/dca11354e756ebd03e036bd8ad58d6d7168c80ce1fe5e75218e4945cbab7/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:177b5253b2834fe3678cb4a5f0059808258584c559193998be2601324fdeafb1", size = 20745, upload-time = "2025-09-27T18:36:13.504Z" }, - { url = "https://files.pythonhosted.org/packages/87/99/faba9369a7ad6e4d10b6a5fbf71fa2a188fe4a593b15f0963b73859a1bbd/markupsafe-3.0.3-cp310-cp310-win32.whl", hash = "sha256:2a15a08b17dd94c53a1da0438822d70ebcd13f8c3a95abe3a9ef9f11a94830aa", size = 14571, upload-time = "2025-09-27T18:36:14.779Z" }, - { url = "https://files.pythonhosted.org/packages/d6/25/55dc3ab959917602c96985cb1253efaa4ff42f71194bddeb61eb7278b8be/markupsafe-3.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:c4ffb7ebf07cfe8931028e3e4c85f0357459a3f9f9490886198848f4fa002ec8", size = 15056, upload-time = "2025-09-27T18:36:16.125Z" }, - { url = "https://files.pythonhosted.org/packages/d0/9e/0a02226640c255d1da0b8d12e24ac2aa6734da68bff14c05dd53b94a0fc3/markupsafe-3.0.3-cp310-cp310-win_arm64.whl", hash = "sha256:e2103a929dfa2fcaf9bb4e7c091983a49c9ac3b19c9061b6d5427dd7d14d81a1", size = 13932, upload-time = "2025-09-27T18:36:17.311Z" }, { url = "https://files.pythonhosted.org/packages/08/db/fefacb2136439fc8dd20e797950e749aa1f4997ed584c62cfb8ef7c2be0e/markupsafe-3.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad", size = 11631, upload-time = "2025-09-27T18:36:18.185Z" }, { url = "https://files.pythonhosted.org/packages/e1/2e/5898933336b61975ce9dc04decbc0a7f2fee78c30353c5efba7f2d6ff27a/markupsafe-3.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a", size = 12058, upload-time = "2025-09-27T18:36:19.444Z" }, { url = "https://files.pythonhosted.org/packages/1d/09/adf2df3699d87d1d8184038df46a9c80d78c0148492323f4693df54e17bb/markupsafe-3.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50", size = 24287, upload-time = "2025-09-27T18:36:20.768Z" }, @@ -2285,9 +2055,6 @@ wheels = [ name = "maturin" version = "1.15.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "tomli", marker = "python_full_version < '3.11'" }, -] sdist = { url = "https://files.pythonhosted.org/packages/b9/c8/22e5e21b2679c9bce6415ca578034ca2cc9316be0642ae21e051a2d5198c/maturin-1.15.0.tar.gz", hash = "sha256:94b26cc8e8aba61a5f2099715fe640e18c5f678e9a500408b38761263954228a", size = 385504, upload-time = "2026-08-24T12:11:22.665Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/14/69/5c01b461044eb1f45ddcce006706eb88110c793cdb11c7ae0b5e08492e94/maturin-1.15.0-py3-none-linux_armv6l.whl", hash = "sha256:6bf6dc62e22d4dcfd5a51244ff0d58975fa4979c48209fe84159617648956d82", size = 10206220, upload-time = "2026-08-24T12:10:53.327Z" }, @@ -2339,9 +2106,6 @@ wheels = [ name = "mistune" version = "3.3.2" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] sdist = { url = "https://files.pythonhosted.org/packages/04/5f/007786743f962224423753b78f7d7acb0f2ade46d1604f2e0fa2bedf9020/mistune-3.3.2.tar.gz", hash = "sha256:e12ee4f1e74336e91aa1141e35f913b337c40bdf7c0cc49f21fb853a27e8b62f", size = 111284, upload-time = "2026-06-23T00:29:28.568Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/44/43/894c2cbbcbdf53b57d1257a249811abe2ee9ab7ef76af301b40f1c054533/mistune-3.3.2-py3-none-any.whl", hash = "sha256:a678a56387d487db7368ede4647cb2ba1deff22ce61f92343e4ebe0ddfce4f2d", size = 61554, upload-time = "2026-06-23T00:29:27.088Z" }, @@ -2418,7 +2182,7 @@ wheels = [ [[package]] name = "mkdocs-material" -version = "9.7.6" +version = "9.8.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "babel" }, @@ -2433,9 +2197,9 @@ dependencies = [ { name = "pymdown-extensions" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/45/29/6d2bcf41ae40802c4beda2432396fff97b8456fb496371d1bc7aad6512ec/mkdocs_material-9.7.6.tar.gz", hash = "sha256:00bdde50574f776d328b1862fe65daeaf581ec309bd150f7bff345a098c64a69", size = 4097959, upload-time = "2026-03-19T15:41:58.161Z" } +sdist = { url = "https://files.pythonhosted.org/packages/99/bf/c47389fa622b513c2d115eb4c16075ef04a5f4d8156039f46cb26e5c70a9/mkdocs_material-9.8.2.tar.gz", hash = "sha256:005d942bdbfa22efa049f4818c31d42fb36bed6d362adb641dd7a2e948078f9d", size = 4160697, upload-time = "2026-11-19T19:52:25.799Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/01/bc663630c510822c95c47a66af9fa7a443c295b47d5f041e5e6ae62ef659/mkdocs_material-9.7.6-py3-none-any.whl", hash = "sha256:71b84353921b8ea1ba84fe11c50912cc512da8fe0881038fcc9a0761c0e635ba", size = 9305470, upload-time = "2026-03-19T15:41:55.217Z" }, + { url = "https://files.pythonhosted.org/packages/18/86/9204441dd9e224f1dc3f1a32edf6a474e84696bfa493c7df067dcde36366/mkdocs_material-9.8.2-py3-none-any.whl", hash = "sha256:ef1414cab33d64fcc13387e972af5ba4620f55f93482d1842933399ed2c69b02", size = 9302480, upload-time = "2026-11-19T19:52:22.436Z" }, ] [[package]] @@ -2449,7 +2213,7 @@ wheels = [ [[package]] name = "mkdocstrings" -version = "1.0.4" +version = "1.0.7" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jinja2" }, @@ -2459,9 +2223,14 @@ dependencies = [ { name = "mkdocs-autorefs" }, { name = "pymdown-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1d/5d/f888d4d3eb31359b327bc9b17a212d6ef03fe0b0682fbb3fc2cb849fb12b/mkdocstrings-1.0.4.tar.gz", hash = "sha256:3969a6515b77db65fd097b53c1b7aa4ae840bd71a2ee62a6a3e89503446d7172", size = 100088, upload-time = "2026-04-15T09:16:53.376Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/e8/445b19834bf9559ebbbaa76897e965665b83d2861461eed8d8de4d122057/mkdocstrings-1.0.7.tar.gz", hash = "sha256:0951b147f352118a45a3db85f0f3b660833d34cb5120a2751315b8d08dafd159", size = 103739, upload-time = "2026-10-10T13:50:59.957Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6e/94/be70f8ee9c45f2f62b39a1f0e9303bc20e138a8f3b8e50ffd89498e177e1/mkdocstrings-1.0.4-py3-none-any.whl", hash = "sha256:63464b4b29053514f32a1dbbf604e52876d5e638111b0c295ab7ed3cac73ca9b", size = 35560, upload-time = "2026-04-15T09:16:51.436Z" }, + { url = "https://files.pythonhosted.org/packages/22/c3/9062531735ff1fd27f3a79c353c4cf4d822eeffd062fd90b2c553a96f4bb/mkdocstrings-1.0.7-py3-none-any.whl", hash = "sha256:9563828667eeb35256f87a6b61fe857676ac628ec1abbce9aea9839a502c9cb1", size = 41597, upload-time = "2026-10-10T13:50:58.43Z" }, +] + +[package.optional-dependencies] +python = [ + { name = "mkdocstrings-python" }, ] [[package]] @@ -2472,7 +2241,6 @@ dependencies = [ { name = "griffelib" }, { name = "mkdocs-autorefs" }, { name = "mkdocstrings" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] 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 = [ @@ -2518,29 +2286,8 @@ wheels = [ name = "multidict" version = "6.7.1" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] 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/84/0b/19348d4c98980c4851d2f943f8ebafdece2ae7ef737adcfa5994ce8e5f10/multidict-6.7.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:c93c3db7ea657dd4637d57e74ab73de31bccefe144d3d4ce370052035bc85fb5", size = 77176, upload-time = "2026-01-26T02:42:59.784Z" }, - { url = "https://files.pythonhosted.org/packages/ef/04/9de3f8077852e3d438215c81e9b691244532d2e05b4270e89ce67b7d103c/multidict-6.7.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:974e72a2474600827abaeda71af0c53d9ebbc3c2eb7da37b37d7829ae31232d8", size = 44996, upload-time = "2026-01-26T02:43:01.674Z" }, - { url = "https://files.pythonhosted.org/packages/31/5c/08c7f7fe311f32e83f7621cd3f99d805f45519cd06fafb247628b861da7d/multidict-6.7.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:cdea2e7b2456cfb6694fb113066fd0ec7ea4d67e3a35e1f4cbeea0b448bf5872", size = 44631, upload-time = "2026-01-26T02:43:03.169Z" }, - { url = "https://files.pythonhosted.org/packages/b7/7f/0e3b1390ae772f27501199996b94b52ceeb64fe6f9120a32c6c3f6b781be/multidict-6.7.1-cp310-cp310-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:17207077e29342fdc2c9a82e4b306f1127bf1ea91f8b71e02d4798a70bb99991", size = 242561, upload-time = "2026-01-26T02:43:04.733Z" }, - { url = "https://files.pythonhosted.org/packages/dd/f4/8719f4f167586af317b69dd3e90f913416c91ca610cac79a45c53f590312/multidict-6.7.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4f49cb5661344764e4c7c7973e92a47a59b8fc19b6523649ec9dc4960e58a03", size = 242223, upload-time = "2026-01-26T02:43:06.695Z" }, - { url = "https://files.pythonhosted.org/packages/47/ab/7c36164cce64a6ad19c6d9a85377b7178ecf3b89f8fd589c73381a5eedfd/multidict-6.7.1-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a9fc4caa29e2e6ae408d1c450ac8bf19892c5fca83ee634ecd88a53332c59981", size = 222322, upload-time = "2026-01-26T02:43:08.472Z" }, - { url = "https://files.pythonhosted.org/packages/f5/79/a25add6fb38035b5337bc5734f296d9afc99163403bbcf56d4170f97eb62/multidict-6.7.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c5f0c21549ab432b57dcc82130f388d84ad8179824cc3f223d5e7cfbfd4143f6", size = 254005, upload-time = "2026-01-26T02:43:10.127Z" }, - { url = "https://files.pythonhosted.org/packages/4a/7b/64a87cf98e12f756fc8bd444b001232ffff2be37288f018ad0d3f0aae931/multidict-6.7.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7dfb78d966b2c906ae1d28ccf6e6712a3cd04407ee5088cd276fe8cb42186190", size = 251173, upload-time = "2026-01-26T02:43:11.731Z" }, - { url = "https://files.pythonhosted.org/packages/4b/ac/b605473de2bb404e742f2cc3583d12aedb2352a70e49ae8fce455b50c5aa/multidict-6.7.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9b0d9b91d1aa44db9c1f1ecd0d9d2ae610b2f4f856448664e01a3b35899f3f92", size = 243273, upload-time = "2026-01-26T02:43:13.063Z" }, - { url = "https://files.pythonhosted.org/packages/03/65/11492d6a0e259783720f3bc1d9ea55579a76f1407e31ed44045c99542004/multidict-6.7.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:dd96c01a9dcd4889dcfcf9eb5544ca0c77603f239e3ffab0524ec17aea9a93ee", size = 238956, upload-time = "2026-01-26T02:43:14.843Z" }, - { url = "https://files.pythonhosted.org/packages/5f/a7/7ee591302af64e7c196fb63fe856c788993c1372df765102bd0448e7e165/multidict-6.7.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:067343c68cd6612d375710f895337b3a98a033c94f14b9a99eff902f205424e2", size = 233477, upload-time = "2026-01-26T02:43:16.025Z" }, - { url = "https://files.pythonhosted.org/packages/9c/99/c109962d58756c35fd9992fed7f2355303846ea2ff054bb5f5e9d6b888de/multidict-6.7.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:5884a04f4ff56c6120f6ccf703bdeb8b5079d808ba604d4d53aec0d55dc33568", size = 243615, upload-time = "2026-01-26T02:43:17.84Z" }, - { url = "https://files.pythonhosted.org/packages/d5/5f/1973e7c771c86e93dcfe1c9cc55a5481b610f6614acfc28c0d326fe6bfad/multidict-6.7.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8affcf1c98b82bc901702eb73b6947a1bfa170823c153fe8a47b5f5f02e48e40", size = 249930, upload-time = "2026-01-26T02:43:19.06Z" }, - { url = "https://files.pythonhosted.org/packages/5d/a5/f170fc2268c3243853580203378cd522446b2df632061e0a5409817854c7/multidict-6.7.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:0d17522c37d03e85c8098ec8431636309b2682cf12e58f4dbc76121fb50e4962", size = 243807, upload-time = "2026-01-26T02:43:20.286Z" }, - { url = "https://files.pythonhosted.org/packages/de/01/73856fab6d125e5bc652c3986b90e8699a95e84b48d72f39ade6c0e74a8c/multidict-6.7.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:24c0cf81544ca5e17cfcb6e482e7a82cd475925242b308b890c9452a074d4505", size = 239103, upload-time = "2026-01-26T02:43:21.508Z" }, - { url = "https://files.pythonhosted.org/packages/e7/46/f1220bd9944d8aa40d8ccff100eeeee19b505b857b6f603d6078cb5315b0/multidict-6.7.1-cp310-cp310-win32.whl", hash = "sha256:d82dd730a95e6643802f4454b8fdecdf08667881a9c5670db85bc5a56693f122", size = 41416, upload-time = "2026-01-26T02:43:22.703Z" }, - { url = "https://files.pythonhosted.org/packages/68/00/9b38e272a770303692fc406c36e1a4c740f401522d5787691eb38a8925a8/multidict-6.7.1-cp310-cp310-win_amd64.whl", hash = "sha256:cf37cbe5ced48d417ba045aca1b21bafca67489452debcde94778a576666a1df", size = 46022, upload-time = "2026-01-26T02:43:23.77Z" }, - { url = "https://files.pythonhosted.org/packages/64/65/d8d42490c02ee07b6bbe00f7190d70bb4738b3cce7629aaf9f213ef730dd/multidict-6.7.1-cp310-cp310-win_arm64.whl", hash = "sha256:59bc83d3f66b41dac1e7460aac1d196edc70c9ba3094965c467715a70ecb46db", size = 43238, upload-time = "2026-01-26T02:43:24.882Z" }, { url = "https://files.pythonhosted.org/packages/ce/f1/a90635c4f88fb913fbf4ce660b83b7445b7a02615bda034b2f8eb38fd597/multidict-6.7.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7ff981b266af91d7b4b3793ca3382e53229088d193a85dfad6f5f4c27fc73e5d", size = 76626, upload-time = "2026-01-26T02:43:26.485Z" }, { url = "https://files.pythonhosted.org/packages/a6/9b/267e64eaf6fc637a15b35f5de31a566634a2740f97d8d094a69d34f524a4/multidict-6.7.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:844c5bca0b5444adb44a623fb0a1310c2f4cd41f402126bb269cd44c9b3f3e1e", size = 44706, upload-time = "2026-01-26T02:43:27.607Z" }, { url = "https://files.pythonhosted.org/packages/dd/a4/d45caf2b97b035c57267791ecfaafbd59c68212004b3842830954bb4b02e/multidict-6.7.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f2a0a924d4c2e9afcd7ec64f9de35fcd96915149b2216e1cb2c10a56df483855", size = 44356, upload-time = "2026-01-26T02:43:28.661Z" }, @@ -2725,37 +2472,10 @@ 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 = "networkx" -version = "3.4.2" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] -sdist = { url = "https://files.pythonhosted.org/packages/fd/1d/06475e1cd5264c0b870ea2cc6fdb3e37177c1e565c43f56ff17a10e3937f/networkx-3.4.2.tar.gz", hash = "sha256:307c3669428c5362aab27c8a1260aa8f47c4e91d3891f48be0141738d8d053e1", size = 2151368, upload-time = "2024-10-21T12:39:38.695Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/54/dd730b32ea14ea797530a4479b2ed46a6fb250f682a9cfb997e968bf0261/networkx-3.4.2-py3-none-any.whl", hash = "sha256:df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f", size = 1723263, upload-time = "2024-10-21T12:39:36.247Z" }, -] - [[package]] name = "networkx" version = "3.6.1" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", -] 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" }, @@ -2770,81 +2490,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/b2/d0896bdcdc8d28a7fc5717c305f1a861c26e18c05047949fb371034d98bd/nodeenv-1.10.0-py2.py3-none-any.whl", hash = "sha256:5bb13e3eed2923615535339b3c620e76779af4cb4c6a90deccc9e36b274d3827", size = 23438, upload-time = "2025-12-20T14:08:52.782Z" }, ] -[[package]] -name = "numpy" -version = "2.2.6" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] -sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440, upload-time = "2025-05-17T22:38:04.611Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/3e/ed6db5be21ce87955c0cbd3009f2803f59fa08df21b5df06862e2d8e2bdd/numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb", size = 21165245, upload-time = "2025-05-17T21:27:58.555Z" }, - { url = "https://files.pythonhosted.org/packages/22/c2/4b9221495b2a132cc9d2eb862e21d42a009f5a60e45fc44b00118c174bff/numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90", size = 14360048, upload-time = "2025-05-17T21:28:21.406Z" }, - { url = "https://files.pythonhosted.org/packages/fd/77/dc2fcfc66943c6410e2bf598062f5959372735ffda175b39906d54f02349/numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163", size = 5340542, upload-time = "2025-05-17T21:28:30.931Z" }, - { url = "https://files.pythonhosted.org/packages/7a/4f/1cb5fdc353a5f5cc7feb692db9b8ec2c3d6405453f982435efc52561df58/numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf", size = 6878301, upload-time = "2025-05-17T21:28:41.613Z" }, - { url = "https://files.pythonhosted.org/packages/eb/17/96a3acd228cec142fcb8723bd3cc39c2a474f7dcf0a5d16731980bcafa95/numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83", size = 14297320, upload-time = "2025-05-17T21:29:02.78Z" }, - { url = "https://files.pythonhosted.org/packages/b4/63/3de6a34ad7ad6646ac7d2f55ebc6ad439dbbf9c4370017c50cf403fb19b5/numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915", size = 16801050, upload-time = "2025-05-17T21:29:27.675Z" }, - { url = "https://files.pythonhosted.org/packages/07/b6/89d837eddef52b3d0cec5c6ba0456c1bf1b9ef6a6672fc2b7873c3ec4e2e/numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680", size = 15807034, upload-time = "2025-05-17T21:29:51.102Z" }, - { url = "https://files.pythonhosted.org/packages/01/c8/dc6ae86e3c61cfec1f178e5c9f7858584049b6093f843bca541f94120920/numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289", size = 18614185, upload-time = "2025-05-17T21:30:18.703Z" }, - { url = "https://files.pythonhosted.org/packages/5b/c5/0064b1b7e7c89137b471ccec1fd2282fceaae0ab3a9550f2568782d80357/numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d", size = 6527149, upload-time = "2025-05-17T21:30:29.788Z" }, - { url = "https://files.pythonhosted.org/packages/a3/dd/4b822569d6b96c39d1215dbae0582fd99954dcbcf0c1a13c61783feaca3f/numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3", size = 12904620, upload-time = "2025-05-17T21:30:48.994Z" }, - { url = "https://files.pythonhosted.org/packages/da/a8/4f83e2aa666a9fbf56d6118faaaf5f1974d456b1823fda0a176eff722839/numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae", size = 21176963, upload-time = "2025-05-17T21:31:19.36Z" }, - { url = "https://files.pythonhosted.org/packages/b3/2b/64e1affc7972decb74c9e29e5649fac940514910960ba25cd9af4488b66c/numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a", size = 14406743, upload-time = "2025-05-17T21:31:41.087Z" }, - { url = "https://files.pythonhosted.org/packages/4a/9f/0121e375000b5e50ffdd8b25bf78d8e1a5aa4cca3f185d41265198c7b834/numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42", size = 5352616, upload-time = "2025-05-17T21:31:50.072Z" }, - { url = "https://files.pythonhosted.org/packages/31/0d/b48c405c91693635fbe2dcd7bc84a33a602add5f63286e024d3b6741411c/numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491", size = 6889579, upload-time = "2025-05-17T21:32:01.712Z" }, - { url = "https://files.pythonhosted.org/packages/52/b8/7f0554d49b565d0171eab6e99001846882000883998e7b7d9f0d98b1f934/numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a", size = 14312005, upload-time = "2025-05-17T21:32:23.332Z" }, - { url = "https://files.pythonhosted.org/packages/b3/dd/2238b898e51bd6d389b7389ffb20d7f4c10066d80351187ec8e303a5a475/numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf", size = 16821570, upload-time = "2025-05-17T21:32:47.991Z" }, - { url = "https://files.pythonhosted.org/packages/83/6c/44d0325722cf644f191042bf47eedad61c1e6df2432ed65cbe28509d404e/numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1", size = 15818548, upload-time = "2025-05-17T21:33:11.728Z" }, - { url = "https://files.pythonhosted.org/packages/ae/9d/81e8216030ce66be25279098789b665d49ff19eef08bfa8cb96d4957f422/numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab", size = 18620521, upload-time = "2025-05-17T21:33:39.139Z" }, - { url = "https://files.pythonhosted.org/packages/6a/fd/e19617b9530b031db51b0926eed5345ce8ddc669bb3bc0044b23e275ebe8/numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47", size = 6525866, upload-time = "2025-05-17T21:33:50.273Z" }, - { url = "https://files.pythonhosted.org/packages/31/0a/f354fb7176b81747d870f7991dc763e157a934c717b67b58456bc63da3df/numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303", size = 12907455, upload-time = "2025-05-17T21:34:09.135Z" }, - { url = "https://files.pythonhosted.org/packages/82/5d/c00588b6cf18e1da539b45d3598d3557084990dcc4331960c15ee776ee41/numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff", size = 20875348, upload-time = "2025-05-17T21:34:39.648Z" }, - { url = "https://files.pythonhosted.org/packages/66/ee/560deadcdde6c2f90200450d5938f63a34b37e27ebff162810f716f6a230/numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c", size = 14119362, upload-time = "2025-05-17T21:35:01.241Z" }, - { url = "https://files.pythonhosted.org/packages/3c/65/4baa99f1c53b30adf0acd9a5519078871ddde8d2339dc5a7fde80d9d87da/numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3", size = 5084103, upload-time = "2025-05-17T21:35:10.622Z" }, - { url = "https://files.pythonhosted.org/packages/cc/89/e5a34c071a0570cc40c9a54eb472d113eea6d002e9ae12bb3a8407fb912e/numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282", size = 6625382, upload-time = "2025-05-17T21:35:21.414Z" }, - { url = "https://files.pythonhosted.org/packages/f8/35/8c80729f1ff76b3921d5c9487c7ac3de9b2a103b1cd05e905b3090513510/numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87", size = 14018462, upload-time = "2025-05-17T21:35:42.174Z" }, - { url = "https://files.pythonhosted.org/packages/8c/3d/1e1db36cfd41f895d266b103df00ca5b3cbe965184df824dec5c08c6b803/numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249", size = 16527618, upload-time = "2025-05-17T21:36:06.711Z" }, - { url = "https://files.pythonhosted.org/packages/61/c6/03ed30992602c85aa3cd95b9070a514f8b3c33e31124694438d88809ae36/numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49", size = 15505511, upload-time = "2025-05-17T21:36:29.965Z" }, - { url = "https://files.pythonhosted.org/packages/b7/25/5761d832a81df431e260719ec45de696414266613c9ee268394dd5ad8236/numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de", size = 18313783, upload-time = "2025-05-17T21:36:56.883Z" }, - { url = "https://files.pythonhosted.org/packages/57/0a/72d5a3527c5ebffcd47bde9162c39fae1f90138c961e5296491ce778e682/numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4", size = 6246506, upload-time = "2025-05-17T21:37:07.368Z" }, - { url = "https://files.pythonhosted.org/packages/36/fa/8c9210162ca1b88529ab76b41ba02d433fd54fecaf6feb70ef9f124683f1/numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2", size = 12614190, upload-time = "2025-05-17T21:37:26.213Z" }, - { url = "https://files.pythonhosted.org/packages/f9/5c/6657823f4f594f72b5471f1db1ab12e26e890bb2e41897522d134d2a3e81/numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84", size = 20867828, upload-time = "2025-05-17T21:37:56.699Z" }, - { url = "https://files.pythonhosted.org/packages/dc/9e/14520dc3dadf3c803473bd07e9b2bd1b69bc583cb2497b47000fed2fa92f/numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b", size = 14143006, upload-time = "2025-05-17T21:38:18.291Z" }, - { url = "https://files.pythonhosted.org/packages/4f/06/7e96c57d90bebdce9918412087fc22ca9851cceaf5567a45c1f404480e9e/numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d", size = 5076765, upload-time = "2025-05-17T21:38:27.319Z" }, - { url = "https://files.pythonhosted.org/packages/73/ed/63d920c23b4289fdac96ddbdd6132e9427790977d5457cd132f18e76eae0/numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566", size = 6617736, upload-time = "2025-05-17T21:38:38.141Z" }, - { url = "https://files.pythonhosted.org/packages/85/c5/e19c8f99d83fd377ec8c7e0cf627a8049746da54afc24ef0a0cb73d5dfb5/numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f", size = 14010719, upload-time = "2025-05-17T21:38:58.433Z" }, - { url = "https://files.pythonhosted.org/packages/19/49/4df9123aafa7b539317bf6d342cb6d227e49f7a35b99c287a6109b13dd93/numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f", size = 16526072, upload-time = "2025-05-17T21:39:22.638Z" }, - { url = "https://files.pythonhosted.org/packages/b2/6c/04b5f47f4f32f7c2b0e7260442a8cbcf8168b0e1a41ff1495da42f42a14f/numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868", size = 15503213, upload-time = "2025-05-17T21:39:45.865Z" }, - { url = "https://files.pythonhosted.org/packages/17/0a/5cd92e352c1307640d5b6fec1b2ffb06cd0dabe7d7b8227f97933d378422/numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d", size = 18316632, upload-time = "2025-05-17T21:40:13.331Z" }, - { url = "https://files.pythonhosted.org/packages/f0/3b/5cba2b1d88760ef86596ad0f3d484b1cbff7c115ae2429678465057c5155/numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd", size = 6244532, upload-time = "2025-05-17T21:43:46.099Z" }, - { url = "https://files.pythonhosted.org/packages/cb/3b/d58c12eafcb298d4e6d0d40216866ab15f59e55d148a5658bb3132311fcf/numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c", size = 12610885, upload-time = "2025-05-17T21:44:05.145Z" }, - { url = "https://files.pythonhosted.org/packages/6b/9e/4bf918b818e516322db999ac25d00c75788ddfd2d2ade4fa66f1f38097e1/numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6", size = 20963467, upload-time = "2025-05-17T21:40:44Z" }, - { url = "https://files.pythonhosted.org/packages/61/66/d2de6b291507517ff2e438e13ff7b1e2cdbdb7cb40b3ed475377aece69f9/numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda", size = 14225144, upload-time = "2025-05-17T21:41:05.695Z" }, - { url = "https://files.pythonhosted.org/packages/e4/25/480387655407ead912e28ba3a820bc69af9adf13bcbe40b299d454ec011f/numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40", size = 5200217, upload-time = "2025-05-17T21:41:15.903Z" }, - { url = "https://files.pythonhosted.org/packages/aa/4a/6e313b5108f53dcbf3aca0c0f3e9c92f4c10ce57a0a721851f9785872895/numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8", size = 6712014, upload-time = "2025-05-17T21:41:27.321Z" }, - { url = "https://files.pythonhosted.org/packages/b7/30/172c2d5c4be71fdf476e9de553443cf8e25feddbe185e0bd88b096915bcc/numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f", size = 14077935, upload-time = "2025-05-17T21:41:49.738Z" }, - { url = "https://files.pythonhosted.org/packages/12/fb/9e743f8d4e4d3c710902cf87af3512082ae3d43b945d5d16563f26ec251d/numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa", size = 16600122, upload-time = "2025-05-17T21:42:14.046Z" }, - { url = "https://files.pythonhosted.org/packages/12/75/ee20da0e58d3a66f204f38916757e01e33a9737d0b22373b3eb5a27358f9/numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571", size = 15586143, upload-time = "2025-05-17T21:42:37.464Z" }, - { url = "https://files.pythonhosted.org/packages/76/95/bef5b37f29fc5e739947e9ce5179ad402875633308504a52d188302319c8/numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1", size = 18385260, upload-time = "2025-05-17T21:43:05.189Z" }, - { url = "https://files.pythonhosted.org/packages/09/04/f2f83279d287407cf36a7a8053a5abe7be3622a4363337338f2585e4afda/numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff", size = 6377225, upload-time = "2025-05-17T21:43:16.254Z" }, - { url = "https://files.pythonhosted.org/packages/67/0e/35082d13c09c02c011cf21570543d202ad929d961c02a147493cb0c2bdf5/numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06", size = 12771374, upload-time = "2025-05-17T21:43:35.479Z" }, - { url = "https://files.pythonhosted.org/packages/9e/3b/d94a75f4dbf1ef5d321523ecac21ef23a3cd2ac8b78ae2aac40873590229/numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d", size = 21040391, upload-time = "2025-05-17T21:44:35.948Z" }, - { url = "https://files.pythonhosted.org/packages/17/f4/09b2fa1b58f0fb4f7c7963a1649c64c4d315752240377ed74d9cd878f7b5/numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db", size = 6786754, upload-time = "2025-05-17T21:44:47.446Z" }, - { url = "https://files.pythonhosted.org/packages/af/30/feba75f143bdc868a1cc3f44ccfa6c4b9ec522b36458e738cd00f67b573f/numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543", size = 16643476, upload-time = "2025-05-17T21:45:11.871Z" }, - { url = "https://files.pythonhosted.org/packages/37/48/ac2a9584402fb6c0cd5b5d1a91dcf176b15760130dd386bbafdbfe3640bf/numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00", size = 12812666, upload-time = "2025-05-17T21:45:31.426Z" }, -] - [[package]] name = "numpy" version = "2.4.6" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", + "python_full_version < '3.12'", ] sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" } wheels = [ @@ -2928,12 +2579,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.12' and python_full_version < '3.14'", ] 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 = [ @@ -3023,7 +2670,7 @@ name = "nvidia-cudnn-cu13" version = "9.19.0.56" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cublas" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f1/84/26025437c1e6b61a707442184fa0c03d083b661adf3a3eecfd6d21677740/nvidia_cudnn_cu13-9.19.0.56-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:6ed29ffaee1176c612daf442e4dd6cfeb6a0caa43ddcbeb59da94953030b1be4", size = 433781201, upload-time = "2026-02-03T20:40:53.805Z" }, @@ -3035,7 +2682,7 @@ name = "nvidia-cufft" version = "12.0.0.61" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, @@ -3065,9 +2712,9 @@ name = "nvidia-cusolver" version = "12.0.4.66" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cusparse", marker = "sys_platform == 'linux'" }, - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cublas" }, + { name = "nvidia-cusparse" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, @@ -3079,7 +2726,7 @@ name = "nvidia-cusparse" version = "12.6.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, @@ -3270,87 +2917,23 @@ 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 = "pandas" -version = "2.2.3" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] -dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "python-dateutil", marker = "python_full_version < '3.11'" }, - { name = "pytz", marker = "python_full_version < '3.11'" }, - { name = "tzdata", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9c/d6/9f8431bacc2e19dca897724cd097b1bb224a6ad5433784a44b587c7c13af/pandas-2.2.3.tar.gz", hash = "sha256:4f18ba62b61d7e192368b84517265a99b4d7ee8912f8708660fb4a366cc82667", size = 4399213, upload-time = "2024-09-20T13:10:04.827Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/aa/70/c853aec59839bceed032d52010ff5f1b8d87dc3114b762e4ba2727661a3b/pandas-2.2.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1948ddde24197a0f7add2bdc4ca83bf2b1ef84a1bc8ccffd95eda17fd836ecb5", size = 12580827, upload-time = "2024-09-20T13:08:42.347Z" }, - { url = "https://files.pythonhosted.org/packages/99/f2/c4527768739ffa4469b2b4fff05aa3768a478aed89a2f271a79a40eee984/pandas-2.2.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:381175499d3802cde0eabbaf6324cce0c4f5d52ca6f8c377c29ad442f50f6348", size = 11303897, upload-time = "2024-09-20T13:08:45.807Z" }, - { url = "https://files.pythonhosted.org/packages/ed/12/86c1747ea27989d7a4064f806ce2bae2c6d575b950be087837bdfcabacc9/pandas-2.2.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d9c45366def9a3dd85a6454c0e7908f2b3b8e9c138f5dc38fed7ce720d8453ed", size = 66480908, upload-time = "2024-09-20T18:37:13.513Z" }, - { url = "https://files.pythonhosted.org/packages/44/50/7db2cd5e6373ae796f0ddad3675268c8d59fb6076e66f0c339d61cea886b/pandas-2.2.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:86976a1c5b25ae3f8ccae3a5306e443569ee3c3faf444dfd0f41cda24667ad57", size = 13064210, upload-time = "2024-09-20T13:08:48.325Z" }, - { url = "https://files.pythonhosted.org/packages/61/61/a89015a6d5536cb0d6c3ba02cebed51a95538cf83472975275e28ebf7d0c/pandas-2.2.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:b8661b0238a69d7aafe156b7fa86c44b881387509653fdf857bebc5e4008ad42", size = 16754292, upload-time = "2024-09-20T19:01:54.443Z" }, - { url = "https://files.pythonhosted.org/packages/ce/0d/4cc7b69ce37fac07645a94e1d4b0880b15999494372c1523508511b09e40/pandas-2.2.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:37e0aced3e8f539eccf2e099f65cdb9c8aa85109b0be6e93e2baff94264bdc6f", size = 14416379, upload-time = "2024-09-20T13:08:50.882Z" }, - { url = "https://files.pythonhosted.org/packages/31/9e/6ebb433de864a6cd45716af52a4d7a8c3c9aaf3a98368e61db9e69e69a9c/pandas-2.2.3-cp310-cp310-win_amd64.whl", hash = "sha256:56534ce0746a58afaf7942ba4863e0ef81c9c50d3f0ae93e9497d6a41a057645", size = 11598471, upload-time = "2024-09-20T13:08:53.332Z" }, - { url = "https://files.pythonhosted.org/packages/a8/44/d9502bf0ed197ba9bf1103c9867d5904ddcaf869e52329787fc54ed70cc8/pandas-2.2.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:66108071e1b935240e74525006034333f98bcdb87ea116de573a6a0dccb6c039", size = 12602222, upload-time = "2024-09-20T13:08:56.254Z" }, - { url = "https://files.pythonhosted.org/packages/52/11/9eac327a38834f162b8250aab32a6781339c69afe7574368fffe46387edf/pandas-2.2.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7c2875855b0ff77b2a64a0365e24455d9990730d6431b9e0ee18ad8acee13dbd", size = 11321274, upload-time = "2024-09-20T13:08:58.645Z" }, - { url = "https://files.pythonhosted.org/packages/45/fb/c4beeb084718598ba19aa9f5abbc8aed8b42f90930da861fcb1acdb54c3a/pandas-2.2.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cd8d0c3be0515c12fed0bdbae072551c8b54b7192c7b1fda0ba56059a0179698", size = 15579836, upload-time = "2024-09-20T19:01:57.571Z" }, - { url = "https://files.pythonhosted.org/packages/cd/5f/4dba1d39bb9c38d574a9a22548c540177f78ea47b32f99c0ff2ec499fac5/pandas-2.2.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c124333816c3a9b03fbeef3a9f230ba9a737e9e5bb4060aa2107a86cc0a497fc", size = 13058505, upload-time = "2024-09-20T13:09:01.501Z" }, - { url = "https://files.pythonhosted.org/packages/b9/57/708135b90391995361636634df1f1130d03ba456e95bcf576fada459115a/pandas-2.2.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:63cc132e40a2e084cf01adf0775b15ac515ba905d7dcca47e9a251819c575ef3", size = 16744420, upload-time = "2024-09-20T19:02:00.678Z" }, - { url = "https://files.pythonhosted.org/packages/86/4a/03ed6b7ee323cf30404265c284cee9c65c56a212e0a08d9ee06984ba2240/pandas-2.2.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:29401dbfa9ad77319367d36940cd8a0b3a11aba16063e39632d98b0e931ddf32", size = 14440457, upload-time = "2024-09-20T13:09:04.105Z" }, - { url = "https://files.pythonhosted.org/packages/ed/8c/87ddf1fcb55d11f9f847e3c69bb1c6f8e46e2f40ab1a2d2abadb2401b007/pandas-2.2.3-cp311-cp311-win_amd64.whl", hash = "sha256:3fc6873a41186404dad67245896a6e440baacc92f5b716ccd1bc9ed2995ab2c5", size = 11617166, upload-time = "2024-09-20T13:09:06.917Z" }, - { url = "https://files.pythonhosted.org/packages/17/a3/fb2734118db0af37ea7433f57f722c0a56687e14b14690edff0cdb4b7e58/pandas-2.2.3-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b1d432e8d08679a40e2a6d8b2f9770a5c21793a6f9f47fdd52c5ce1948a5a8a9", size = 12529893, upload-time = "2024-09-20T13:09:09.655Z" }, - { url = "https://files.pythonhosted.org/packages/e1/0c/ad295fd74bfac85358fd579e271cded3ac969de81f62dd0142c426b9da91/pandas-2.2.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a5a1595fe639f5988ba6a8e5bc9649af3baf26df3998a0abe56c02609392e0a4", size = 11363475, upload-time = "2024-09-20T13:09:14.718Z" }, - { url = "https://files.pythonhosted.org/packages/c6/2a/4bba3f03f7d07207481fed47f5b35f556c7441acddc368ec43d6643c5777/pandas-2.2.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5de54125a92bb4d1c051c0659e6fcb75256bf799a732a87184e5ea503965bce3", size = 15188645, upload-time = "2024-09-20T19:02:03.88Z" }, - { url = "https://files.pythonhosted.org/packages/38/f8/d8fddee9ed0d0c0f4a2132c1dfcf0e3e53265055da8df952a53e7eaf178c/pandas-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fffb8ae78d8af97f849404f21411c95062db1496aeb3e56f146f0355c9989319", size = 12739445, upload-time = "2024-09-20T13:09:17.621Z" }, - { url = "https://files.pythonhosted.org/packages/20/e8/45a05d9c39d2cea61ab175dbe6a2de1d05b679e8de2011da4ee190d7e748/pandas-2.2.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6dfcb5ee8d4d50c06a51c2fffa6cff6272098ad6540aed1a76d15fb9318194d8", size = 16359235, upload-time = "2024-09-20T19:02:07.094Z" }, - { url = "https://files.pythonhosted.org/packages/1d/99/617d07a6a5e429ff90c90da64d428516605a1ec7d7bea494235e1c3882de/pandas-2.2.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:062309c1b9ea12a50e8ce661145c6aab431b1e99530d3cd60640e255778bd43a", size = 14056756, upload-time = "2024-09-20T13:09:20.474Z" }, - { url = "https://files.pythonhosted.org/packages/29/d4/1244ab8edf173a10fd601f7e13b9566c1b525c4f365d6bee918e68381889/pandas-2.2.3-cp312-cp312-win_amd64.whl", hash = "sha256:59ef3764d0fe818125a5097d2ae867ca3fa64df032331b7e0917cf5d7bf66b13", size = 11504248, upload-time = "2024-09-20T13:09:23.137Z" }, - { url = "https://files.pythonhosted.org/packages/64/22/3b8f4e0ed70644e85cfdcd57454686b9057c6c38d2f74fe4b8bc2527214a/pandas-2.2.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f00d1345d84d8c86a63e476bb4955e46458b304b9575dcf71102b5c705320015", size = 12477643, upload-time = "2024-09-20T13:09:25.522Z" }, - { url = "https://files.pythonhosted.org/packages/e4/93/b3f5d1838500e22c8d793625da672f3eec046b1a99257666c94446969282/pandas-2.2.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3508d914817e153ad359d7e069d752cdd736a247c322d932eb89e6bc84217f28", size = 11281573, upload-time = "2024-09-20T13:09:28.012Z" }, - { url = "https://files.pythonhosted.org/packages/f5/94/6c79b07f0e5aab1dcfa35a75f4817f5c4f677931d4234afcd75f0e6a66ca/pandas-2.2.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:22a9d949bfc9a502d320aa04e5d02feab689d61da4e7764b62c30b991c42c5f0", size = 15196085, upload-time = "2024-09-20T19:02:10.451Z" }, - { url = "https://files.pythonhosted.org/packages/e8/31/aa8da88ca0eadbabd0a639788a6da13bb2ff6edbbb9f29aa786450a30a91/pandas-2.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f3a255b2c19987fbbe62a9dfd6cff7ff2aa9ccab3fc75218fd4b7530f01efa24", size = 12711809, upload-time = "2024-09-20T13:09:30.814Z" }, - { url = "https://files.pythonhosted.org/packages/ee/7c/c6dbdb0cb2a4344cacfb8de1c5808ca885b2e4dcfde8008266608f9372af/pandas-2.2.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:800250ecdadb6d9c78eae4990da62743b857b470883fa27f652db8bdde7f6659", size = 16356316, upload-time = "2024-09-20T19:02:13.825Z" }, - { url = "https://files.pythonhosted.org/packages/57/b7/8b757e7d92023b832869fa8881a992696a0bfe2e26f72c9ae9f255988d42/pandas-2.2.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6374c452ff3ec675a8f46fd9ab25c4ad0ba590b71cf0656f8b6daa5202bca3fb", size = 14022055, upload-time = "2024-09-20T13:09:33.462Z" }, - { url = "https://files.pythonhosted.org/packages/3b/bc/4b18e2b8c002572c5a441a64826252ce5da2aa738855747247a971988043/pandas-2.2.3-cp313-cp313-win_amd64.whl", hash = "sha256:61c5ad4043f791b61dd4752191d9f07f0ae412515d59ba8f005832a532f8736d", size = 11481175, upload-time = "2024-09-20T13:09:35.871Z" }, - { url = "https://files.pythonhosted.org/packages/76/a3/a5d88146815e972d40d19247b2c162e88213ef51c7c25993942c39dbf41d/pandas-2.2.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3b71f27954685ee685317063bf13c7709a7ba74fc996b84fc6821c59b0f06468", size = 12615650, upload-time = "2024-09-20T13:09:38.685Z" }, - { url = "https://files.pythonhosted.org/packages/9c/8c/f0fd18f6140ddafc0c24122c8a964e48294acc579d47def376fef12bcb4a/pandas-2.2.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:38cf8125c40dae9d5acc10fa66af8ea6fdf760b2714ee482ca691fc66e6fcb18", size = 11290177, upload-time = "2024-09-20T13:09:41.141Z" }, - { url = "https://files.pythonhosted.org/packages/ed/f9/e995754eab9c0f14c6777401f7eece0943840b7a9fc932221c19d1abee9f/pandas-2.2.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ba96630bc17c875161df3818780af30e43be9b166ce51c9a18c1feae342906c2", size = 14651526, upload-time = "2024-09-20T19:02:16.905Z" }, - { url = "https://files.pythonhosted.org/packages/25/b0/98d6ae2e1abac4f35230aa756005e8654649d305df9a28b16b9ae4353bff/pandas-2.2.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1db71525a1538b30142094edb9adc10be3f3e176748cd7acc2240c2f2e5aa3a4", size = 11871013, upload-time = "2024-09-20T13:09:44.39Z" }, - { url = "https://files.pythonhosted.org/packages/cc/57/0f72a10f9db6a4628744c8e8f0df4e6e21de01212c7c981d31e50ffc8328/pandas-2.2.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:15c0e1e02e93116177d29ff83e8b1619c93ddc9c49083f237d4312337a61165d", size = 15711620, upload-time = "2024-09-20T19:02:20.639Z" }, - { url = "https://files.pythonhosted.org/packages/ab/5f/b38085618b950b79d2d9164a711c52b10aefc0ae6833b96f626b7021b2ed/pandas-2.2.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:ad5b65698ab28ed8d7f18790a0dc58005c7629f227be9ecc1072aa74c0c1d43a", size = 13098436, upload-time = "2024-09-20T13:09:48.112Z" }, -] - [[package]] name = "pandas" version = "2.3.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14'", + "python_full_version < '3.12'", ] dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12' or python_full_version >= '3.14'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and python_full_version < '3.14'" }, - { name = "python-dateutil", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, - { name = "pytz", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, - { name = "tzdata", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, ] sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3d/f7/f425a00df4fcc22b292c6895c6831c0c8ae1d9fac1e024d16f98a9ce8749/pandas-2.3.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:376c6446ae31770764215a6c937f72d917f214b43560603cd60da6408f183b6c", size = 11555763, upload-time = "2025-09-29T23:16:53.287Z" }, - { url = "https://files.pythonhosted.org/packages/13/4f/66d99628ff8ce7857aca52fed8f0066ce209f96be2fede6cef9f84e8d04f/pandas-2.3.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e19d192383eab2f4ceb30b412b22ea30690c9e618f78870357ae1d682912015a", size = 10801217, upload-time = "2025-09-29T23:17:04.522Z" }, - { url = "https://files.pythonhosted.org/packages/1d/03/3fc4a529a7710f890a239cc496fc6d50ad4a0995657dccc1d64695adb9f4/pandas-2.3.3-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5caf26f64126b6c7aec964f74266f435afef1c1b13da3b0636c7518a1fa3e2b1", size = 12148791, upload-time = "2025-09-29T23:17:18.444Z" }, - { url = "https://files.pythonhosted.org/packages/40/a8/4dac1f8f8235e5d25b9955d02ff6f29396191d4e665d71122c3722ca83c5/pandas-2.3.3-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dd7478f1463441ae4ca7308a70e90b33470fa593429f9d4c578dd00d1fa78838", size = 12769373, upload-time = "2025-09-29T23:17:35.846Z" }, - { url = "https://files.pythonhosted.org/packages/df/91/82cc5169b6b25440a7fc0ef3a694582418d875c8e3ebf796a6d6470aa578/pandas-2.3.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4793891684806ae50d1288c9bae9330293ab4e083ccd1c5e383c34549c6e4250", size = 13200444, upload-time = "2025-09-29T23:17:49.341Z" }, - { url = "https://files.pythonhosted.org/packages/10/ae/89b3283800ab58f7af2952704078555fa60c807fff764395bb57ea0b0dbd/pandas-2.3.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:28083c648d9a99a5dd035ec125d42439c6c1c525098c58af0fc38dd1a7a1b3d4", size = 13858459, upload-time = "2025-09-29T23:18:03.722Z" }, - { url = "https://files.pythonhosted.org/packages/85/72/530900610650f54a35a19476eca5104f38555afccda1aa11a92ee14cb21d/pandas-2.3.3-cp310-cp310-win_amd64.whl", hash = "sha256:503cf027cf9940d2ceaa1a93cfb5f8c8c7e6e90720a2850378f0b3f3b1e06826", size = 11346086, upload-time = "2025-09-29T23:18:18.505Z" }, { url = "https://files.pythonhosted.org/packages/c1/fa/7ac648108144a095b4fb6aa3de1954689f7af60a14cf25583f4960ecb878/pandas-2.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:602b8615ebcc4a0c1751e71840428ddebeb142ec02c786e8ad6b1ce3c8dec523", size = 11578790, upload-time = "2025-09-29T23:18:30.065Z" }, { url = "https://files.pythonhosted.org/packages/9b/35/74442388c6cf008882d4d4bdfc4109be87e9b8b7ccd097ad1e7f006e2e95/pandas-2.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8fe25fc7b623b0ef6b5009149627e34d2a4657e880948ec3c840e9402e5c1b45", size = 10833831, upload-time = "2025-09-29T23:38:56.071Z" }, { url = "https://files.pythonhosted.org/packages/fe/e4/de154cbfeee13383ad58d23017da99390b91d73f8c11856f2095e813201b/pandas-2.3.3-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b468d3dad6ff947df92dcb32ede5b7bd41a9b3cceef0a30ed925f6d01fb8fa66", size = 12199267, upload-time = "2025-09-29T23:18:41.627Z" }, @@ -3400,14 +2983,12 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, - { name = "python-dateutil", marker = "python_full_version >= '3.14'" }, - { name = "tzdata", marker = "(python_full_version >= '3.14' and sys_platform == 'emscripten') or (python_full_version >= '3.14' and sys_platform == 'win32')" }, + { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f8/87/4341c6252d1c47b08768c3d25ac487362bf403f0313ddae4a2a26c9b1b4c/pandas-3.0.3.tar.gz", hash = "sha256:696a4a00a2a2a35d4e5deb3fc946641b96c944f02230e4f76137fe35d806c4fc", size = 4651414, upload-time = "2026-05-11T18:54:29.21Z" } wheels = [ @@ -3494,8 +3075,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "accelerate" }, { name = "huggingface-hub" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "packaging" }, { name = "psutil" }, @@ -3515,7 +3095,7 @@ name = "pexpect" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ptyprocess", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { 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 = [ @@ -3524,96 +3104,92 @@ wheels = [ [[package]] name = "pillow" -version = "12.3.0" +version = "13.0.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" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/25/c2/669d88644cddb1485bd9534e63e8cf476c8e51cb3c3a1297677023505c0e/pillow-12.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a", size = 5392418, upload-time = "2026-07-01T11:53:27.808Z" }, - { url = "https://files.pythonhosted.org/packages/6b/ba/3762f376a2948e3036488d773a146e0ae6ecc2ca03ac20e2615bd0b2ba02/pillow-12.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7", size = 4785287, upload-time = "2026-07-01T11:53:29.761Z" }, - { url = "https://files.pythonhosted.org/packages/07/50/b5d688cc9c52d4482f3d5bcab6ce20bc2a74a85d2343841c907444a3be2c/pillow-12.3.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f", size = 6253754, upload-time = "2026-07-01T11:53:32.298Z" }, - { url = "https://files.pythonhosted.org/packages/4e/89/36f4cd76cf4baf05c50ababb976249153f18c959171c7f6ba09a6f217260/pillow-12.3.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec", size = 6925605, upload-time = "2026-07-01T11:53:34.487Z" }, - { url = "https://files.pythonhosted.org/packages/eb/c0/4de58cf6633b9e3a6061ef4be6fb91fc3c90b812ece886f531e3c523d777/pillow-12.3.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468", size = 6327788, upload-time = "2026-07-01T11:53:36.433Z" }, - { url = "https://files.pythonhosted.org/packages/87/3c/14d53682a19550dbbaf3b598f807d5457646c510805a44c7d7891cd1cd1a/pillow-12.3.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed", size = 7036288, upload-time = "2026-07-01T11:53:38.712Z" }, - { url = "https://files.pythonhosted.org/packages/38/1d/36279e3c77efe034e4cc2b0393ee74ffdb5a62391dacbf9b916154f5f0b8/pillow-12.3.0-cp310-cp310-win32.whl", hash = "sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1", size = 6472396, upload-time = "2026-07-01T11:53:40.781Z" }, - { url = "https://files.pythonhosted.org/packages/48/7c/8fa0039574c476d7c6fa57dd7c32a130436877c6ec1e5ce1cc8ec44878c1/pillow-12.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb", size = 7226887, upload-time = "2026-07-01T11:53:42.764Z" }, - { url = "https://files.pythonhosted.org/packages/fa/17/e324be141d173c1c919428066c3259f21c1b8982e564e01a4a81e96dbdcf/pillow-12.3.0-cp310-cp310-win_arm64.whl", hash = "sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f", size = 2568039, upload-time = "2026-07-01T11:53:45.372Z" }, - { url = "https://files.pythonhosted.org/packages/fb/c8/0a78b0e02d7ac54bc03e5321c9220da52f0c2ea83b21f7c40e7f3169c502/pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756", size = 5392415, upload-time = "2026-07-01T11:53:47.162Z" }, - { url = "https://files.pythonhosted.org/packages/b2/5b/a02d30018abd97ced9f5a6c63d28597694a00d066516b9c1c6de45859fc9/pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6", size = 4785266, upload-time = "2026-07-01T11:53:49.079Z" }, - { url = "https://files.pythonhosted.org/packages/c8/98/766667a4be768150a202836acd9fad19c06824ca86c4286d3cf6b274964e/pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd", size = 6263814, upload-time = "2026-07-01T11:53:51.32Z" }, - { url = "https://files.pythonhosted.org/packages/3b/2d/ede717bc1144f63886c21fd349bb95860b0d1a21149ff16f2bb362b612b6/pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd", size = 6934408, upload-time = "2026-07-01T11:53:53.487Z" }, - { url = "https://files.pythonhosted.org/packages/a3/48/9c58b685e69d49c31af6c8eb9012055fab7e665785165c84796e2c73ce72/pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c", size = 6337160, upload-time = "2026-07-01T11:53:55.457Z" }, - { url = "https://files.pythonhosted.org/packages/ff/fa/dc2a5c0ba6df93f67c31d34b808b7ce440b40cdbf96f0b81cde1d1e6fa93/pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5", size = 7045172, upload-time = "2026-07-01T11:53:57.736Z" }, - { url = "https://files.pythonhosted.org/packages/86/a5/444817a4d4c4c2417df00513086ca196f388d8f9ef40c2e4ccd1ad1af54b/pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b", size = 6472232, upload-time = "2026-07-01T11:53:59.767Z" }, - { url = "https://files.pythonhosted.org/packages/63/c6/4bad1b18d132a50b27e1365e1ab163616f7a5bb56d330f66f9d1d9d4f9d4/pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a", size = 7233653, upload-time = "2026-07-01T11:54:02.066Z" }, - { url = "https://files.pythonhosted.org/packages/fd/16/00f91ab7760dc842f5aad55217e80fc4a7067a0604535249bc8a2d6d9870/pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26", size = 2568195, upload-time = "2026-07-01T11:54:04.622Z" }, - { 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" }, - { url = "https://files.pythonhosted.org/packages/75/18/2e8b40223153ccbc60df07f9e8928dc0c76202aa4e55ae9f53962b6510d6/pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468", size = 5302510, upload-time = "2026-07-01T11:56:25.736Z" }, - { url = "https://files.pythonhosted.org/packages/46/3e/51fabf59d5ab801ceab709453d3ab6b180083496579549de4c45ced6528a/pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94", size = 4736058, upload-time = "2026-07-01T11:56:28.041Z" }, - { url = "https://files.pythonhosted.org/packages/bf/20/22fe9384b7949e25fb1293bcfc84fb82590ff4ea6b37c95b24d26d793d86/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e", size = 5237776, upload-time = "2026-07-01T11:56:30.263Z" }, - { url = "https://files.pythonhosted.org/packages/08/14/f6ba68107680ffa74b39985f3f30884e41318fbc4250caa423c79b4788bb/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3", size = 5860358, upload-time = "2026-07-01T11:56:32.68Z" }, - { url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" }, + { url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" }, + { url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" }, + { url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" }, + { url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" }, + { url = "https://files.pythonhosted.org/packages/7a/b8/58d79332229482eb0d27c82973850808c19d37e5bdc14443d3417bd373f5/pillow-13.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79", size = 5568643, upload-time = "2026-10-16T22:15:44.474Z" }, + { url = "https://files.pythonhosted.org/packages/39/4b/f2ed53d83aa44ac19599ac0a54897f867fafb95f406980d1e24083f8cbe3/pillow-13.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52", size = 4852329, upload-time = "2026-10-16T22:15:46.284Z" }, + { url = "https://files.pythonhosted.org/packages/3b/bb/9e30e8ed18c20800ee327a12107d5249ad8dc444867b3adfcc21654e3c71/pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d", size = 6519309, upload-time = "2026-10-16T22:15:48.14Z" }, + { url = "https://files.pythonhosted.org/packages/e6/99/fdf65cc539e266ab93546c261bdf98411fe165c6e4e13f9dbf597097192b/pillow-13.0.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca", size = 7144542, upload-time = "2026-10-16T22:15:50.093Z" }, + { url = "https://files.pythonhosted.org/packages/26/9b/f38b7c4d8f599537e2d1a6d546cec9beef7536ff8f5c49a3f9c78179d8ac/pillow-13.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620", size = 6618042, upload-time = "2026-10-16T22:15:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a8/7c/45ee28531f89ee4582967d8a17f7a26d71ca64cd902b93c269590cd60a00/pillow-13.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40", size = 7228137, upload-time = "2026-10-16T22:15:54.009Z" }, + { url = "https://files.pythonhosted.org/packages/01/bc/9c2a969cb1b70201d04fa17fd5aedf02a732870b8da86bceaaa30b0ca385/pillow-13.0.0-cp312-cp312-win32.whl", hash = "sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27", size = 6515423, upload-time = "2026-10-16T22:15:56.25Z" }, + { url = "https://files.pythonhosted.org/packages/ff/cd/73a79ecdc822076002eb24b5e1e4a530b0bb5310fcb6d239abbec877110b/pillow-13.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b", size = 7272166, upload-time = "2026-10-16T22:15:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/4a/a3/be5a1236efd085b3984e4305da8f179ae9dab80c991d2ad78f2bd5c4c843/pillow-13.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51", size = 2698943, upload-time = "2026-10-16T22:16:00.637Z" }, + { url = "https://files.pythonhosted.org/packages/82/e2/9132d38df320e8099e2642d9fa538f18a7dfebf68a875a31725dc2a115aa/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00", size = 4190620, upload-time = "2026-10-16T22:16:02.527Z" }, + { url = "https://files.pythonhosted.org/packages/cb/be/436dac0996876f65ef1916ffb711c5ef4af2ebc57414b6f16642e07f6b47/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033", size = 4290286, upload-time = "2026-10-16T22:16:04.861Z" }, + { url = "https://files.pythonhosted.org/packages/60/16/7c1007162e4169ea0d5bec47e2e0b2174f56c50cf5b8c02a1dc23e41037e/pillow-13.0.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599", size = 3723169, upload-time = "2026-10-16T22:16:06.956Z" }, + { url = "https://files.pythonhosted.org/packages/08/bc/578ab2eaa04705a8978bd9be0fe15c3d43a8fc95097c4f7e39540e79e4fa/pillow-13.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe", size = 5568469, upload-time = "2026-10-16T22:16:08.664Z" }, + { url = "https://files.pythonhosted.org/packages/98/c8/ccede3dcc4f274b80fb49199eed1ef34ba05566c8b71976b9d1f111da2e3/pillow-13.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313", size = 4852187, upload-time = "2026-10-16T22:16:10.693Z" }, + { url = "https://files.pythonhosted.org/packages/fb/3c/cd0770e96d20bfd990db024bcbd43897ff3e88da1f4782cf90ea231b1d4f/pillow-13.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369", size = 6515908, upload-time = "2026-10-16T22:16:12.896Z" }, + { url = "https://files.pythonhosted.org/packages/ef/fe/f5cdaa2d1c4086e757430f368c271a58ee29cfe7378e7ae7b9d964015c25/pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582", size = 7142544, upload-time = "2026-10-16T22:16:14.844Z" }, + { url = "https://files.pythonhosted.org/packages/fb/b5/a54f6d44adbcd23737c8c12953f42be107e4cca64e247c0ca3a5b563061c/pillow-13.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81", size = 6613097, upload-time = "2026-10-16T22:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/e6/b4/9e6c1207c21b2e91db0d15c16d30f3701ce5add1bd4da0e787761e66cb6e/pillow-13.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502", size = 7224846, upload-time = "2026-10-16T22:16:19.195Z" }, + { url = "https://files.pythonhosted.org/packages/78/9f/d3c3cb0518f3dd1eee0ef501535f53d15597a53c5c4118d178086143397a/pillow-13.0.0-cp313-cp313-win32.whl", hash = "sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8", size = 6516013, upload-time = "2026-10-16T22:16:21.389Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ed/1b16fb66a37e1b9e41370b93b2c614c7da761a5b2a41dc333f7af4639962/pillow-13.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42", size = 7284777, upload-time = "2026-10-16T22:16:23.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/7d/8d02eba9f7ecc87f8e90f731e032cc4773802f2a843763afd0c66a535ff4/pillow-13.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f", size = 2698826, upload-time = "2026-10-16T22:16:25.382Z" }, + { url = "https://files.pythonhosted.org/packages/8e/45/fbad9c7f5e2f1745c373a434d46072bc84eddfefaa28b852425ac957fda6/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c", size = 4190721, upload-time = "2026-10-16T22:16:27.524Z" }, + { url = "https://files.pythonhosted.org/packages/a2/bf/2074902a259a90692c5dbf132885d21671644cbbd3f690047516243a55db/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76", size = 4290236, upload-time = "2026-10-16T22:16:29.562Z" }, + { url = "https://files.pythonhosted.org/packages/ff/a5/3d1bb93b8ea38d15d21356c1b8e9f50971ac592aaa248f7fb71739094c0e/pillow-13.0.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981", size = 3723093, upload-time = "2026-10-16T22:16:31.249Z" }, + { url = "https://files.pythonhosted.org/packages/84/a1/be060135d85187b25fa8b2573786c0e45c62ae27527fff5257675eb97f4a/pillow-13.0.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4", size = 5572253, upload-time = "2026-10-16T22:16:33.103Z" }, + { url = "https://files.pythonhosted.org/packages/b5/f4/0bf6f1ac9ba7ee2ffe9914aeb410a1035a0c1a3c42f122388d7fc950bc4b/pillow-13.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d", size = 4852269, upload-time = "2026-10-16T22:16:35.102Z" }, + { url = "https://files.pythonhosted.org/packages/83/16/b603274617b3e6728da3a0133d4fba1ea8d7fbe0c4ea5fef9cbffa398b8b/pillow-13.0.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6", size = 6516058, upload-time = "2026-10-16T22:16:37.228Z" }, + { url = "https://files.pythonhosted.org/packages/1d/f2/1371707ce438ba9a43f9d24089828494ec6f9396e28cd7903aa704dd6306/pillow-13.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d", size = 7142574, upload-time = "2026-10-16T22:16:39.172Z" }, + { url = "https://files.pythonhosted.org/packages/b9/a9/62cf68587f910bc87c5951bcb6e9430c7643a65076adf5f18b4bf350e2bd/pillow-13.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c", size = 6614295, upload-time = "2026-10-16T22:16:41.117Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c9/9e9b48178649730299be0bafbf5f810a5b6977538f5a92d47e4ba5f5d608/pillow-13.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0", size = 7224841, upload-time = "2026-10-16T22:16:43.118Z" }, + { url = "https://files.pythonhosted.org/packages/8f/48/c44e91384b1b6c072a714a63d00608acc16a6a968735e478e4be4384e5ac/pillow-13.0.0-cp314-cp314-win32.whl", hash = "sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055", size = 6508694, upload-time = "2026-10-16T22:16:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/50/e2/7ad17747517e4c813dca78257d6bb593466f8231baf1384bc98d92745edb/pillow-13.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a", size = 7281830, upload-time = "2026-10-16T22:16:47.725Z" }, + { url = "https://files.pythonhosted.org/packages/41/9f/e5b51f2ce8ef4563215334035403ce61a244f93a2e65c24a940131618f87/pillow-13.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4", size = 2695468, upload-time = "2026-10-16T22:16:49.515Z" }, + { url = "https://files.pythonhosted.org/packages/97/73/a53502f731f6c84805a4ce87a8881e86d07a65aee64728b900d112dc703e/pillow-13.0.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa", size = 5578196, upload-time = "2026-10-16T22:16:51.291Z" }, + { url = "https://files.pythonhosted.org/packages/21/50/7e949959a56b5559c78ef172b70fc6025706acb289f3f648a15329e4fa6f/pillow-13.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f", size = 4857276, upload-time = "2026-10-16T22:16:53.399Z" }, + { url = "https://files.pythonhosted.org/packages/c9/52/43ded0ac08e77e39d17bd6d894162572201b5e8fdc4a022b14c55a1960a4/pillow-13.0.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1", size = 6607008, upload-time = "2026-10-16T22:16:55.525Z" }, + { url = "https://files.pythonhosted.org/packages/0d/2e/4a57ed216d5bf877387cba4d44c02aa87abe51ad2e06404aa6b597c4da39/pillow-13.0.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683", size = 7224281, upload-time = "2026-10-16T22:16:57.738Z" }, + { url = "https://files.pythonhosted.org/packages/5c/3d/2929b248e135752d63aaeabf53f6de797e905b7b6263f9c1e2adade20aba/pillow-13.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058", size = 6695600, upload-time = "2026-10-16T22:16:59.842Z" }, + { url = "https://files.pythonhosted.org/packages/bc/33/fb0da992cf084ed1ee6ee05e96b6191e35c351eb707ca2df874feb24ce47/pillow-13.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e", size = 7300589, upload-time = "2026-10-16T22:17:01.686Z" }, + { url = "https://files.pythonhosted.org/packages/bb/af/c30dd9ef6a3dce84ecb1b2393cac629047a32e66279056c6cb46c3ffd65c/pillow-13.0.0-cp314-cp314t-win32.whl", hash = "sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15", size = 6517204, upload-time = "2026-10-16T22:17:03.722Z" }, + { url = "https://files.pythonhosted.org/packages/85/d5/ef3a8ae7609c8ab26570abf18194882534b480d245a9148b895a2262c004/pillow-13.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0", size = 7286695, upload-time = "2026-10-16T22:17:05.543Z" }, + { url = "https://files.pythonhosted.org/packages/84/3c/0861db0c69a03689ebe3e7599d35668a414deb5aaafd8255215e4e62e3d3/pillow-13.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692", size = 2698098, upload-time = "2026-10-16T22:17:07.674Z" }, + { url = "https://files.pythonhosted.org/packages/6e/eb/e86a41962a3a31ad495a3d6a912d9002b01bba4a6fa71c28703abdca7f69/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521", size = 4191213, upload-time = "2026-10-16T22:17:09.449Z" }, + { url = "https://files.pythonhosted.org/packages/dd/04/7e7445e706afec84ef06dc25b2c77f9cecff242c23730c62928ad1089d4a/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc", size = 4290650, upload-time = "2026-10-16T22:17:11.196Z" }, + { url = "https://files.pythonhosted.org/packages/46/85/d534089068ac40c0f61f650389a296c812eab745a8a733f81feec39ae955/pillow-13.0.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac", size = 3723078, upload-time = "2026-10-16T22:17:12.772Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2b/00b5c3b401df538b5dbe311d3899730fae5ba1e21cb8b80a128887ac6747/pillow-13.0.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d", size = 5572292, upload-time = "2026-10-16T22:17:14.539Z" }, + { url = "https://files.pythonhosted.org/packages/72/f5/a6b0610f946e9b54ae888ba7ad29d6e2f8d9b11f69e212d70416b7186c09/pillow-13.0.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782", size = 4852222, upload-time = "2026-10-16T22:17:16.521Z" }, + { url = "https://files.pythonhosted.org/packages/1e/d0/c0ff25bb0427ec70f32aac995453321fc3c4494a46c7292ff02d9d260b04/pillow-13.0.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071", size = 6527349, upload-time = "2026-10-16T22:17:18.534Z" }, + { url = "https://files.pythonhosted.org/packages/85/11/e46fa0bcc0fc117f1eacc206b3d51f04d583fab328b4b740672d0438d83f/pillow-13.0.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf", size = 7152873, upload-time = "2026-10-16T22:17:20.415Z" }, + { url = "https://files.pythonhosted.org/packages/7c/53/2bdeca705f3a58679fa9201233193c86a30238340ca29b3a152c3fcc719b/pillow-13.0.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3", size = 6626871, upload-time = "2026-10-16T22:17:22.361Z" }, + { url = "https://files.pythonhosted.org/packages/14/de/3829030f209722ade3753bb456b805a0e7f885cf885b483407365c82e9ca/pillow-13.0.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932", size = 7236439, upload-time = "2026-10-16T22:17:24.352Z" }, + { url = "https://files.pythonhosted.org/packages/44/b1/67fc37388382bc036a74f04da5bb6fcbf90ec3ac1f45893e06176c373fd3/pillow-13.0.0-cp315-cp315-win32.whl", hash = "sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81", size = 6508688, upload-time = "2026-10-16T22:17:26.314Z" }, + { url = "https://files.pythonhosted.org/packages/44/05/fdb6a79aee10861165526b41b7b440e36ee1ff58613b2fbefe3acbf06d4f/pillow-13.0.0-cp315-cp315-win_amd64.whl", hash = "sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6", size = 7281107, upload-time = "2026-10-16T22:17:28.198Z" }, + { url = "https://files.pythonhosted.org/packages/e6/9c/6c6f7dc2a566467baf121394e83de25ac287cffe34cc030726beb4be0224/pillow-13.0.0-cp315-cp315-win_arm64.whl", hash = "sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0", size = 2695513, upload-time = "2026-10-16T22:17:30.013Z" }, + { url = "https://files.pythonhosted.org/packages/23/16/e9120defdb8bff693b582d035312acc6f530cdc2bc5238a87f410efccd82/pillow-13.0.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f", size = 5578129, upload-time = "2026-10-16T22:17:31.642Z" }, + { url = "https://files.pythonhosted.org/packages/47/22/76faf2bb2448f48a84cf894c1e2bb1090d7d2b1aa521ece131cb2f05d631/pillow-13.0.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88", size = 4857428, upload-time = "2026-10-16T22:17:33.43Z" }, + { url = "https://files.pythonhosted.org/packages/b3/64/0861ea4e03c50b14af9ed9dd8b9f388ab42f445c623a9fcbab19aef7aa55/pillow-13.0.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb", size = 6612582, upload-time = "2026-10-16T22:17:35.415Z" }, + { url = "https://files.pythonhosted.org/packages/5c/20/cd1e9b3f60a9f3d5ebe46da36955c26004092a501f7f2c42f9fcc26611bc/pillow-13.0.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe", size = 7230176, upload-time = "2026-10-16T22:17:37.362Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ef/ffb0a2fc85690714fb7ac662956949645d57f15bf4426f520da361e7b6e3/pillow-13.0.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22", size = 6703640, upload-time = "2026-10-16T22:17:39.313Z" }, + { url = "https://files.pythonhosted.org/packages/e0/c2/6402ee3ccb3363aeed8fdb3f9fe56703ac5377a539f0b81b53999d7e121f/pillow-13.0.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630", size = 7309231, upload-time = "2026-10-16T22:17:41.021Z" }, + { url = "https://files.pythonhosted.org/packages/fc/96/d6b82e8b8c06ad143b66b12e0b31051e4bf489b4fabca1f390a14fe1ebde/pillow-13.0.0-cp315-cp315t-win32.whl", hash = "sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2", size = 6517200, upload-time = "2026-10-16T22:17:42.886Z" }, + { url = "https://files.pythonhosted.org/packages/60/d4/0062e6005e9b270b165015aafd343364ac378ec5a685431ea42baad33357/pillow-13.0.0-cp315-cp315t-win_amd64.whl", hash = "sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43", size = 7287488, upload-time = "2026-10-16T22:17:45.56Z" }, + { url = "https://files.pythonhosted.org/packages/e4/81/b8eb349746be7bce47dd95337c6634e84910af91b59aaa9159c034c614fa/pillow-13.0.0-cp315-cp315t-win_arm64.whl", hash = "sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8", size = 2698073, upload-time = "2026-10-16T22:17:47.556Z" }, + { url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" }, + { url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" }, + { url = "https://files.pythonhosted.org/packages/60/da/f6d644e631c5b370c5d0b899f3ccadd2780aab070b29a110527cf4e1fd2c/pillow-13.0.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463", size = 5523188, upload-time = "2026-10-16T22:17:59.334Z" }, + { url = "https://files.pythonhosted.org/packages/e4/b0/2594f202d743a35d4fe80682bfd96f277e5ca7aecb27cf64ef5bfc1d000b/pillow-13.0.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e", size = 4806808, upload-time = "2026-10-16T22:18:01.188Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ed/d504165ef79af6fafe25c76726cf30f544cc236002f7ed054f1d51adc4ff/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63", size = 5464358, upload-time = "2026-10-16T22:18:02.779Z" }, + { url = "https://files.pythonhosted.org/packages/7b/fe/a10aba5503ca13e9e009b8bd0a1a4ce5584bdce246245fd6f3a83701369c/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61", size = 6043514, upload-time = "2026-10-16T22:18:04.538Z" }, + { url = "https://files.pythonhosted.org/packages/c0/37/66b12dc476041fe523bca29c9d58fbf1ea92a4eaf73acfb9e993948f1191/pillow-13.0.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a", size = 7366030, upload-time = "2026-10-16T22:18:06.638Z" }, ] [[package]] @@ -3681,23 +3257,6 @@ 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/5b/56/030b7b4719d53085722893e0009dffb9236aa10bca1b12121bdc5626ef16/propcache-0.5.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d5a81be28596d6559f6131ef33e10200de6e17643b3c74ce03f9eb103be6ae8b", size = 93417, upload-time = "2026-05-08T20:59:15.597Z" }, - { url = "https://files.pythonhosted.org/packages/1a/55/1140a8e067b8ec093a18a4ae7bb0045d9db65da38a08618ddc5e2f1994aa/propcache-0.5.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:29cbaac5ea0212663e6845e04b5e188d5a6ae6dd919810ac835bf1d3b42c3f4c", size = 53847, upload-time = "2026-05-08T20:59:17.096Z" }, - { url = "https://files.pythonhosted.org/packages/20/42/0e7443c90310498561addf346e7d57fe3c6ba1914e1ba938b5464c7bbfd2/propcache-0.5.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:6bf3be92233808fcd338eba0fb4d0b59ec5772af4f4ecfcec450d1bfc0f8b5eb", size = 53512, upload-time = "2026-05-08T20:59:18.64Z" }, - { url = "https://files.pythonhosted.org/packages/b7/db/cf51a71bab2009517d1a7f0ee07657e3bd446c4d69f67e6966cf17bcf956/propcache-0.5.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2f8ea531c794b9d6274acd4e8d2c2ebcac590a4361d27482edd3010b79f1325e", size = 58068, upload-time = "2026-05-08T20:59:20.683Z" }, - { url = "https://files.pythonhosted.org/packages/b7/43/39b6bdee9699fa1e1641c519feeb64a67e2a9f93bb465c70776b37a7333f/propcache-0.5.2-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:decfca4c79dd53ebab484b00cc4b6717d8c369f86e74aa4ca395a64ac651495e", size = 61020, upload-time = "2026-05-08T20:59:22.112Z" }, - { url = "https://files.pythonhosted.org/packages/26/0b/843726fbb0a29a8c5684fdb25971823638399f31e52e9d1f06a02dc9aa6b/propcache-0.5.2-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4621064bbf28fa77ff64dd5d94367c04684c67d3a5bf1dff25f0cd0d98a38f3b", size = 62732, upload-time = "2026-05-08T20:59:23.805Z" }, - { url = "https://files.pythonhosted.org/packages/39/6e/899fed76dc1942b8a64193a4f059d7f1a2c7ef65085e8a9366ed8ec0d199/propcache-0.5.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b96db7141a592cbc968daf1feea83a118e6ab378af4abbc72b248c895414c22d", size = 60140, upload-time = "2026-05-08T20:59:25.389Z" }, - { url = "https://files.pythonhosted.org/packages/ab/09/3da4be9b5b879219ad234aa535b3dd4a080ed1ad48d3a73ca07a9e798f22/propcache-0.5.2-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1ca071adabaab6e9219924bbe00af821f1ee7de113a9eca1cdc292de3d120f4d", size = 60400, upload-time = "2026-05-08T20:59:27.238Z" }, - { url = "https://files.pythonhosted.org/packages/60/2f/09b72b874a9aa0044faf52a69807a6ed618e267ceaa9ec4a63195fa5b504/propcache-0.5.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:e4294d04a94dcab1b3bccd8b66d962dcad411a1d19414b2a41d1445f1de32ad0", size = 58155, upload-time = "2026-05-08T20:59:28.48Z" }, - { url = "https://files.pythonhosted.org/packages/8a/37/97489848c54c95578045473954f10956d619ce6a09e7ac137b71cdcb698b/propcache-0.5.2-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:a0e399a2eccb91ed18721f86aa85757727400b6865c89e88934781deb9c8498b", size = 57037, upload-time = "2026-05-08T20:59:30.146Z" }, - { url = "https://files.pythonhosted.org/packages/22/db/6c695285ccfc49012743ee9c98212b8c5dd0aed7b63cfd816d4a0f7a1601/propcache-0.5.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:823581fd5cb08b12a48bfa11fe962a7916766b6170c17b028fbdf762b85eb9bf", size = 61103, upload-time = "2026-05-08T20:59:31.626Z" }, - { url = "https://files.pythonhosted.org/packages/98/a9/1e500401ca593b0bdb6bf75a70bc2d723835fd53360edff6af70692c7546/propcache-0.5.2-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:949c91d1a990cf3b2e8188dfcfb25005e0b834a06c63fa4ef9f360878ce21ecf", size = 60394, upload-time = "2026-05-08T20:59:32.829Z" }, - { url = "https://files.pythonhosted.org/packages/1f/87/f638b6e375eae0f30a1a2325d8b34fd85fdc785bb9960cf805f3bf1ec69a/propcache-0.5.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:cc1177027eda740fdb152706bd215a3f124e3eea15afc39f2cb9fe351b50619e", size = 63084, upload-time = "2026-05-08T20:59:35.964Z" }, - { url = "https://files.pythonhosted.org/packages/f6/18/884573f5d97b6d9eba68de759a82c901b7e39d7904d30f7b8d58d42d2a12/propcache-0.5.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b05d643f944a8c3c4bd86d65ffd87bf3264b617f87791940302bc474d2ff5274", size = 60999, upload-time = "2026-05-08T20:59:38.481Z" }, - { url = "https://files.pythonhosted.org/packages/8f/1a/c3915eb059ceec9e758a56e4cfd955292bc0f201be2176a46b76d94b303a/propcache-0.5.2-cp310-cp310-win32.whl", hash = "sha256:8114f28879e0904748e831c3a7774261bd9e75f49be089f389a76f959dcd13fe", size = 39036, upload-time = "2026-05-08T20:59:40.323Z" }, - { url = "https://files.pythonhosted.org/packages/5b/02/1dfd5607501a602d19c1c449d2d193b7d1c611f9246b4059026a1189a80e/propcache-0.5.2-cp310-cp310-win_amd64.whl", hash = "sha256:5fcb98e7598b1ee0addab320d90f65b530297a867dbfe9de52ea838077e16e3d", size = 42190, upload-time = "2026-05-08T20:59:42.232Z" }, - { url = "https://files.pythonhosted.org/packages/57/93/f71588ad08b3e6f4b555b5ef215808a3c02b042d0151ad82fa6f15be677a/propcache-0.5.2-cp310-cp310-win_arm64.whl", hash = "sha256:04dc2390d9edbbaef7461f33322555976ffddf0b650a038649d026358714e6c5", size = 38545, upload-time = "2026-05-08T20:59:44.087Z" }, { url = "https://files.pythonhosted.org/packages/e7/f1/8a8cc1c2c7e7934ab77e0163414f736fadbc0f5e8dd9673b952355ac175b/propcache-0.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:74b70780220e2dd89175ca24b81b68b67c83db499ae611e7f2313cb329801c78", size = 90744, upload-time = "2026-05-08T20:59:45.799Z" }, { url = "https://files.pythonhosted.org/packages/c2/f4/651b1225e976bd1a2ba5cfba0c29d096581c2636b437e3a9a7ab6276270a/propcache-0.5.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a4840ab0ae0216d952f4b53dc6d0b992bfc2bedbfe360bdd9b548bc184c08959", size = 52033, upload-time = "2026-05-08T20:59:47.408Z" }, { url = "https://files.pythonhosted.org/packages/15/a8/8ede85d6aa1f79fc7dc2f8fd2c8d65920b8272c3892903c8a1affde48cfb/propcache-0.5.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c6844ba6364fb12f403928a82cfd295ab103a2b315c77c747b2dbe4a41894ea7", size = 52754, upload-time = "2026-05-08T20:59:49.202Z" }, @@ -3851,59 +3410,59 @@ wheels = [ [[package]] name = "pyarrow" -version = "24.0.0" +version = "26.0.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/91/13/13e1069b351bdc3881266e11147ffccf687505dbb0ea74036237f5d454a5/pyarrow-24.0.0.tar.gz", hash = "sha256:85fe721a14dd823aca09127acbb06c3ca723efbd436c004f16bca601b04dcc83", size = 1180261, upload-time = "2026-04-21T10:51:25.837Z" } +sdist = { url = "https://files.pythonhosted.org/packages/bc/5e/9cb2a56d5e293aab4e2fbecc5b0620d93227d66b8d5a63c554c31e1f80fe/pyarrow-26.0.1.tar.gz", hash = "sha256:93affcbd8a343e98dc19e9ec8fe17271ebf8fe98102d8b7454175074409f8b72", size = 1237985, upload-time = "2026-11-03T10:54:17.563Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a5/bf/a34fee1d624152124fa8355c42f34195ad5fe5233ce5bb87946432047d52/pyarrow-24.0.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:7c2b98645d576a0b9616892ead22b64a83a5f043c5e2ca15ebcefcb5b70c80cb", size = 35076681, upload-time = "2026-04-21T08:51:46.845Z" }, - { url = "https://files.pythonhosted.org/packages/1d/41/64180033d7027afce12dc96d0fe1f504c6fa112190582b458acea2399530/pyarrow-24.0.0-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:644a246325b8c69c595ad1dd4b463eba4b0cdb731370e4a86137d433208d6147", size = 36684260, upload-time = "2026-04-21T08:51:53.642Z" }, - { url = "https://files.pythonhosted.org/packages/57/02/9b9320e673dd8a99411fac78690f3df92f6dd6f59754c750110bca66d64e/pyarrow-24.0.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:3a577bd840ca83f646f0a625dbc571dba7044c43c2d1503afc378b570954345c", size = 45698566, upload-time = "2026-04-21T10:46:02.133Z" }, - { url = "https://files.pythonhosted.org/packages/67/33/f75e91b9a64c3f33c787e263c93b871ad91b8a4a68c1d5cebddd9840e835/pyarrow-24.0.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:e3268e43984d0b1a185c89b4cfff282a7ead12fc93f56cfd7088bdbcbe727041", size = 48835562, upload-time = "2026-04-21T10:46:10.278Z" }, - { url = "https://files.pythonhosted.org/packages/a5/63/097510448e47e4091faa41c43ba92f97cecaab8f4535b56a3d149578f634/pyarrow-24.0.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:2392d954fcb920f42d230284b677605e4e2fbb11f2821e823e642abd67fbb491", size = 49394997, upload-time = "2026-04-21T10:46:18.08Z" }, - { url = "https://files.pythonhosted.org/packages/60/6b/c047d6222ab279024a062742d1807e2fbaf27bba88a98637299ff47b9236/pyarrow-24.0.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:bec9373df11544592b0ba7ec2af0e35059e5f0e7647c6183a854dedd193298f1", size = 51911424, upload-time = "2026-04-21T10:46:25.347Z" }, - { url = "https://files.pythonhosted.org/packages/3a/ba/464cc70761c2a525d97ebd84e21c31ebd47f3ef4bdcee117009f51c46f24/pyarrow-24.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:c42ab9439498270139cc63e18847a02afe5c8b3ed9c931266533cfe378bd3591", size = 27251730, upload-time = "2026-04-21T10:46:30.913Z" }, - { url = "https://files.pythonhosted.org/packages/62/c9/a47ab7ece0d86cbe6678418a0fbd1ac4bb493b9184a3891dfa0e7f287ae0/pyarrow-24.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:b0e131f880cda8d04e076cee175a46fc0e8bc8b65c99c6c09dff6669335fde74", size = 35068898, upload-time = "2026-04-21T10:46:36.599Z" }, - { url = "https://files.pythonhosted.org/packages/d1/bc/8db86617a9a58008acf8913d6fed68ea2a46acb6de928db28d724c891a68/pyarrow-24.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:1b2fe7f9a5566401a0ef2571f197eb92358925c1f0c8dba305d6e43ea0871bb3", size = 36679915, upload-time = "2026-04-21T10:46:42.602Z" }, - { url = "https://files.pythonhosted.org/packages/eb/8e/fb178720400ef69db251eb4a9c3ccf4af269bc1feb5055529b8fc87170d1/pyarrow-24.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:0b3537c00fb8d384f15ac1e79b6eb6db04a16514c8c1d22e59a9b95c8ba42868", size = 45697931, upload-time = "2026-04-21T10:46:48.403Z" }, - { url = "https://files.pythonhosted.org/packages/f3/27/99c42abe8e21b44f4917f62631f3aa31404882a2c41d8a4cd5c110e13d52/pyarrow-24.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:14e31a3c9e35f1ab6356c6378f6f72830e6d2d5f1791df3774a7b097d18a6a1e", size = 48837449, upload-time = "2026-04-21T10:46:55.329Z" }, - { url = "https://files.pythonhosted.org/packages/36/b6/333749e2666e9032891125bf9c691146e92901bece62030ac1430e2e7c88/pyarrow-24.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b7d9a514e73bc42711e6a35aaccf3587c520024fe0a25d830a1a8a27c15f4f57", size = 49395949, upload-time = "2026-04-21T10:47:01.869Z" }, - { url = "https://files.pythonhosted.org/packages/17/25/c5201706a2dd374e8ba6ee3fd7a8c89fb7ffc16eed5217a91fd2bd7f7626/pyarrow-24.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b196eb3f931862af3fa84c2a253514d859c08e0d8fe020e07be12e75a5a9780c", size = 51912986, upload-time = "2026-04-21T10:47:09.872Z" }, - { url = "https://files.pythonhosted.org/packages/f8/d2/4d1bbba65320b21a49678d6fbdc6ff7c649251359fdcfc03568c4136231d/pyarrow-24.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:35405aecb474e683fb36af650618fd5340ee5471fc65a21b36076a18bbc6c981", size = 27255371, upload-time = "2026-04-21T10:47:15.943Z" }, - { url = "https://files.pythonhosted.org/packages/b4/a9/9686d9f07837f91f775e8932659192e02c74f9d8920524b480b85212cc68/pyarrow-24.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:6233c9ed9ab9d1db47de57d9753256d9dcffbf42db341576099f0fd9f6bf4810", size = 34981559, upload-time = "2026-04-21T10:47:22.17Z" }, - { url = "https://files.pythonhosted.org/packages/80/b6/0ddf0e9b6ead3474ab087ae598c76b031fc45532bf6a63f3a553440fb258/pyarrow-24.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:f7616236ec1bc2b15bfdec22a71ab38851c86f8f05ff64f379e1278cf20c634a", size = 36663654, upload-time = "2026-04-21T10:47:28.315Z" }, - { url = "https://files.pythonhosted.org/packages/7c/3b/926382efe8ce27ba729071d3566ade6dfb86bdf112f366000196b2f5780a/pyarrow-24.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:1617043b99bd33e5318ae18eb2919af09c71322ef1ca46566cdafc6e6712fb66", size = 45679394, upload-time = "2026-04-21T10:47:34.821Z" }, - { url = "https://files.pythonhosted.org/packages/b3/7a/829f7d9dfd37c207206081d6dad474d81dde29952401f07f2ba507814818/pyarrow-24.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6165461f55ef6314f026de6638d661188e3455d3ec49834556a0ebbdbace18bb", size = 48863122, upload-time = "2026-04-21T10:47:42.056Z" }, - { url = "https://files.pythonhosted.org/packages/5f/e8/f88ce625fe8babaae64e8db2d417c7653adb3019b08aae85c5ed787dc816/pyarrow-24.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b13dedfe76a0ad2d1d859b0811b53827a4e9d93a0bcb05cf59333ab4980cc7e", size = 49376032, upload-time = "2026-04-21T10:47:48.967Z" }, - { url = "https://files.pythonhosted.org/packages/36/7a/82c363caa145fff88fb475da50d3bf52bb024f61917be5424c3392eaf878/pyarrow-24.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:25ea65d868eb04015cd18e6df2fbe98f07e5bda2abefabcb88fce39a947716f6", size = 51929490, upload-time = "2026-04-21T10:47:55.981Z" }, - { url = "https://files.pythonhosted.org/packages/66/1c/e3e72c8014ad2743ca64a701652c733cc5cbcee15c0463a32a8c55518d9e/pyarrow-24.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:295f0a7f2e242dabd513737cf076007dc5b2d59237e3eca37b05c0c6446f3826", size = 27355660, upload-time = "2026-04-21T10:48:01.718Z" }, - { url = "https://files.pythonhosted.org/packages/6f/d3/a1abf004482026ddc17f4503db227787fa3cfe41ec5091ff20e4fea55e57/pyarrow-24.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:02b001b3ed4723caa44f6cd1af2d5c86aa2cf9971dacc2ffa55b21237713dfba", size = 34976759, upload-time = "2026-04-21T10:48:07.258Z" }, - { url = "https://files.pythonhosted.org/packages/4f/4a/34f0a36d28a2dd32225301b79daad44e243dc1a2bb77d43b60749be255c4/pyarrow-24.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:04920d6a71aabd08a0417709efce97d45ea8e6fb733d9ca9ecffb13c67839f68", size = 36658471, upload-time = "2026-04-21T10:48:13.347Z" }, - { url = "https://files.pythonhosted.org/packages/1f/78/543b94712ae8bb1a6023bcc1acf1a740fbff8286747c289cd9468fced2a5/pyarrow-24.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a964266397740257f16f7bb2e4f08a0c81454004beab8ff59dd531b73610e9f2", size = 45675981, upload-time = "2026-04-21T10:48:20.201Z" }, - { url = "https://files.pythonhosted.org/packages/84/9f/8fb7c222b100d314137fa40ec050de56cd8c6d957d1cfff685ce72f15b17/pyarrow-24.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:6f066b179d68c413374294bc1735f68475457c933258df594443bb9d88ddc2a0", size = 48859172, upload-time = "2026-04-21T10:48:27.541Z" }, - { url = "https://files.pythonhosted.org/packages/a7/d3/1ea72538e6c8b3b475ed78d1049a2c518e655761ea50fe1171fc855fcab7/pyarrow-24.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1183baeb14c5f587b1ec52831e665718ce632caab84b7cd6b85fd44f96114495", size = 49385733, upload-time = "2026-04-21T10:48:34.7Z" }, - { url = "https://files.pythonhosted.org/packages/c3/be/c3d8b06a1ba35f2260f8e1f771abbee7d5e345c0937aab90675706b1690a/pyarrow-24.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:806f24b4085453c197a5078218d1ee08783ebbba271badd153d1ae22a3ee804f", size = 51934335, upload-time = "2026-04-21T10:48:42.099Z" }, - { url = "https://files.pythonhosted.org/packages/9c/62/89e07a1e7329d2cde3e3c6994ba0839a24977a2beda8be6005ea3d860b99/pyarrow-24.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:e4505fc6583f7b05ab854934896bcac8253b04ac1171a77dfb73efef92076d91", size = 27271748, upload-time = "2026-04-21T10:49:42.532Z" }, - { url = "https://files.pythonhosted.org/packages/17/1a/cff3a59f80b5b1658549d46611b67163f65e0664431c076ad728bf9d5af4/pyarrow-24.0.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:1a4e45017efbf115032e4475ee876d525e0e36c742214fbe405332480ecd6275", size = 35238554, upload-time = "2026-04-21T10:48:48.526Z" }, - { url = "https://files.pythonhosted.org/packages/a8/99/cce0f42a327bfef2c420fb6078a3eb834826e5d6697bf3009fe11d2ad051/pyarrow-24.0.0-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:7986f1fa71cee060ad00758bcc79d3a93bab8559bf978fab9e53472a2e25a17b", size = 36782301, upload-time = "2026-04-21T10:48:55.181Z" }, - { url = "https://files.pythonhosted.org/packages/2a/66/8e560d5ff6793ca29aca213c53eec0dd482dd46cb93b2819e5aab52e4252/pyarrow-24.0.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:d3e0b61e8efb24ed38898e5cdc5fffa9124be480008d401a1f8071500494ae42", size = 45721929, upload-time = "2026-04-21T10:49:03.676Z" }, - { url = "https://files.pythonhosted.org/packages/27/0c/a26e25505d030716e078d9f16eb74973cbf0b33b672884e9f9da1c83b871/pyarrow-24.0.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:55a3bc1e3df3b5567b7d27ef551b2283f0c68a5e86f1cd56abc569da4f31335b", size = 48825365, upload-time = "2026-04-21T10:49:11.714Z" }, - { url = "https://files.pythonhosted.org/packages/5f/eb/771f9ecb0c65e73fe9dccdd1717901b9594f08c4515d000c7c62df573811/pyarrow-24.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:641f795b361874ac9da5294f8f443dfdbee355cf2bd9e3b8d97aaac2306b9b37", size = 49451819, upload-time = "2026-04-21T10:49:21.474Z" }, - { url = "https://files.pythonhosted.org/packages/48/da/61ae89a88732f5a785646f3ec6125dbb640fa98a540eb2b9889caa561403/pyarrow-24.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8adc8e6ce5fccf5dc707046ae4914fd537def529709cc0d285d37a7f9cd442ca", size = 51909252, upload-time = "2026-04-21T10:49:31.164Z" }, - { url = "https://files.pythonhosted.org/packages/cb/1a/8dd5cafab7b66573fa91c03d06d213356ad4edd71813aa75e08ce2b3a844/pyarrow-24.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:9b18371ad2f44044b81a8d23bc2d8a9b6a6226dca775e8e16cfee640473d6c5d", size = 27388127, upload-time = "2026-04-21T10:49:37.334Z" }, - { url = "https://files.pythonhosted.org/packages/ad/80/d022a34ff05d2cbedd8ccf841fc1f532ecfa9eb5ed1711b56d0e0ea71fc9/pyarrow-24.0.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:1cc9057f0319e26333b357e17f3c2c022f1a83739b48a88b25bfd5fa2dc18838", size = 35007997, upload-time = "2026-04-21T10:49:48.796Z" }, - { url = "https://files.pythonhosted.org/packages/1a/ff/f01485fda6f4e5d441afb8dd5e7681e4db18826c1e271852f5d3957d6a80/pyarrow-24.0.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:e6f1278ee4785b6db21229374a1c9e54ec7c549de5d1efc9630b6207de7e170b", size = 36678720, upload-time = "2026-04-21T10:49:55.858Z" }, - { url = "https://files.pythonhosted.org/packages/9e/c2/2d2d5fea814237923f71b36495211f20b43a1576f9a4d6da7e751a64ec6f/pyarrow-24.0.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:adbbedc55506cbdabb830890444fb856bfb0060c46c6f8026c6c2f2cf86ae795", size = 45741852, upload-time = "2026-04-21T10:50:04.624Z" }, - { url = "https://files.pythonhosted.org/packages/8e/3a/28ba9c1c1ebdbb5f1b94dfebb46f207e52e6a554b7fe4132540fde29a3a0/pyarrow-24.0.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:ae8a1145af31d903fa9bb166824d7abe9b4681a000b0159c9fb99c11bc11ad26", size = 48889852, upload-time = "2026-04-21T10:50:12.293Z" }, - { url = "https://files.pythonhosted.org/packages/df/51/4a389acfd31dca009f8fb82d7f510bb4130f2b3a8e18cf00194d0687d8ac/pyarrow-24.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d7027eba1df3b2069e2e8d80f644fa0918b68c46432af3d088ddd390d063ecde", size = 49445207, upload-time = "2026-04-21T10:50:20.677Z" }, - { url = "https://files.pythonhosted.org/packages/19/4b/0bab2b23d2ae901b1b9a03c0efd4b2d070256f8ce3fc43f6e58c167b2081/pyarrow-24.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e56a1ffe9bf7b727432b89104cc0849c21582949dd7bdcb34f17b2001a351a76", size = 51954117, upload-time = "2026-04-21T10:50:29.14Z" }, - { url = "https://files.pythonhosted.org/packages/29/88/f4e9145da0417b3d2c12035a8492b35ff4a3dbc653e614fcfb51d9dedb38/pyarrow-24.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:38be1808cdd068605b787e6ca9119b27eb275a0234e50212c3492331680c3b1e", size = 28001155, upload-time = "2026-04-21T10:51:22.337Z" }, - { url = "https://files.pythonhosted.org/packages/79/4f/46a49a63f43526da895b1a45bbb51d5baf8e4d77159f8528fc3e5490007f/pyarrow-24.0.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:418e48ce50a45a6a6c73c454677203a9c75c966cb1e92ca3370959185f197a05", size = 35250387, upload-time = "2026-04-21T10:50:35.552Z" }, - { url = "https://files.pythonhosted.org/packages/a0/da/d5e0cd5ef00796922404806d5f00325cdadc3441ce2c13fe7115f2df9a64/pyarrow-24.0.0-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:2f16197705a230a78270cdd4ea8a1d57e86b2fdcbc34a1f6aebc72e65c986f9a", size = 36797102, upload-time = "2026-04-21T10:50:42.417Z" }, - { url = "https://files.pythonhosted.org/packages/34/c7/5904145b0a593a05236c882933d439b5720f0a145381179063722fbfc123/pyarrow-24.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:fb24ac194bfc5e86839d7dcd52092ee31e5fe6733fe11f5e3b06ef0812b20072", size = 45745118, upload-time = "2026-04-21T10:50:49.324Z" }, - { url = "https://files.pythonhosted.org/packages/13/d3/cca42fe166d1c6e4d5b80e530b7949104d10e17508a90ae202dac205ce2a/pyarrow-24.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:9700ebd9a51f5895ce75ff4ac4b3c47a7d4b42bc618be8e713e5d56bacf5f931", size = 48844765, upload-time = "2026-04-21T10:50:55.579Z" }, - { url = "https://files.pythonhosted.org/packages/b0/49/942c3b79878ba928324d1e17c274ed84581db8c0a749b24bcf4cbdf15bd3/pyarrow-24.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d8ddd2768da81d3ee08cfea9b597f4abb4e8e1dc8ae7e204b608d23a0d3ab699", size = 49471890, upload-time = "2026-04-21T10:51:02.439Z" }, - { url = "https://files.pythonhosted.org/packages/76/97/ff71431000a75d84135a1ace5ca4ba11726a231a8007bbb320a4c54075d5/pyarrow-24.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:61a3d7eaa97a14768b542f3d284dc6400dd2470d9f080708b13cd46b6ae18136", size = 51932250, upload-time = "2026-04-21T10:51:10.576Z" }, - { url = "https://files.pythonhosted.org/packages/51/be/6f79d55816d5c22557cf27533543d5d70dfe692adfbee4b99f2760674f38/pyarrow-24.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:c91d00057f23b8d353039520dc3a6c09d8608164c692e9f59a175a42b2ae0c19", size = 28131282, upload-time = "2026-04-21T10:51:16.815Z" }, + { url = "https://files.pythonhosted.org/packages/fd/aa/459f3f5adebf6427a8bf1e976168f55793a3732ec1c6c6fe9e05a060b63b/pyarrow-26.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:9a62748f6b1f9f438706f0307acbb26e6a15010ea58f202c9d2725bc6eac0871", size = 37327168, upload-time = "2026-11-03T09:54:01.046Z" }, + { url = "https://files.pythonhosted.org/packages/5f/ed/29218597cb38aa9058dffda7906749df9e9da02b4c4da4e88dd8bcfa85eb/pyarrow-26.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:0187cbe6558cb158e148dd7b779f59cab6104163d148d808d04f293dc897b7ec", size = 39778863, upload-time = "2026-11-03T09:57:58.046Z" }, + { url = "https://files.pythonhosted.org/packages/03/f9/44489f525c73cc469f23fd02c0a3009882a8dcf45d0d9fb6ca1bb84a53e2/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:22a96a225de107eb9acd1ad9a818198ca832df2a4c0952412f754a7ed2105a98", size = 51836882, upload-time = "2026-11-03T10:48:50.544Z" }, + { url = "https://files.pythonhosted.org/packages/e6/87/6bf528898ef82dc3e8d762cbec7b42ae127a543895cc78c5df26a1f497f5/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:39cb0f2418282c24bea6ceda77b03e5a8f0a5766b63a8bf194d4e2a2c423548c", size = 55016622, upload-time = "2026-11-03T10:48:58.916Z" }, + { url = "https://files.pythonhosted.org/packages/97/e8/3b4898693744efb5aa60a859774ee3874a2635b288f309f1afb78a698f38/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:24350194bc83f1fde74aa321b6b43cd78bfdbfe613a795a6b9145fd4beaf4827", size = 55452257, upload-time = "2026-11-03T10:49:05.872Z" }, + { url = "https://files.pythonhosted.org/packages/86/96/bbeb5152a27406c65b80b72ecba4451fea18d549a5aea1fbb2c097d86b08/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ed1e19bfaf79565b74e3b0a45a0ba6d05620e68d5a5b48a8193c2bbee7cf5484", size = 58605344, upload-time = "2026-11-03T10:49:14.145Z" }, + { url = "https://files.pythonhosted.org/packages/bf/aa/afb7321eaed5f65332aa691fcd892bf67d0289e2ba884c8ce592d3188a26/pyarrow-26.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:5f681458e4fb81aefef50d3a8a432fe92f8480a87693616f9d95e95ceac8844c", size = 29034160, upload-time = "2026-11-03T10:49:19.45Z" }, + { url = "https://files.pythonhosted.org/packages/61/81/dc5814d61f8c956363e81bcaba61b4712a5d227324d40c766b3858160711/pyarrow-26.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:217497a51fd41abb74502ba2f4900872e0944c226945c02ee8a1cb4f81df3392", size = 37290209, upload-time = "2026-11-03T10:49:25.185Z" }, + { url = "https://files.pythonhosted.org/packages/f7/c8/dcc42b1cceb69ff032fa16430bd82c086b933e35ef05ab521e56313b76be/pyarrow-26.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:a2c5e9cec45b318917b630dc040cf197aef624d94866ab2c8e709708057123d2", size = 39757493, upload-time = "2026-11-03T10:49:30.886Z" }, + { url = "https://files.pythonhosted.org/packages/ab/7e/da9831bfcaaa908ae6d5d049c04c2233a5a7e216d6b961e22861056ef3fd/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6c18167774fb599d42444b7ac558a893d49e750fb14232b538955e6f0d1d51ea", size = 51818506, upload-time = "2026-11-03T10:49:37.89Z" }, + { url = "https://files.pythonhosted.org/packages/d3/79/e2fc9b1317b7a21e7bcd57eb035cac3fe72f47af3efe2ec3b4dea9a08a04/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c718bf97a92a6dea97fd1062c3b9f9e2e83cb9cc926e752289fa4ffff41738f9", size = 55043763, upload-time = "2026-11-03T10:49:45.732Z" }, + { url = "https://files.pythonhosted.org/packages/e3/66/dbe72f5fa21a92b645d56410bacac605defe63e5d3e9794b2fd8c7d77030/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:40aea57ab8bd3cf35a11e604cd7d0c7436dc90d1ce9b88b6711ef2f1a232968e", size = 55438656, upload-time = "2026-11-03T10:49:53.74Z" }, + { url = "https://files.pythonhosted.org/packages/d1/b1/c91322fc4c1800c1f7dd78f911b1dd74187acaeb246d86478a0f064f6af5/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:73534fbda7f73cab0791b569b93112d4c9e1546cedd0f309d1f69889beb6a08f", size = 58625736, upload-time = "2026-11-03T10:50:01.442Z" }, + { url = "https://files.pythonhosted.org/packages/30/61/d94decccacb4dd40a4ebeed0ff3b2cea8f0b680f50184ea7eb0264db779b/pyarrow-26.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:9379f0d1056cad6866c4697aec83a15830202ec7e0bd52f8bd508b316260fa61", size = 29078866, upload-time = "2026-11-03T10:50:06.854Z" }, + { url = "https://files.pythonhosted.org/packages/15/b8/c31c51fbe7df901817d88c73eeec25079d0da5f7c7b67fc0bf071f6a2df5/pyarrow-26.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:4cb739ccb87292c673e1f69819b68432a73bb8bb456e8599641bba9183a8a1dd", size = 37292947, upload-time = "2026-11-03T10:50:12.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/63/0c2559ae33ce59d2ca5ce74117676f8ff8da4cf102729a158ea46415eb50/pyarrow-26.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:50b40aea92f43b2b6da3427548a5337741b4b93b92e8015a8a3eefc0e75acca2", size = 39767535, upload-time = "2026-11-03T10:50:18.254Z" }, + { url = "https://files.pythonhosted.org/packages/31/02/d9462d1ae4e54c3964af38316a802b29c28970b7d375722ef190af736640/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a3a79661404ba3d41b7c9a45cb56113246a244b38cb1393fadae289bc66b91b4", size = 51815955, upload-time = "2026-11-03T10:50:25.332Z" }, + { url = "https://files.pythonhosted.org/packages/96/54/33c2df56948d88a4d83a52999a4a81a4871b2de481ff25ccd6f5ccd2589a/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:f71221bbc7707e3fad920d0478db9350791d4714ec445299ee0d56559fbc156c", size = 55038406, upload-time = "2026-11-03T10:50:32.551Z" }, + { url = "https://files.pythonhosted.org/packages/99/57/8e1f886ee96c7edab89ab6f15fbb00c85c2bb2173f3cb504925731d00564/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8ccfb9958bcd09f34678c64fb42a0e270b47cd092ae79578da51e0d7bb144296", size = 55437362, upload-time = "2026-11-03T10:50:39.89Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c3/d87939a5f6cd30bb406bad6c20926fcedafc52ec5629f6eb27e4cd5db709/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:029e881af986375a2731da79c999fe734a72547fabb16503d65fc079d4bc7eb2", size = 58618865, upload-time = "2026-11-03T10:50:48.029Z" }, + { url = "https://files.pythonhosted.org/packages/c1/9e/b6c8afec2ffc06bbd00a88326826f9d66e4bbca752c0837ee8e2dbf2238f/pyarrow-26.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:8196f36a2f4cb8d2d6ef3651941b80e5ccf125d7653657d99af5bb298e7a7026", size = 28989592, upload-time = "2026-11-03T10:50:53.384Z" }, + { url = "https://files.pythonhosted.org/packages/de/48/999f6e30323e2e95a4439180b62f6308023970e4a37d31497080ea2a1a78/pyarrow-26.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:15435b595c14583f6ac8495c3ef89ac3fed6bc94f168467bfd3b6ba53ad3a643", size = 37334639, upload-time = "2026-11-03T10:50:59.462Z" }, + { url = "https://files.pythonhosted.org/packages/7f/3a/4458972c69ead95af5d3b701c80885133c351075895382499df49ed92d36/pyarrow-26.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:a44a244867cac106cd326dd0a04be0850d2b8af3b1418ed7aeb8146d13aba360", size = 39802150, upload-time = "2026-11-03T10:51:05.743Z" }, + { url = "https://files.pythonhosted.org/packages/86/d0/fa4bc5d66f78cbc4ec8482b210c2fc3b8cb59564efe171f3ca9be416f8ee/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0044cb9303c3ae082cc52a2493312109c955bcfa84e87be768736f7d6d8f6257", size = 51880097, upload-time = "2026-11-03T10:51:12.75Z" }, + { url = "https://files.pythonhosted.org/packages/f3/57/755a1b54d37c2a9e2c283d8bc648a50aa4ce57f977ce6a4b1d65eba29f51/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:7ae48ab53610b85e004b03bccff593fbdf22186d0ab48ed42c90797915dac814", size = 55063542, upload-time = "2026-11-03T10:51:20.417Z" }, + { url = "https://files.pythonhosted.org/packages/45/ba/7cd1d78c2ef5a36b1f8d137d1790179875639f197ed90702268084a2470a/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a97df0c52c966ae8970ac0899ae75d81083c5400eca267de2608ca0f13e6e118", size = 55490507, upload-time = "2026-11-03T10:51:28.295Z" }, + { url = "https://files.pythonhosted.org/packages/9f/02/39e18c5381ad908d7161cc16a02dce03b3db236d3c3ac99fc020878287fb/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5f665e73790222779613ae3d23d2a1d72f0f13a4646862277e9784bb46e14fca", size = 58648328, upload-time = "2026-11-03T10:51:36.303Z" }, + { url = "https://files.pythonhosted.org/packages/1c/18/2cd453cc2e282d465e9c9b60834d6ca17601dc08e2d402751cb40af92356/pyarrow-26.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:492dc499097968e51cac46e03e0054c68dd3c5f39d75098343f5ad05ec79f7df", size = 29757743, upload-time = "2026-11-03T10:52:35.061Z" }, + { url = "https://files.pythonhosted.org/packages/db/46/b97f117adb46f93620aa94bf13747a81ccc5e099be534cc195c94b281ba7/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ec196b35270263eda71fc3f43bd31a89b778c6787f19872df5abb9d4264057ff", size = 37452099, upload-time = "2026-11-03T10:51:42.419Z" }, + { url = "https://files.pythonhosted.org/packages/a6/40/ac1796654fc8591049d200f6bcd646a2319509010784f47c1cf6b09d1000/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:8af2b4e004dc18da8dc77bce27d97c675d2f71348e3ade2741cecac85c3f0c21", size = 39888805, upload-time = "2026-11-03T10:51:48.766Z" }, + { url = "https://files.pythonhosted.org/packages/6c/93/bcff79148416896738a707992570c4ae8e3bb087bc9e0dca8df7dbf6e983/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:c2bf4444a7e86f109dc03e28b2c98eb6671e2eb95e6057c25043d25684e337e9", size = 51884587, upload-time = "2026-11-03T10:51:56.701Z" }, + { url = "https://files.pythonhosted.org/packages/fa/62/cb05e81d31cd1dc97c2e16151425e61fe3a19274ccd1254cafab3a173f96/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:b121de63e2f92704b6b9881fbe69cb3eeca786ea882379b59ce80b8012c1bd8c", size = 55018252, upload-time = "2026-11-03T10:52:05.813Z" }, + { url = "https://files.pythonhosted.org/packages/f8/f5/e8dbbb803bb28a32411491d502679e272c569af7f590816327e84725c748/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:40b9c1a5841559030ba8d1b8c15d6160bccb702ff2596b4ce296e1efd7665781", size = 55522075, upload-time = "2026-11-03T10:52:14.577Z" }, + { url = "https://files.pythonhosted.org/packages/9b/7a/5000d6082b116359d3db3ee6073a8f708f41cb4bb7d6414f94cd40a90fe7/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9519f70bd847f7628a2d16324d1ea8827e2ec1da347ee0bf96cc7c248195e923", size = 58625604, upload-time = "2026-11-03T10:52:23.045Z" }, + { url = "https://files.pythonhosted.org/packages/41/70/74a5a07eeee1a84cd51e81813b7fd2d5ffc90192a95981a51e97a8ced99e/pyarrow-26.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:6d9b558e1bce3270f1f422c61fd682615cfb34ffd320a51e765e868e8c155a72", size = 29925653, upload-time = "2026-11-03T10:52:29.188Z" }, + { url = "https://files.pythonhosted.org/packages/77/09/4e9461479930e3f4367cc0b4f4356d4444a23be9cb350272b159cd0c7fa9/pyarrow-26.0.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:2c118754a0abe0bf20ef17432f95534ebb0ded37a48b6e8690cdd02625a86d97", size = 37329458, upload-time = "2026-11-03T10:52:41.622Z" }, + { url = "https://files.pythonhosted.org/packages/40/5a/9e44840924b0939defacc2561e54dc9aba10eff1fc5dadcf41921202d99f/pyarrow-26.0.1-cp315-cp315-macosx_12_0_x86_64.whl", hash = "sha256:99574d8eabad06cc4bb3fed327b298c8a44a3596abd2d575738fa019df7ac59e", size = 39799948, upload-time = "2026-11-03T10:52:47.507Z" }, + { url = "https://files.pythonhosted.org/packages/70/3a/5fe40369653a082d86fdb6ce2b7c40a4ef435d90a68da60c05dda0c554fc/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:12c5edbdf9b8a0f121a0a222be150c3a711149bc4322736d6a04693fbfd8c723", size = 51875337, upload-time = "2026-11-03T10:52:54.59Z" }, + { url = "https://files.pythonhosted.org/packages/5e/87/f768a458cf975c17c73912fb25a1e0693ceef8d76d78cf83ffdf1f63ec70/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:8cb5bcfe627ee6b910fbec27871d38cf4f28f331ea6328902ce6a6272851ac70", size = 55060370, upload-time = "2026-11-03T10:53:02.19Z" }, + { url = "https://files.pythonhosted.org/packages/e0/30/280c24a7da9085b782cd6960ccae6763b0170f51385b9122385c12226ff2/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e2ee5f01f84996109405759cba8bb92a16455c50deb6526a535ab3b8d5f4e326", size = 55488705, upload-time = "2026-11-03T10:53:09.8Z" }, + { url = "https://files.pythonhosted.org/packages/42/e7/8e7b7f7bd58c88fd8da93db0d0869c69175c3ddccf365afbcc13fbd691da/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e25d4a886868c5ce136d194f308bd690e1335aebf6b8bcae3511b0becdb3a65a", size = 58646822, upload-time = "2026-11-03T10:53:17.902Z" }, + { url = "https://files.pythonhosted.org/packages/3b/c7/6094fa2c0b5602d81b1177ac7f5b2de8a386862d08e57a75931da774f3e0/pyarrow-26.0.1-cp315-cp315-win_amd64.whl", hash = "sha256:6cdad5f67a30bbcea54c3c2a27ea45bd5a170377bf45f80f4d7e3a726e8e3283", size = 29755706, upload-time = "2026-11-03T10:54:14.582Z" }, + { url = "https://files.pythonhosted.org/packages/41/0f/86747650c8218bcea7443884e7c8ba9d3fe9a13fb5a4be99acdd5c2b9144/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:12dc85cec96aa62d429d7c43749c072e9330c373b67d6ee458edeef444c8941f", size = 37445268, upload-time = "2026-11-03T10:53:25.531Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ec/4159b2362267009b754a7c2f138f16bdfd6623b308005678eb7cf1b65863/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_x86_64.whl", hash = "sha256:52e4daba8f1b4316b7b9ba7e84903a339cbc52998ebddc9a7c78b5ea37c23bbb", size = 39877540, upload-time = "2026-11-03T10:53:33.046Z" }, + { url = "https://files.pythonhosted.org/packages/a8/0e/df0501e93eef78402f94f33f948aba996181b3d3c54f97a3f16544916d05/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_aarch64.whl", hash = "sha256:322f6fc80c6db1ec87c9d905df3ce259cd22e922f47fbad3c58d0dd6f63bc7a9", size = 51874165, upload-time = "2026-11-03T10:53:41.281Z" }, + { url = "https://files.pythonhosted.org/packages/fb/30/0d43bf6a49fca51142a96c73d693ec34d229c902a46e007c25f3b9798b52/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_x86_64.whl", hash = "sha256:68b91f34e3424d55564e9d4d4f7491aaebd6db3998039cc33ba795a63167f04e", size = 55012741, upload-time = "2026-11-03T10:53:49.153Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ff/0e6cd73832d97c3852284eda9bee2428c53a92bcf6f6aa4bda1e15314a59/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b801300d65859adaf611c9c0a4cb39bd3cb1713b60b974ad20650a8a0f8af2fd", size = 55512474, upload-time = "2026-11-03T10:53:56.512Z" }, + { url = "https://files.pythonhosted.org/packages/f0/1e/43cdcf9719169f0228b3e516e5004ed0acfc3a4c70ce35e3f2a80a485baf/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:2623b6c20637c0e2c40be96bda3d127dde49d6e6734ad6e71df91a013e40a3c4", size = 58616300, upload-time = "2026-11-03T10:54:04.472Z" }, + { url = "https://files.pythonhosted.org/packages/df/bf/8e29b47c61fc961e92e96db129d5dc7b716c2091dfe05359e70f20d712b9/pyarrow-26.0.1-cp315-cp315t-win_amd64.whl", hash = "sha256:55b1d871f21c8ed249c93f7375a35c35aa9b7b3af6896405cb8a6b67ad9bc7f9", size = 29909417, upload-time = "2026-11-03T10:54:09.613Z" }, ] [[package]] @@ -3972,20 +3531,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/9d/56/921726b776ace8d8f5db44c4ef961006580d91dc52b803c489fafd1aa249/pydantic_core-2.46.4.tar.gz", hash = "sha256:62f875393d7f270851f20523dd2e29f082bcc82292d66db2b64ea71f64b6e1c1", size = 471464, upload-time = "2026-05-06T13:37:06.98Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/08/f1ba952f1c8ae5581c70fa9c6da89f247b83e3dd8c09c035d5d7931fc23d/pydantic_core-2.46.4-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:a396dcc17e5a0b164dbe026896245a4fa9ff402edca1dff0be3d53a517f74de4", size = 2113146, upload-time = "2026-05-06T13:37:36.537Z" }, - { url = "https://files.pythonhosted.org/packages/56/c6/65f646c7ff09bd257f660434adb45c4dfcbbcebcc030562fecf6f5bf887d/pydantic_core-2.46.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:da4b951fe36dc7c3a1ccb4e3cd1747c3542b8c9ceede8fc86cae054e764485f5", size = 1949769, upload-time = "2026-05-06T13:37:46.365Z" }, - { url = "https://files.pythonhosted.org/packages/64/ba/bfb1d928fd5b49e1258935ff104ae356e9fd89384a55bf9f847e9193ad40/pydantic_core-2.46.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bb63e0198ca18aad131c089b9204c23079c3afa95487e561f4c522d519e55aba", size = 1974958, upload-time = "2026-05-06T13:37:28.611Z" }, - { url = "https://files.pythonhosted.org/packages/4e/74/76223bfb117b64af743c9b6670d1364516f5c0604f96b48f3272f6af6cc6/pydantic_core-2.46.4-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f47286a97f0bc9b8859519809077b91b2cefe4ae47fcbf5e466a009c1c5d742b", size = 2042118, upload-time = "2026-05-06T13:36:55.216Z" }, - { url = "https://files.pythonhosted.org/packages/cb/7b/848732968bc8f48f3187542f08358b9d842db564147b256669426ebb1652/pydantic_core-2.46.4-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:905a0ed8ea6f2d61c1738835f99b699348d7857379083e5fc497fa0c967a407c", size = 2222876, upload-time = "2026-05-06T13:38:25.455Z" }, - { url = "https://files.pythonhosted.org/packages/b5/2f/e90b63ee2e14bd8d3db8f705a6d75d64e6ee1b7c2c8833747ce706e1e0ce/pydantic_core-2.46.4-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ea793e075b70290d89d8142074262885d3f7da19634845135751bd6344f73b50", size = 2286703, upload-time = "2026-05-06T13:37:53.304Z" }, - { url = "https://files.pythonhosted.org/packages/ba/1e/acc4d70f88a0a277e4a1fa77ebb985ceabaf900430f875bf9338e11c9420/pydantic_core-2.46.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:395aebd9183f9d112f569aeb5b2214d1a10a33bec8456447f7fbdfa51d38d4cd", size = 2092042, upload-time = "2026-05-06T13:38:46.981Z" }, - { url = "https://files.pythonhosted.org/packages/a9/da/0a422b57bf8504102bf3c4ccea9c41bab5a5cee6a54650acf8faf67f5a24/pydantic_core-2.46.4-cp310-cp310-manylinux_2_31_riscv64.whl", hash = "sha256:b078afbc25f3a1436c7a1d2cd3e322497ee99615ba97c563566fdf46aff1ee01", size = 2117231, upload-time = "2026-05-06T13:39:23.146Z" }, - { url = "https://files.pythonhosted.org/packages/bd/2a/2ac13c3af305843e23c5078c53d135656b3f05a2fd78cb7bbbb12e97b473/pydantic_core-2.46.4-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f747929cf940cddb5b3668a390056ddd5ba2e5010615ea2dcf4f9c4f3ab8791d", size = 2168388, upload-time = "2026-05-06T13:40:08.06Z" }, - { url = "https://files.pythonhosted.org/packages/72/04/2beacf7e1607e93eefe4aed1b4709f079b905fb77530179d4f7c71745f22/pydantic_core-2.46.4-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:daa27d92c36f24388fe3ad306b174781c747627f134452e4f128ea00ce1fe8c4", size = 2184769, upload-time = "2026-05-06T13:38:13.901Z" }, - { url = "https://files.pythonhosted.org/packages/9e/29/d2b9fd9f539133548eaf622c06a4ce176cb46ac59f32d0359c4abc0de047/pydantic_core-2.46.4-cp310-cp310-musllinux_1_1_armv7l.whl", hash = "sha256:19e51f073cd3df251856a8a4189fbdf1de4012c3ebacfb1884f94f1eb406079f", size = 2319312, upload-time = "2026-05-06T13:39:08.24Z" }, - { url = "https://files.pythonhosted.org/packages/7c/af/0f7a5b85fec6075bea96e3ef9187de38fccced0de92c1e7feda8d5cc7bb9/pydantic_core-2.46.4-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:c1747f85cee84c26985853c6f3d9bd3e75da5212912443fa111c113b9c246f39", size = 2361817, upload-time = "2026-05-06T13:38:43.2Z" }, - { url = "https://files.pythonhosted.org/packages/25/a4/73363fec545fd3ec025490bdda2743c56d0dd5b6266b1a53bbe9e4265375/pydantic_core-2.46.4-cp310-cp310-win32.whl", hash = "sha256:2f84c03c8607173d16b5a854ec68a2f9079ae03237a54fb506d13af47e1d018d", size = 1987085, upload-time = "2026-05-06T13:39:25.497Z" }, - { url = "https://files.pythonhosted.org/packages/01/aa/62f082da2c91fac1c234bc9ee0066257ce83f0604abd72e4c9d5991f2d84/pydantic_core-2.46.4-cp310-cp310-win_amd64.whl", hash = "sha256:8358a950c8909158e3df31538a7e4edc2d7265a7c54b47f0864d9e5bae9dcebf", size = 2074311, upload-time = "2026-05-06T13:39:59.922Z" }, { url = "https://files.pythonhosted.org/packages/5c/fa/6d7708d2cfc1a832acb6aeb0cd16e801902df8a0f583bb3b4b527fde022e/pydantic_core-2.46.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:0e96592440881c74a213e5ad528e2b24d3d4f940de2766bed9010ab1d9e51594", size = 2111872, upload-time = "2026-05-06T13:40:27.596Z" }, { url = "https://files.pythonhosted.org/packages/ae/6f/aa064a3e74b5745afbdf250594f38e7ead05e2d651bcb35994b9417a0d4d/pydantic_core-2.46.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e0d65b8c354be7fb5f720c3caa8bc940bc2d20ce749c8e06135f07f8ed95dd7c", size = 1948255, upload-time = "2026-05-06T13:39:12.574Z" }, { url = "https://files.pythonhosted.org/packages/43/3a/41114a9f7569b84b4d84e7a018c57c56347dac30c0d4a872946ec4e36c46/pydantic_core-2.46.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7bfb192b3f4b9e8a89b6277b6ce787564f62cfd272055f6e685726b111dc7826", size = 1972827, upload-time = "2026-05-06T13:38:19.841Z" }, @@ -4090,14 +3635,11 @@ wheels = [ [[package]] name = "pyjwt" -version = "2.13.0" +version = "2.15.1" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" } +sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" }, + { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" }, ] [package.optional-dependencies] @@ -4107,54 +3649,20 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b4" +version = "16.0.0b4" source = { registry = "https://pypi.fury.io/lance-format/" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] dependencies = [ - { name = "lance-namespace", marker = "sys_platform == 'darwin'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform == 'darwin'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*' and sys_platform == 'darwin'" }, - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and sys_platform == 'darwin'" }, - { name = "pyarrow", marker = "sys_platform == 'darwin'" }, + { name = "lance-namespace" }, + { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_1Bbzay/pylance-15.0.0b4-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c948ac22105a0bd9f8314edb883edac421a64b059d992ea6d614773cd2fa2e65" }, -] - -[[package]] -name = "pylance" -version = "15.0.0b9" -source = { registry = "https://pypi.fury.io/lance-format/" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", -] -dependencies = [ - { name = "lance-namespace", marker = "sys_platform != 'darwin'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform != 'darwin'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*' and sys_platform != 'darwin'" }, - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and sys_platform != 'darwin'" }, - { name = "pyarrow", marker = "sys_platform != 'darwin'" }, -] -wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_11uz9g/pylance-15.0.0b9-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:749d4da73a22f5d33f6926387109dfaf814413d3bd1c36b974edf81ca040eb04" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Zl1Qd/pylance-15.0.0b9-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c49523c68122f4cb42fd310155af6f420f90559752f0735d1503c06f7f45629" }, - { url = "https://pypi.fury.io/lance-format/-/ver_23GhEu/pylance-15.0.0b9-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:78ff23c91b1b4113bae7715fd143af1fec732cdc0fd2429db6d3149de16d565a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1IKCVE/pylance-15.0.0b9-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ee8f71b7bdf16bb44305f961b6a2cf4a75f47f1db7d217955e2aca0020acdf05" }, - { url = "https://pypi.fury.io/lance-format/-/ver_10hNTp/pylance-15.0.0b9-cp310-abi3-win_amd64.whl", hash = "sha256:28f1f92c8af8072a7fdc6f4eca5a8814a54e457843e2ac7e0f00554da5152d90" }, + { url = "https://pypi.fury.io/lance-format/-/ver_oJPBj/pylance-16.0.0b4-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:495789f4c6376aed8c5ad41fd04a828910120245e7d021cc2f59651f01ec7e45" }, + { url = "https://pypi.fury.io/lance-format/-/ver_bll8w/pylance-16.0.0b4-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7579acd634b3d1513bb836d437d1f13bc4eb76625b0795e65b583007b16f223b" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2d4iLq/pylance-16.0.0b4-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e5cf1c63d612ac36141399ceff30f46be16e537cd4d01562bc0453e8d79f19e8" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1X7cLu/pylance-16.0.0b4-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:b478f6ffef5a4e938e5578a6ec8f5b00866098b253daadd8f704008851d58417" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pZ4HP/pylance-16.0.0b4-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:be9d95a9d22dad0371139faf982297cdd918aded1d59bc3ab4dd27394f55ba79" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1M3BoM/pylance-16.0.0b4-cp310-abi3-win_amd64.whl", hash = "sha256:1f84164d895df4522722cc7f8f10eaa42449c3c997f25476fb07ab48ef3b2969" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1AAGRf/pylance-16.0.0b4-cp310-abi3-win_arm64.whl", hash = "sha256:9423e6f4edef4f4048fab6cde69dd5cf2d2acdfc6dbe6171ce720753136b6b0a" }, ] [[package]] @@ -4202,12 +3710,10 @@ version = "9.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, { name = "pygments" }, - { name = "tomli", marker = "python_full_version < '3.11'" }, ] 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 = [ @@ -4219,7 +3725,6 @@ name = "pytest-asyncio" version = "1.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "backports-asyncio-runner", marker = "python_full_version < '3.11'" }, { name = "pytest" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] @@ -4274,12 +3779,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/89/33/4287ebdcbdcae6f93521be56ffdd5f474b6aebda1a50df4c4b9870a140fa/python_pkcs11-0.9.4.tar.gz", hash = "sha256:3d950aadefa473b880dc75f01539133487e65ec2a97db1e955c4f6bef1bd71d5", size = 180658, upload-time = "2026-04-13T13:32:51.769Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/36/98/6da01b81312c481f743b675577ae64ee1887a7d1c6ca4294b136a189f581/python_pkcs11-0.9.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:fbf1436684a74b2b26cb5f51e970f2505d81bac74ee084641b625d956f08af29", size = 558896, upload-time = "2026-04-13T13:31:51.089Z" }, - { url = "https://files.pythonhosted.org/packages/4a/b3/ffa8d044bf9831c20a7a9e305117cde8512c6ccdf26d5e95a605dc7bc5c6/python_pkcs11-0.9.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c2b1af32dad1457250959d42093e05ebc98f94f62d4c2393d72eef0c73c846c7", size = 1833458, upload-time = "2026-04-13T13:31:52.714Z" }, - { url = "https://files.pythonhosted.org/packages/bc/f7/d73bbfc9cca5a6837b7fce2aebf4a71290bacbcf31709271ff81faa92744/python_pkcs11-0.9.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2ac2f25bc27b618f8f1d17b4d6cd5887e4202ee32edec206052d6f46943f8990", size = 1851767, upload-time = "2026-04-13T13:31:54.673Z" }, - { url = "https://files.pythonhosted.org/packages/5d/b6/08a12c496ec6e49a40afc9aaad526b110a99e778822295778359fc2a1161/python_pkcs11-0.9.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a3edf4ae24def328f454d38dffef1677baec69d376755523d4e56280fc177173", size = 1779639, upload-time = "2026-04-13T13:31:56.744Z" }, - { url = "https://files.pythonhosted.org/packages/bd/78/1792a808dd3aeeb46acfdcd2d28084d22c7648ce7b7cb925fc1c78b07052/python_pkcs11-0.9.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:975389457f533bdbaa96b845e9517ef6c4cdaed627a54515fb77165014399c27", size = 1830315, upload-time = "2026-04-13T13:31:58.715Z" }, - { url = "https://files.pythonhosted.org/packages/9f/ed/80063318f6fc8f775200add5eefb0a2b6dcf6bdc5da89b562c8d5530cb9c/python_pkcs11-0.9.4-cp310-cp310-win_amd64.whl", hash = "sha256:8ed0225ae59ec061575076bf67db4bd2b4b71e1157462fed4c7c10f11bd6709d", size = 284002, upload-time = "2026-04-13T13:32:00.268Z" }, { url = "https://files.pythonhosted.org/packages/00/10/e2f33f3acca84b72d36b7bc66f62f2eac9b12b61268fb1a3c452ca084fcf/python_pkcs11-0.9.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:585bfeaafd12db0875fa74e2c4cbe8b055a75a6c359f873a4777deefbcbb2c6f", size = 557105, upload-time = "2026-04-13T13:32:01.725Z" }, { url = "https://files.pythonhosted.org/packages/db/e6/fd48a495d57f488976b0871f1c08efed1a19722aadea253a49b989c611b1/python_pkcs11-0.9.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b8bff8267d1e5813c591290b02c1c7e700786b94a3ba750fda5f8d44f9fc7191", size = 1916836, upload-time = "2026-04-13T13:32:03.486Z" }, { url = "https://files.pythonhosted.org/packages/bc/d2/a627fdd228c1253e25f9dd4b6facf3499cb7b2d76260bf337b1f84cb1bd2/python_pkcs11-0.9.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54399a5235c427c25f654c89f451648084dbabe0696bf9e685e86c741460857b", size = 1935363, upload-time = "2026-04-13T13:32:05.101Z" }, @@ -4321,15 +3820,6 @@ 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/f4/a0/39350dd17dd6d6c6507025c0e53aef67a9293a6d37d3511f23ea510d5800/pyyaml-6.0.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b", size = 184227, upload-time = "2025-09-25T21:31:46.04Z" }, - { url = "https://files.pythonhosted.org/packages/05/14/52d505b5c59ce73244f59c7a50ecf47093ce4765f116cdb98286a71eeca2/pyyaml-6.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956", size = 174019, upload-time = "2025-09-25T21:31:47.706Z" }, - { url = "https://files.pythonhosted.org/packages/43/f7/0e6a5ae5599c838c696adb4e6330a59f463265bfa1e116cfd1fbb0abaaae/pyyaml-6.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8", size = 740646, upload-time = "2025-09-25T21:31:49.21Z" }, - { url = "https://files.pythonhosted.org/packages/2f/3a/61b9db1d28f00f8fd0ae760459a5c4bf1b941baf714e207b6eb0657d2578/pyyaml-6.0.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198", size = 840793, upload-time = "2025-09-25T21:31:50.735Z" }, - { url = "https://files.pythonhosted.org/packages/7a/1e/7acc4f0e74c4b3d9531e24739e0ab832a5edf40e64fbae1a9c01941cabd7/pyyaml-6.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b", size = 770293, upload-time = "2025-09-25T21:31:51.828Z" }, - { url = "https://files.pythonhosted.org/packages/8b/ef/abd085f06853af0cd59fa5f913d61a8eab65d7639ff2a658d18a25d6a89d/pyyaml-6.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0", size = 732872, upload-time = "2025-09-25T21:31:53.282Z" }, - { url = "https://files.pythonhosted.org/packages/1f/15/2bc9c8faf6450a8b3c9fc5448ed869c599c0a74ba2669772b1f3a0040180/pyyaml-6.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69", size = 758828, upload-time = "2025-09-25T21:31:54.807Z" }, - { url = "https://files.pythonhosted.org/packages/a3/00/531e92e88c00f4333ce359e50c19b8d1de9fe8d581b1534e35ccfbc5f393/pyyaml-6.0.3-cp310-cp310-win32.whl", hash = "sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e", size = 142415, upload-time = "2025-09-25T21:31:55.885Z" }, - { url = "https://files.pythonhosted.org/packages/2a/fa/926c003379b19fca39dd4634818b00dec6c62d87faf628d1394e137354d4/pyyaml-6.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c", size = 158561, upload-time = "2025-09-25T21:31:57.406Z" }, { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" }, { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" }, { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" }, @@ -4400,16 +3890,6 @@ dependencies = [ ] 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/67/b9/52aa9ec2867528b54f1e60846728d8b4d84726630874fee3a91e66c7df81/pyzmq-27.1.0-cp310-cp310-macosx_10_15_universal2.whl", hash = "sha256:508e23ec9bc44c0005c4946ea013d9317ae00ac67778bd47519fdf5a0e930ff4", size = 1329850, upload-time = "2025-09-08T23:07:26.274Z" }, - { url = "https://files.pythonhosted.org/packages/99/64/5653e7b7425b169f994835a2b2abf9486264401fdef18df91ddae47ce2cc/pyzmq-27.1.0-cp310-cp310-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:507b6f430bdcf0ee48c0d30e734ea89ce5567fd7b8a0f0044a369c176aa44556", size = 906380, upload-time = "2025-09-08T23:07:29.78Z" }, - { url = "https://files.pythonhosted.org/packages/73/78/7d713284dbe022f6440e391bd1f3c48d9185673878034cfb3939cdf333b2/pyzmq-27.1.0-cp310-cp310-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf7b38f9fd7b81cb6d9391b2946382c8237fd814075c6aa9c3b746d53076023b", size = 666421, upload-time = "2025-09-08T23:07:31.263Z" }, - { url = "https://files.pythonhosted.org/packages/30/76/8f099f9d6482450428b17c4d6b241281af7ce6a9de8149ca8c1c649f6792/pyzmq-27.1.0-cp310-cp310-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:03ff0b279b40d687691a6217c12242ee71f0fba28bf8626ff50e3ef0f4410e1e", size = 854149, upload-time = "2025-09-08T23:07:33.17Z" }, - { url = "https://files.pythonhosted.org/packages/59/f0/37fbfff06c68016019043897e4c969ceab18bde46cd2aca89821fcf4fb2e/pyzmq-27.1.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:677e744fee605753eac48198b15a2124016c009a11056f93807000ab11ce6526", size = 1655070, upload-time = "2025-09-08T23:07:35.205Z" }, - { url = "https://files.pythonhosted.org/packages/47/14/7254be73f7a8edc3587609554fcaa7bfd30649bf89cd260e4487ca70fdaa/pyzmq-27.1.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:dd2fec2b13137416a1c5648b7009499bcc8fea78154cd888855fa32514f3dad1", size = 2033441, upload-time = "2025-09-08T23:07:37.432Z" }, - { url = "https://files.pythonhosted.org/packages/22/dc/49f2be26c6f86f347e796a4d99b19167fc94503f0af3fd010ad262158822/pyzmq-27.1.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:08e90bb4b57603b84eab1d0ca05b3bbb10f60c1839dc471fc1c9e1507bef3386", size = 1891529, upload-time = "2025-09-08T23:07:39.047Z" }, - { url = "https://files.pythonhosted.org/packages/a3/3e/154fb963ae25be70c0064ce97776c937ecc7d8b0259f22858154a9999769/pyzmq-27.1.0-cp310-cp310-win32.whl", hash = "sha256:a5b42d7a0658b515319148875fcb782bbf118dd41c671b62dae33666c2213bda", size = 567276, upload-time = "2025-09-08T23:07:40.695Z" }, - { url = "https://files.pythonhosted.org/packages/62/b2/f4ab56c8c595abcb26b2be5fd9fa9e6899c1e5ad54964e93ae8bb35482be/pyzmq-27.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:c0bb87227430ee3aefcc0ade2088100e528d5d3298a0a715a64f3d04c60ba02f", size = 632208, upload-time = "2025-09-08T23:07:42.298Z" }, - { url = "https://files.pythonhosted.org/packages/3b/e3/be2cc7ab8332bdac0522fdb64c17b1b6241a795bee02e0196636ec5beb79/pyzmq-27.1.0-cp310-cp310-win_arm64.whl", hash = "sha256:9a916f76c2ab8d045b19f2286851a38e9ac94ea91faf65bd64735924522a8b32", size = 559766, upload-time = "2025-09-08T23:07:43.869Z" }, { url = "https://files.pythonhosted.org/packages/06/5d/305323ba86b284e6fcb0d842d6adaa2999035f70f8c38a9b6d21ad28c3d4/pyzmq-27.1.0-cp311-cp311-macosx_10_15_universal2.whl", hash = "sha256:226b091818d461a3bef763805e75685e478ac17e9008f49fce2d3e52b3d58b86", size = 1333328, upload-time = "2025-09-08T23:07:45.946Z" }, { url = "https://files.pythonhosted.org/packages/bd/a0/fc7e78a23748ad5443ac3275943457e8452da67fda347e05260261108cbc/pyzmq-27.1.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:0790a0161c281ca9723f804871b4027f2e8b5a528d357c8952d08cd1a9c15581", size = 908803, upload-time = "2025-09-08T23:07:47.551Z" }, { url = "https://files.pythonhosted.org/packages/7e/22/37d15eb05f3bdfa4abea6f6d96eb3bb58585fbd3e4e0ded4e743bc650c97/pyzmq-27.1.0-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c895a6f35476b0c3a54e3eb6ccf41bf3018de937016e6e18748317f25d4e925f", size = 668836, upload-time = "2025-09-08T23:07:49.436Z" }, @@ -4452,11 +3932,6 @@ wheels = [ { 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" }, - { url = "https://files.pythonhosted.org/packages/f3/81/a65e71c1552f74dec9dff91d95bafb6e0d33338a8dfefbc88aa562a20c92/pyzmq-27.1.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:c17e03cbc9312bee223864f1a2b13a99522e0dc9f7c5df0177cd45210ac286e6", size = 836266, upload-time = "2025-09-08T23:09:40.048Z" }, - { url = "https://files.pythonhosted.org/packages/58/ed/0202ca350f4f2b69faa95c6d931e3c05c3a397c184cacb84cb4f8f42f287/pyzmq-27.1.0-pp310-pypy310_pp73-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:f328d01128373cb6763823b2b4e7f73bdf767834268c565151eacb3b7a392f90", size = 800206, upload-time = "2025-09-08T23:09:41.902Z" }, - { url = "https://files.pythonhosted.org/packages/47/42/1ff831fa87fe8f0a840ddb399054ca0009605d820e2b44ea43114f5459f4/pyzmq-27.1.0-pp310-pypy310_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c1790386614232e1b3a40a958454bdd42c6d1811837b15ddbb052a032a43f62", size = 567747, upload-time = "2025-09-08T23:09:43.741Z" }, - { url = "https://files.pythonhosted.org/packages/d1/db/5c4d6807434751e3f21231bee98109aa57b9b9b55e058e450d0aef59b70f/pyzmq-27.1.0-pp310-pypy310_pp73-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:448f9cb54eb0cee4732b46584f2710c8bc178b0e5371d9e4fc8125201e413a74", size = 747371, upload-time = "2025-09-08T23:09:45.575Z" }, - { url = "https://files.pythonhosted.org/packages/26/af/78ce193dbf03567eb8c0dc30e3df2b9e56f12a670bf7eb20f9fb532c7e8a/pyzmq-27.1.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:05b12f2d32112bf8c95ef2e74ec4f1d4beb01f8b5e703b38537f8849f92cb9ba", size = 544862, upload-time = "2025-09-08T23:09:47.448Z" }, { url = "https://files.pythonhosted.org/packages/4c/c6/c4dcdecdbaa70969ee1fdced6d7b8f60cfabe64d25361f27ac4665a70620/pyzmq-27.1.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:18770c8d3563715387139060d37859c02ce40718d1faf299abddcdcc6a649066", size = 836265, upload-time = "2025-09-08T23:09:49.376Z" }, { url = "https://files.pythonhosted.org/packages/3e/79/f38c92eeaeb03a2ccc2ba9866f0439593bb08c5e3b714ac1d553e5c96e25/pyzmq-27.1.0-pp311-pypy311_pp73-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:ac25465d42f92e990f8d8b0546b01c391ad431c3bf447683fdc40565941d0604", size = 800208, upload-time = "2025-09-08T23:09:51.073Z" }, { url = "https://files.pythonhosted.org/packages/49/0e/3f0d0d335c6b3abb9b7b723776d0b21fa7f3a6c819a0db6097059aada160/pyzmq-27.1.0-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:53b40f8ae006f2734ee7608d59ed661419f087521edbfc2149c3932e9c14808c", size = 567747, upload-time = "2025-09-08T23:09:52.698Z" }, @@ -4470,8 +3945,7 @@ version = "0.37.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, - { name = "rpds-py", version = "0.30.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "rpds-py", version = "2026.6.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { 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" } @@ -4485,23 +3959,6 @@ version = "2026.6.28" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f1/05/e4f219230e11e774a6c9987d2ab0d0c6b8573e13a17e143d0015bee710ef/regex-2026.6.28.tar.gz", hash = "sha256:3cb4b6c5cb3060cc31efdc1fbb27c25fb9b29044afd87e40601a1c4d9db54342", size = 416101, upload-time = "2026-06-28T19:56:55.302Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d8/dc/f7a8c9cf0768f704153d358fae2bc883199bc4ea1e4aa458f1be9d0ef2ce/regex-2026.6.28-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b83932645630965fd860fdb70ebbf964bf3e8007f08851ea424d01f8d35454a8", size = 489471, upload-time = "2026-06-28T19:53:06.385Z" }, - { url = "https://files.pythonhosted.org/packages/44/b3/9786a4a2133e2f1cc5897ed3d2da3da29ff54b775ffa38bc5935fc24be82/regex-2026.6.28-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e81f1952355042e517dc9861ce65c676e4a098f42402993c40461786d1f794d4", size = 291294, upload-time = "2026-06-28T19:53:09.232Z" }, - { url = "https://files.pythonhosted.org/packages/dd/1f/bfe5b529257f0853aa6b94146e0f6462f4d45aa4f3c05d5a828f415dfd40/regex-2026.6.28-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2097591101d70bcc108af64c46f6066bb698ee067fec5f75beac0be317639311", size = 289216, upload-time = "2026-06-28T19:53:10.682Z" }, - { url = "https://files.pythonhosted.org/packages/25/56/f615165e90ac5f3b72b249240643439520bbac0ac60a9de06868528eba4c/regex-2026.6.28-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:31d7538a614b5842bf53ce329d07b43f97754ca7e6db8d69f347e071bce1c953", size = 784787, upload-time = "2026-06-28T19:53:12.393Z" }, - { url = "https://files.pythonhosted.org/packages/04/94/c9e3ad31b3d5fbe1228fee8319e0c02a5460296624f220d08764547fe6ae/regex-2026.6.28-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f5561e47bbe2b75373b695326507743fcdd4d2cc7f5022312024ccf39fa094e0", size = 852137, upload-time = "2026-06-28T19:53:14.287Z" }, - { url = "https://files.pythonhosted.org/packages/c0/77/d506a428e446466ee298f5425a774737d0671d070425ed794bb3314d60c6/regex-2026.6.28-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c10f2c5a55ab3dd8318d8ad5f11b530e2691c0edebebde7713066f484902c3fb", size = 899525, upload-time = "2026-06-28T19:53:15.987Z" }, - { url = "https://files.pythonhosted.org/packages/aa/72/becc00d839f19401f10a20168b44711c7b02f7f62bba875b2d8f98417435/regex-2026.6.28-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23f7e0cc60c72486b42a685f1ff4eec90d50d4fb05e4f9c7d5363b03aa02600d", size = 794116, upload-time = "2026-06-28T19:53:17.372Z" }, - { url = "https://files.pythonhosted.org/packages/fa/11/ea2ca423eeaac2e18077a18b058614e9201f130750df2126d444e39acab2/regex-2026.6.28-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:76493755f79a88d5ed2c9e63a41d3c05997e0a7ffbe76ed8c4ded8be35b8b14c", size = 786257, upload-time = "2026-06-28T19:53:18.712Z" }, - { url = "https://files.pythonhosted.org/packages/6d/9e/f5bf7ecbd14ff2086f015c54dc24fd0d74ba5327fef0de479213f8128615/regex-2026.6.28-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ff0f41a00f23ea5054acb61901380c41813d813eee3f80f800995710bcc52ecd", size = 769914, upload-time = "2026-06-28T19:53:20.564Z" }, - { url = "https://files.pythonhosted.org/packages/43/04/f9040a5360a06241ba5b7f2e6f1c6184e104a84e6f6522535700e94bf8e2/regex-2026.6.28-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3c60b297292e7e1ef5d02a4759f9e452ee4c8bb95e168d8fd0b5db01bd806f9f", size = 775013, upload-time = "2026-06-28T19:53:22.067Z" }, - { url = "https://files.pythonhosted.org/packages/73/97/4e46f7abf2f864319d2bcac609af3c0532968c66a3364337778fd232b83c/regex-2026.6.28-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:a7cf03c87f7b9cbc25a8894cf9be83818406677b6b391b003ec7c884923387b5", size = 848814, upload-time = "2026-06-28T19:53:24.575Z" }, - { url = "https://files.pythonhosted.org/packages/f7/b8/3d1f995727799a1e2e693e397acb7358094606e5591b6b5fd3128d2d1409/regex-2026.6.28-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:418208ea0af51cfed4f46eb9b1ea7cfc990ca284f0084ecbd951460fb089421e", size = 757702, upload-time = "2026-06-28T19:53:26.215Z" }, - { url = "https://files.pythonhosted.org/packages/20/10/fd5653b8572910a4fe9055f8959b070d7d9443c94ce986529fcdb5fb2a3c/regex-2026.6.28-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:7635fa2cddb917a6bbfac7890602573d2d8c4e470703b0640e6f86a988817ec3", size = 837140, upload-time = "2026-06-28T19:53:27.655Z" }, - { url = "https://files.pythonhosted.org/packages/5d/31/da77e3ef7b594a2aacbd03ce3d0050f33ab3e021df50c6901467c9006511/regex-2026.6.28-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:7bb96c13d6cf5880d31bbef84ca701a64d738aa491c2b79975cc33f8ad00a31e", size = 782105, upload-time = "2026-06-28T19:53:29.375Z" }, - { url = "https://files.pythonhosted.org/packages/cd/4d/c379001448d0f58b6946f168d4af96ad60a16c1553259c27b0df8701b640/regex-2026.6.28-cp310-cp310-win32.whl", hash = "sha256:56f05194c4843957dd8b3af87eb0c52d8cf0509e7f18e172d727f5f8ff840646", size = 266728, upload-time = "2026-06-28T19:53:31.813Z" }, - { url = "https://files.pythonhosted.org/packages/f3/8f/cb656529efa87d74cce0d69e606c745537016da3bdfae78f342af2242ee3/regex-2026.6.28-cp310-cp310-win_amd64.whl", hash = "sha256:70710927033af3b54369f17aaba1343b97a23d0b1aa994fa1512b08b1b8c136a", size = 277901, upload-time = "2026-06-28T19:53:33.293Z" }, - { url = "https://files.pythonhosted.org/packages/7b/ac/d35ccc309c9409406445ab2ef0b56f6a341a916ccff49ff9ac5cc6bb8e9b/regex-2026.6.28-cp310-cp310-win_arm64.whl", hash = "sha256:ed7b30185ee3f8b9b053b0be567b4d226016e2afbebc17fde1c6a4580937b688", size = 276880, upload-time = "2026-06-28T19:53:35.029Z" }, { url = "https://files.pythonhosted.org/packages/72/db/9051b36294bdbabaa9c7db57db0fbcdfbd17f7a106c539bb423d0323faea/regex-2026.6.28-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a71b51dd08b9b62f055fafab3dee8af8bd2ec81b373a44caef18d6c5ca28f43a", size = 489481, upload-time = "2026-06-28T19:53:36.684Z" }, { url = "https://files.pythonhosted.org/packages/35/3f/24097a3c3ff30f9a639888900faaecabcf5f54a5bc9c851c297e11b349ef/regex-2026.6.28-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9c26a47770d30a0f85c01e261d2a3ebc342c4af6fd666dbd8c1fe4cbf3adf726", size = 291292, upload-time = "2026-06-28T19:53:38.39Z" }, { url = "https://files.pythonhosted.org/packages/5e/cc/e0d762a189cfb4e8926d16e691720690d139a977b38fdb80230c259332ab/regex-2026.6.28-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e5efbc1af38f97e300d43028e5a92e752d924bcfb7f465d8669d5d5a6e78c233", size = 289232, upload-time = "2026-06-28T19:53:40.181Z" }, @@ -4628,150 +4085,10 @@ 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 = "rpds-py" -version = "0.30.0" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] -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/06/0c/0c411a0ec64ccb6d104dcabe0e713e05e153a9a2c3c2bd2b32ce412166fe/rpds_py-0.30.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:679ae98e00c0e8d68a7fda324e16b90fd5260945b45d3b824c892cec9eea3288", size = 370490, upload-time = "2025-11-30T20:21:33.256Z" }, - { url = "https://files.pythonhosted.org/packages/19/6a/4ba3d0fb7297ebae71171822554abe48d7cab29c28b8f9f2c04b79988c05/rpds_py-0.30.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:4cc2206b76b4f576934f0ed374b10d7ca5f457858b157ca52064bdfc26b9fc00", size = 359751, upload-time = "2025-11-30T20:21:34.591Z" }, - { url = "https://files.pythonhosted.org/packages/cd/7c/e4933565ef7f7a0818985d87c15d9d273f1a649afa6a52ea35ad011195ea/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:389a2d49eded1896c3d48b0136ead37c48e221b391c052fba3f4055c367f60a6", size = 389696, upload-time = "2025-11-30T20:21:36.122Z" }, - { url = "https://files.pythonhosted.org/packages/5e/01/6271a2511ad0815f00f7ed4390cf2567bec1d4b1da39e2c27a41e6e3b4de/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:32c8528634e1bf7121f3de08fa85b138f4e0dc47657866630611b03967f041d7", size = 403136, upload-time = "2025-11-30T20:21:37.728Z" }, - { url = "https://files.pythonhosted.org/packages/55/64/c857eb7cd7541e9b4eee9d49c196e833128a55b89a9850a9c9ac33ccf897/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f207f69853edd6f6700b86efb84999651baf3789e78a466431df1331608e5324", size = 524699, upload-time = "2025-11-30T20:21:38.92Z" }, - { url = "https://files.pythonhosted.org/packages/9c/ed/94816543404078af9ab26159c44f9e98e20fe47e2126d5d32c9d9948d10a/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:67b02ec25ba7a9e8fa74c63b6ca44cf5707f2fbfadae3ee8e7494297d56aa9df", size = 412022, upload-time = "2025-11-30T20:21:40.407Z" }, - { url = "https://files.pythonhosted.org/packages/61/b5/707f6cf0066a6412aacc11d17920ea2e19e5b2f04081c64526eb35b5c6e7/rpds_py-0.30.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0c0e95f6819a19965ff420f65578bacb0b00f251fefe2c8b23347c37174271f3", size = 390522, upload-time = "2025-11-30T20:21:42.17Z" }, - { url = "https://files.pythonhosted.org/packages/13/4e/57a85fda37a229ff4226f8cbcf09f2a455d1ed20e802ce5b2b4a7f5ed053/rpds_py-0.30.0-cp310-cp310-manylinux_2_31_riscv64.whl", hash = "sha256:a452763cc5198f2f98898eb98f7569649fe5da666c2dc6b5ddb10fde5a574221", size = 404579, upload-time = "2025-11-30T20:21:43.769Z" }, - { url = "https://files.pythonhosted.org/packages/f9/da/c9339293513ec680a721e0e16bf2bac3db6e5d7e922488de471308349bba/rpds_py-0.30.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e0b65193a413ccc930671c55153a03ee57cecb49e6227204b04fae512eb657a7", size = 421305, upload-time = "2025-11-30T20:21:44.994Z" }, - { url = "https://files.pythonhosted.org/packages/f9/be/522cb84751114f4ad9d822ff5a1aa3c98006341895d5f084779b99596e5c/rpds_py-0.30.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:858738e9c32147f78b3ac24dc0edb6610000e56dc0f700fd5f651d0a0f0eb9ff", size = 572503, upload-time = "2025-11-30T20:21:46.91Z" }, - { url = "https://files.pythonhosted.org/packages/a2/9b/de879f7e7ceddc973ea6e4629e9b380213a6938a249e94b0cdbcc325bb66/rpds_py-0.30.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:da279aa314f00acbb803da1e76fa18666778e8a8f83484fba94526da5de2cba7", size = 598322, upload-time = "2025-11-30T20:21:48.709Z" }, - { url = "https://files.pythonhosted.org/packages/48/ac/f01fc22efec3f37d8a914fc1b2fb9bcafd56a299edbe96406f3053edea5a/rpds_py-0.30.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:7c64d38fb49b6cdeda16ab49e35fe0da2e1e9b34bc38bd78386530f218b37139", size = 560792, upload-time = "2025-11-30T20:21:50.024Z" }, - { url = "https://files.pythonhosted.org/packages/e2/da/4e2b19d0f131f35b6146425f846563d0ce036763e38913d917187307a671/rpds_py-0.30.0-cp310-cp310-win32.whl", hash = "sha256:6de2a32a1665b93233cde140ff8b3467bdb9e2af2b91079f0333a0974d12d464", size = 221901, upload-time = "2025-11-30T20:21:51.32Z" }, - { url = "https://files.pythonhosted.org/packages/96/cb/156d7a5cf4f78a7cc571465d8aec7a3c447c94f6749c5123f08438bcf7bc/rpds_py-0.30.0-cp310-cp310-win_amd64.whl", hash = "sha256:1726859cd0de969f88dc8673bdd954185b9104e05806be64bcd87badbe313169", size = 235823, upload-time = "2025-11-30T20:21:52.505Z" }, - { url = "https://files.pythonhosted.org/packages/4d/6e/f964e88b3d2abee2a82c1ac8366da848fce1c6d834dc2132c3fda3970290/rpds_py-0.30.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:a2bffea6a4ca9f01b3f8e548302470306689684e61602aa3d141e34da06cf425", size = 370157, upload-time = "2025-11-30T20:21:53.789Z" }, - { url = "https://files.pythonhosted.org/packages/94/ba/24e5ebb7c1c82e74c4e4f33b2112a5573ddc703915b13a073737b59b86e0/rpds_py-0.30.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dc4f992dfe1e2bc3ebc7444f6c7051b4bc13cd8e33e43511e8ffd13bf407010d", size = 359676, upload-time = "2025-11-30T20:21:55.475Z" }, - { url = "https://files.pythonhosted.org/packages/84/86/04dbba1b087227747d64d80c3b74df946b986c57af0a9f0c98726d4d7a3b/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:422c3cb9856d80b09d30d2eb255d0754b23e090034e1deb4083f8004bd0761e4", size = 389938, upload-time = "2025-11-30T20:21:57.079Z" }, - { url = "https://files.pythonhosted.org/packages/42/bb/1463f0b1722b7f45431bdd468301991d1328b16cffe0b1c2918eba2c4eee/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:07ae8a593e1c3c6b82ca3292efbe73c30b61332fd612e05abee07c79359f292f", size = 402932, upload-time = "2025-11-30T20:21:58.47Z" }, - { url = "https://files.pythonhosted.org/packages/99/ee/2520700a5c1f2d76631f948b0736cdf9b0acb25abd0ca8e889b5c62ac2e3/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:12f90dd7557b6bd57f40abe7747e81e0c0b119bef015ea7726e69fe550e394a4", size = 525830, upload-time = "2025-11-30T20:21:59.699Z" }, - { url = "https://files.pythonhosted.org/packages/e0/ad/bd0331f740f5705cc555a5e17fdf334671262160270962e69a2bdef3bf76/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:99b47d6ad9a6da00bec6aabe5a6279ecd3c06a329d4aa4771034a21e335c3a97", size = 412033, upload-time = "2025-11-30T20:22:00.991Z" }, - { url = "https://files.pythonhosted.org/packages/f8/1e/372195d326549bb51f0ba0f2ecb9874579906b97e08880e7a65c3bef1a99/rpds_py-0.30.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:33f559f3104504506a44bb666b93a33f5d33133765b0c216a5bf2f1e1503af89", size = 390828, upload-time = "2025-11-30T20:22:02.723Z" }, - { url = "https://files.pythonhosted.org/packages/ab/2b/d88bb33294e3e0c76bc8f351a3721212713629ffca1700fa94979cb3eae8/rpds_py-0.30.0-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:946fe926af6e44f3697abbc305ea168c2c31d3e3ef1058cf68f379bf0335a78d", size = 404683, upload-time = "2025-11-30T20:22:04.367Z" }, - { url = "https://files.pythonhosted.org/packages/50/32/c759a8d42bcb5289c1fac697cd92f6fe01a018dd937e62ae77e0e7f15702/rpds_py-0.30.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:495aeca4b93d465efde585977365187149e75383ad2684f81519f504f5c13038", size = 421583, upload-time = "2025-11-30T20:22:05.814Z" }, - { url = "https://files.pythonhosted.org/packages/2b/81/e729761dbd55ddf5d84ec4ff1f47857f4374b0f19bdabfcf929164da3e24/rpds_py-0.30.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d9a0ca5da0386dee0655b4ccdf46119df60e0f10da268d04fe7cc87886872ba7", size = 572496, upload-time = "2025-11-30T20:22:07.713Z" }, - { url = "https://files.pythonhosted.org/packages/14/f6/69066a924c3557c9c30baa6ec3a0aa07526305684c6f86c696b08860726c/rpds_py-0.30.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:8d6d1cc13664ec13c1b84241204ff3b12f9bb82464b8ad6e7a5d3486975c2eed", size = 598669, upload-time = "2025-11-30T20:22:09.312Z" }, - { url = "https://files.pythonhosted.org/packages/5f/48/905896b1eb8a05630d20333d1d8ffd162394127b74ce0b0784ae04498d32/rpds_py-0.30.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:3896fa1be39912cf0757753826bc8bdc8ca331a28a7c4ae46b7a21280b06bb85", size = 561011, upload-time = "2025-11-30T20:22:11.309Z" }, - { url = "https://files.pythonhosted.org/packages/22/16/cd3027c7e279d22e5eb431dd3c0fbc677bed58797fe7581e148f3f68818b/rpds_py-0.30.0-cp311-cp311-win32.whl", hash = "sha256:55f66022632205940f1827effeff17c4fa7ae1953d2b74a8581baaefb7d16f8c", size = 221406, upload-time = "2025-11-30T20:22:13.101Z" }, - { url = "https://files.pythonhosted.org/packages/fa/5b/e7b7aa136f28462b344e652ee010d4de26ee9fd16f1bfd5811f5153ccf89/rpds_py-0.30.0-cp311-cp311-win_amd64.whl", hash = "sha256:a51033ff701fca756439d641c0ad09a41d9242fa69121c7d8769604a0a629825", size = 236024, upload-time = "2025-11-30T20:22:14.853Z" }, - { url = "https://files.pythonhosted.org/packages/14/a6/364bba985e4c13658edb156640608f2c9e1d3ea3c81b27aa9d889fff0e31/rpds_py-0.30.0-cp311-cp311-win_arm64.whl", hash = "sha256:47b0ef6231c58f506ef0b74d44e330405caa8428e770fec25329ed2cb971a229", size = 229069, upload-time = "2025-11-30T20:22:16.577Z" }, - { 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" }, - { url = "https://files.pythonhosted.org/packages/69/71/3f34339ee70521864411f8b6992e7ab13ac30d8e4e3309e07c7361767d91/rpds_py-0.30.0-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:c2262bdba0ad4fc6fb5545660673925c2d2a5d9e2e0fb603aad545427be0fc58", size = 372292, upload-time = "2025-11-30T20:24:16.537Z" }, - { url = "https://files.pythonhosted.org/packages/57/09/f183df9b8f2d66720d2ef71075c59f7e1b336bec7ee4c48f0a2b06857653/rpds_py-0.30.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:ee6af14263f25eedc3bb918a3c04245106a42dfd4f5c2285ea6f997b1fc3f89a", size = 362128, upload-time = "2025-11-30T20:24:18.086Z" }, - { url = "https://files.pythonhosted.org/packages/7a/68/5c2594e937253457342e078f0cc1ded3dd7b2ad59afdbf2d354869110a02/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3adbb8179ce342d235c31ab8ec511e66c73faa27a47e076ccc92421add53e2bb", size = 391542, upload-time = "2025-11-30T20:24:20.092Z" }, - { url = "https://files.pythonhosted.org/packages/49/5c/31ef1afd70b4b4fbdb2800249f34c57c64beb687495b10aec0365f53dfc4/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:250fa00e9543ac9b97ac258bd37367ff5256666122c2d0f2bc97577c60a1818c", size = 404004, upload-time = "2025-11-30T20:24:22.231Z" }, - { url = "https://files.pythonhosted.org/packages/e3/63/0cfbea38d05756f3440ce6534d51a491d26176ac045e2707adc99bb6e60a/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9854cf4f488b3d57b9aaeb105f06d78e5529d3145b1e4a41750167e8c213c6d3", size = 527063, upload-time = "2025-11-30T20:24:24.302Z" }, - { url = "https://files.pythonhosted.org/packages/42/e6/01e1f72a2456678b0f618fc9a1a13f882061690893c192fcad9f2926553a/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:993914b8e560023bc0a8bf742c5f303551992dcb85e247b1e5c7f4a7d145bda5", size = 413099, upload-time = "2025-11-30T20:24:25.916Z" }, - { url = "https://files.pythonhosted.org/packages/b8/25/8df56677f209003dcbb180765520c544525e3ef21ea72279c98b9aa7c7fb/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:58edca431fb9b29950807e301826586e5bbf24163677732429770a697ffe6738", size = 392177, upload-time = "2025-11-30T20:24:27.834Z" }, - { url = "https://files.pythonhosted.org/packages/4a/b4/0a771378c5f16f8115f796d1f437950158679bcd2a7c68cf251cfb00ed5b/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:dea5b552272a944763b34394d04577cf0f9bd013207bc32323b5a89a53cf9c2f", size = 406015, upload-time = "2025-11-30T20:24:29.457Z" }, - { url = "https://files.pythonhosted.org/packages/36/d8/456dbba0af75049dc6f63ff295a2f92766b9d521fa00de67a2bd6427d57a/rpds_py-0.30.0-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ba3af48635eb83d03f6c9735dfb21785303e73d22ad03d489e88adae6eab8877", size = 423736, upload-time = "2025-11-30T20:24:31.22Z" }, - { url = "https://files.pythonhosted.org/packages/13/64/b4d76f227d5c45a7e0b796c674fd81b0a6c4fbd48dc29271857d8219571c/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:dff13836529b921e22f15cb099751209a60009731a68519630a24d61f0b1b30a", size = 573981, upload-time = "2025-11-30T20:24:32.934Z" }, - { url = "https://files.pythonhosted.org/packages/20/91/092bacadeda3edf92bf743cc96a7be133e13a39cdbfd7b5082e7ab638406/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:1b151685b23929ab7beec71080a8889d4d6d9fa9a983d213f07121205d48e2c4", size = 599782, upload-time = "2025-11-30T20:24:35.169Z" }, - { url = "https://files.pythonhosted.org/packages/d1/b7/b95708304cd49b7b6f82fdd039f1748b66ec2b21d6a45180910802f1abf1/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:ac37f9f516c51e5753f27dfdef11a88330f04de2d564be3991384b2f3535d02e", size = 562191, upload-time = "2025-11-30T20:24:36.853Z" }, -] - [[package]] name = "rpds-py" version = "2026.6.3" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", -] 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/94/1f/a2dca5ffdbf1d475ffc4e80e4d5d720ff3a00f691795910116960ee12511/rpds_py-2026.6.3-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:7b689145a1485c335569bd056464f3243a29af7ed3871c7be31ad624ba239bc7", size = 342174, upload-time = "2026-06-30T07:14:54.821Z" }, @@ -4964,80 +4281,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" }, ] -[[package]] -name = "scikit-learn" -version = "1.7.2" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] -dependencies = [ - { name = "joblib", marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "threadpoolctl", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ba/3e/daed796fd69cce768b8788401cc464ea90b306fb196ae1ffed0b98182859/scikit_learn-1.7.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6b33579c10a3081d076ab403df4a4190da4f4432d443521674637677dc91e61f", size = 9336221, upload-time = "2025-09-09T08:20:19.328Z" }, - { url = "https://files.pythonhosted.org/packages/1c/ce/af9d99533b24c55ff4e18d9b7b4d9919bbc6cd8f22fe7a7be01519a347d5/scikit_learn-1.7.2-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:36749fb62b3d961b1ce4fedf08fa57a1986cd409eff2d783bca5d4b9b5fce51c", size = 8653834, upload-time = "2025-09-09T08:20:22.073Z" }, - { url = "https://files.pythonhosted.org/packages/58/0e/8c2a03d518fb6bd0b6b0d4b114c63d5f1db01ff0f9925d8eb10960d01c01/scikit_learn-1.7.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7a58814265dfc52b3295b1900cfb5701589d30a8bb026c7540f1e9d3499d5ec8", size = 9660938, upload-time = "2025-09-09T08:20:24.327Z" }, - { url = "https://files.pythonhosted.org/packages/2b/75/4311605069b5d220e7cf5adabb38535bd96f0079313cdbb04b291479b22a/scikit_learn-1.7.2-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a847fea807e278f821a0406ca01e387f97653e284ecbd9750e3ee7c90347f18", size = 9477818, upload-time = "2025-09-09T08:20:26.845Z" }, - { url = "https://files.pythonhosted.org/packages/7f/9b/87961813c34adbca21a6b3f6b2bea344c43b30217a6d24cc437c6147f3e8/scikit_learn-1.7.2-cp310-cp310-win_amd64.whl", hash = "sha256:ca250e6836d10e6f402436d6463d6c0e4d8e0234cfb6a9a47835bd392b852ce5", size = 8886969, upload-time = "2025-09-09T08:20:29.329Z" }, - { url = "https://files.pythonhosted.org/packages/43/83/564e141eef908a5863a54da8ca342a137f45a0bfb71d1d79704c9894c9d1/scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e", size = 9331967, upload-time = "2025-09-09T08:20:32.421Z" }, - { url = "https://files.pythonhosted.org/packages/18/d6/ba863a4171ac9d7314c4d3fc251f015704a2caeee41ced89f321c049ed83/scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1", size = 8648645, upload-time = "2025-09-09T08:20:34.436Z" }, - { url = "https://files.pythonhosted.org/packages/ef/0e/97dbca66347b8cf0ea8b529e6bb9367e337ba2e8be0ef5c1a545232abfde/scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d", size = 9715424, upload-time = "2025-09-09T08:20:36.776Z" }, - { url = "https://files.pythonhosted.org/packages/f7/32/1f3b22e3207e1d2c883a7e09abb956362e7d1bd2f14458c7de258a26ac15/scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1", size = 9509234, upload-time = "2025-09-09T08:20:38.957Z" }, - { url = "https://files.pythonhosted.org/packages/9f/71/34ddbd21f1da67c7a768146968b4d0220ee6831e4bcbad3e03dd3eae88b6/scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1", size = 8894244, upload-time = "2025-09-09T08:20:41.166Z" }, - { url = "https://files.pythonhosted.org/packages/a7/aa/3996e2196075689afb9fce0410ebdb4a09099d7964d061d7213700204409/scikit_learn-1.7.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8d91a97fa2b706943822398ab943cde71858a50245e31bc71dba62aab1d60a96", size = 9259818, upload-time = "2025-09-09T08:20:43.19Z" }, - { url = "https://files.pythonhosted.org/packages/43/5d/779320063e88af9c4a7c2cf463ff11c21ac9c8bd730c4a294b0000b666c9/scikit_learn-1.7.2-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:acbc0f5fd2edd3432a22c69bed78e837c70cf896cd7993d71d51ba6708507476", size = 8636997, upload-time = "2025-09-09T08:20:45.468Z" }, - { url = "https://files.pythonhosted.org/packages/5c/d0/0c577d9325b05594fdd33aa970bf53fb673f051a45496842caee13cfd7fe/scikit_learn-1.7.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e5bf3d930aee75a65478df91ac1225ff89cd28e9ac7bd1196853a9229b6adb0b", size = 9478381, upload-time = "2025-09-09T08:20:47.982Z" }, - { url = "https://files.pythonhosted.org/packages/82/70/8bf44b933837ba8494ca0fc9a9ab60f1c13b062ad0197f60a56e2fc4c43e/scikit_learn-1.7.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4d6e9deed1a47aca9fe2f267ab8e8fe82ee20b4526b2c0cd9e135cea10feb44", size = 9300296, upload-time = "2025-09-09T08:20:50.366Z" }, - { url = "https://files.pythonhosted.org/packages/c6/99/ed35197a158f1fdc2fe7c3680e9c70d0128f662e1fee4ed495f4b5e13db0/scikit_learn-1.7.2-cp312-cp312-win_amd64.whl", hash = "sha256:6088aa475f0785e01bcf8529f55280a3d7d298679f50c0bb70a2364a82d0b290", size = 8731256, upload-time = "2025-09-09T08:20:52.627Z" }, - { url = "https://files.pythonhosted.org/packages/ae/93/a3038cb0293037fd335f77f31fe053b89c72f17b1c8908c576c29d953e84/scikit_learn-1.7.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0b7dacaa05e5d76759fb071558a8b5130f4845166d88654a0f9bdf3eb57851b7", size = 9212382, upload-time = "2025-09-09T08:20:54.731Z" }, - { url = "https://files.pythonhosted.org/packages/40/dd/9a88879b0c1104259136146e4742026b52df8540c39fec21a6383f8292c7/scikit_learn-1.7.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:abebbd61ad9e1deed54cca45caea8ad5f79e1b93173dece40bb8e0c658dbe6fe", size = 8592042, upload-time = "2025-09-09T08:20:57.313Z" }, - { url = "https://files.pythonhosted.org/packages/46/af/c5e286471b7d10871b811b72ae794ac5fe2989c0a2df07f0ec723030f5f5/scikit_learn-1.7.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:502c18e39849c0ea1a5d681af1dbcf15f6cce601aebb657aabbfe84133c1907f", size = 9434180, upload-time = "2025-09-09T08:20:59.671Z" }, - { url = "https://files.pythonhosted.org/packages/f1/fd/df59faa53312d585023b2da27e866524ffb8faf87a68516c23896c718320/scikit_learn-1.7.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a4c328a71785382fe3fe676a9ecf2c86189249beff90bf85e22bdb7efaf9ae0", size = 9283660, upload-time = "2025-09-09T08:21:01.71Z" }, - { url = "https://files.pythonhosted.org/packages/a7/c7/03000262759d7b6f38c836ff9d512f438a70d8a8ddae68ee80de72dcfb63/scikit_learn-1.7.2-cp313-cp313-win_amd64.whl", hash = "sha256:63a9afd6f7b229aad94618c01c252ce9e6fa97918c5ca19c9a17a087d819440c", size = 8702057, upload-time = "2025-09-09T08:21:04.234Z" }, - { url = "https://files.pythonhosted.org/packages/55/87/ef5eb1f267084532c8e4aef98a28b6ffe7425acbfd64b5e2f2e066bc29b3/scikit_learn-1.7.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:9acb6c5e867447b4e1390930e3944a005e2cb115922e693c08a323421a6966e8", size = 9558731, upload-time = "2025-09-09T08:21:06.381Z" }, - { url = "https://files.pythonhosted.org/packages/93/f8/6c1e3fc14b10118068d7938878a9f3f4e6d7b74a8ddb1e5bed65159ccda8/scikit_learn-1.7.2-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:2a41e2a0ef45063e654152ec9d8bcfc39f7afce35b08902bfe290c2498a67a6a", size = 9038852, upload-time = "2025-09-09T08:21:08.628Z" }, - { url = "https://files.pythonhosted.org/packages/83/87/066cafc896ee540c34becf95d30375fe5cbe93c3b75a0ee9aa852cd60021/scikit_learn-1.7.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:98335fb98509b73385b3ab2bd0639b1f610541d3988ee675c670371d6a87aa7c", size = 9527094, upload-time = "2025-09-09T08:21:11.486Z" }, - { url = "https://files.pythonhosted.org/packages/9c/2b/4903e1ccafa1f6453b1ab78413938c8800633988c838aa0be386cbb33072/scikit_learn-1.7.2-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:191e5550980d45449126e23ed1d5e9e24b2c68329ee1f691a3987476e115e09c", size = 9367436, upload-time = "2025-09-09T08:21:13.602Z" }, - { url = "https://files.pythonhosted.org/packages/b5/aa/8444be3cfb10451617ff9d177b3c190288f4563e6c50ff02728be67ad094/scikit_learn-1.7.2-cp313-cp313t-win_amd64.whl", hash = "sha256:57dc4deb1d3762c75d685507fbd0bc17160144b2f2ba4ccea5dc285ab0d0e973", size = 9275749, upload-time = "2025-09-09T08:21:15.96Z" }, - { url = "https://files.pythonhosted.org/packages/d9/82/dee5acf66837852e8e68df6d8d3a6cb22d3df997b733b032f513d95205b7/scikit_learn-1.7.2-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fa8f63940e29c82d1e67a45d5297bdebbcb585f5a5a50c4914cc2e852ab77f33", size = 9208906, upload-time = "2025-09-09T08:21:18.557Z" }, - { url = "https://files.pythonhosted.org/packages/3c/30/9029e54e17b87cb7d50d51a5926429c683d5b4c1732f0507a6c3bed9bf65/scikit_learn-1.7.2-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:f95dc55b7902b91331fa4e5845dd5bde0580c9cd9612b1b2791b7e80c3d32615", size = 8627836, upload-time = "2025-09-09T08:21:20.695Z" }, - { url = "https://files.pythonhosted.org/packages/60/18/4a52c635c71b536879f4b971c2cedf32c35ee78f48367885ed8025d1f7ee/scikit_learn-1.7.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9656e4a53e54578ad10a434dc1f993330568cfee176dff07112b8785fb413106", size = 9426236, upload-time = "2025-09-09T08:21:22.645Z" }, - { url = "https://files.pythonhosted.org/packages/99/7e/290362f6ab582128c53445458a5befd471ed1ea37953d5bcf80604619250/scikit_learn-1.7.2-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96dc05a854add0e50d3f47a1ef21a10a595016da5b007c7d9cd9d0bffd1fcc61", size = 9312593, upload-time = "2025-09-09T08:21:24.65Z" }, - { url = "https://files.pythonhosted.org/packages/8e/87/24f541b6d62b1794939ae6422f8023703bbf6900378b2b34e0b4384dfefd/scikit_learn-1.7.2-cp314-cp314-win_amd64.whl", hash = "sha256:bb24510ed3f9f61476181e4db51ce801e2ba37541def12dc9333b946fc7a9cf8", size = 8820007, upload-time = "2025-09-09T08:21:26.713Z" }, -] - [[package]] name = "scikit-learn" version = "1.9.0" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", -] dependencies = [ - { name = "joblib", marker = "python_full_version >= '3.11'" }, - { name = "narwhals", marker = "python_full_version >= '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "joblib" }, + { name = "narwhals" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "scipy", version = "1.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "threadpoolctl", marker = "python_full_version >= '3.11'" }, + { name = "threadpoolctl" }, ] sdist = { url = "https://files.pythonhosted.org/packages/fa/6f/37092bdb25f712817231799fc5674d8e704066a8a70c1d2d40517e18b4ab/scikit_learn-1.9.0.tar.gz", hash = "sha256:8833266989d3a5110178a9fae30783675460724d0e1efb13b14901d2c660c557", size = 7750767, upload-time = "2026-06-02T11:54:32.706Z" } wheels = [ @@ -5073,78 +4328,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ee/f3/ff83d76d7418112e5a61326443cdda87be3545dd8d6599c95b2481a4419e/scikit_learn-1.9.0-cp314-cp314t-win_arm64.whl", hash = "sha256:051075bda8b7aab87b1906ab3d4740a1e1224a19d7b3781a576736edc94e76aa", size = 8222661, upload-time = "2026-06-02T11:54:30.192Z" }, ] -[[package]] -name = "scipy" -version = "1.15.3" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] -dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/78/2f/4966032c5f8cc7e6a60f1b2e0ad686293b9474b65246b0c642e3ef3badd0/scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c", size = 38702770, upload-time = "2025-05-08T16:04:20.849Z" }, - { url = "https://files.pythonhosted.org/packages/a0/6e/0c3bf90fae0e910c274db43304ebe25a6b391327f3f10b5dcc638c090795/scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253", size = 30094511, upload-time = "2025-05-08T16:04:27.103Z" }, - { url = "https://files.pythonhosted.org/packages/ea/b1/4deb37252311c1acff7f101f6453f0440794f51b6eacb1aad4459a134081/scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f", size = 22368151, upload-time = "2025-05-08T16:04:31.731Z" }, - { url = "https://files.pythonhosted.org/packages/38/7d/f457626e3cd3c29b3a49ca115a304cebb8cc6f31b04678f03b216899d3c6/scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92", size = 25121732, upload-time = "2025-05-08T16:04:36.596Z" }, - { url = "https://files.pythonhosted.org/packages/db/0a/92b1de4a7adc7a15dcf5bddc6e191f6f29ee663b30511ce20467ef9b82e4/scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82", size = 35547617, upload-time = "2025-05-08T16:04:43.546Z" }, - { url = "https://files.pythonhosted.org/packages/8e/6d/41991e503e51fc1134502694c5fa7a1671501a17ffa12716a4a9151af3df/scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40", size = 37662964, upload-time = "2025-05-08T16:04:49.431Z" }, - { url = "https://files.pythonhosted.org/packages/25/e1/3df8f83cb15f3500478c889be8fb18700813b95e9e087328230b98d547ff/scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e", size = 37238749, upload-time = "2025-05-08T16:04:55.215Z" }, - { url = "https://files.pythonhosted.org/packages/93/3e/b3257cf446f2a3533ed7809757039016b74cd6f38271de91682aa844cfc5/scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c", size = 40022383, upload-time = "2025-05-08T16:05:01.914Z" }, - { url = "https://files.pythonhosted.org/packages/d1/84/55bc4881973d3f79b479a5a2e2df61c8c9a04fcb986a213ac9c02cfb659b/scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13", size = 41259201, upload-time = "2025-05-08T16:05:08.166Z" }, - { url = "https://files.pythonhosted.org/packages/96/ab/5cc9f80f28f6a7dff646c5756e559823614a42b1939d86dd0ed550470210/scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b", size = 38714255, upload-time = "2025-05-08T16:05:14.596Z" }, - { url = "https://files.pythonhosted.org/packages/4a/4a/66ba30abe5ad1a3ad15bfb0b59d22174012e8056ff448cb1644deccbfed2/scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba", size = 30111035, upload-time = "2025-05-08T16:05:20.152Z" }, - { url = "https://files.pythonhosted.org/packages/4b/fa/a7e5b95afd80d24313307f03624acc65801846fa75599034f8ceb9e2cbf6/scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65", size = 22384499, upload-time = "2025-05-08T16:05:24.494Z" }, - { url = "https://files.pythonhosted.org/packages/17/99/f3aaddccf3588bb4aea70ba35328c204cadd89517a1612ecfda5b2dd9d7a/scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1", size = 25152602, upload-time = "2025-05-08T16:05:29.313Z" }, - { url = "https://files.pythonhosted.org/packages/56/c5/1032cdb565f146109212153339f9cb8b993701e9fe56b1c97699eee12586/scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889", size = 35503415, upload-time = "2025-05-08T16:05:34.699Z" }, - { url = "https://files.pythonhosted.org/packages/bd/37/89f19c8c05505d0601ed5650156e50eb881ae3918786c8fd7262b4ee66d3/scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982", size = 37652622, upload-time = "2025-05-08T16:05:40.762Z" }, - { url = "https://files.pythonhosted.org/packages/7e/31/be59513aa9695519b18e1851bb9e487de66f2d31f835201f1b42f5d4d475/scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9", size = 37244796, upload-time = "2025-05-08T16:05:48.119Z" }, - { url = "https://files.pythonhosted.org/packages/10/c0/4f5f3eeccc235632aab79b27a74a9130c6c35df358129f7ac8b29f562ac7/scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594", size = 40047684, upload-time = "2025-05-08T16:05:54.22Z" }, - { url = "https://files.pythonhosted.org/packages/ab/a7/0ddaf514ce8a8714f6ed243a2b391b41dbb65251affe21ee3077ec45ea9a/scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb", size = 41246504, upload-time = "2025-05-08T16:06:00.437Z" }, - { url = "https://files.pythonhosted.org/packages/37/4b/683aa044c4162e10ed7a7ea30527f2cbd92e6999c10a8ed8edb253836e9c/scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019", size = 38766735, upload-time = "2025-05-08T16:06:06.471Z" }, - { url = "https://files.pythonhosted.org/packages/7b/7e/f30be3d03de07f25dc0ec926d1681fed5c732d759ac8f51079708c79e680/scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6", size = 30173284, upload-time = "2025-05-08T16:06:11.686Z" }, - { url = "https://files.pythonhosted.org/packages/07/9c/0ddb0d0abdabe0d181c1793db51f02cd59e4901da6f9f7848e1f96759f0d/scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477", size = 22446958, upload-time = "2025-05-08T16:06:15.97Z" }, - { url = "https://files.pythonhosted.org/packages/af/43/0bce905a965f36c58ff80d8bea33f1f9351b05fad4beaad4eae34699b7a1/scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c", size = 25242454, upload-time = "2025-05-08T16:06:20.394Z" }, - { url = "https://files.pythonhosted.org/packages/56/30/a6f08f84ee5b7b28b4c597aca4cbe545535c39fe911845a96414700b64ba/scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45", size = 35210199, upload-time = "2025-05-08T16:06:26.159Z" }, - { url = "https://files.pythonhosted.org/packages/0b/1f/03f52c282437a168ee2c7c14a1a0d0781a9a4a8962d84ac05c06b4c5b555/scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49", size = 37309455, upload-time = "2025-05-08T16:06:32.778Z" }, - { url = "https://files.pythonhosted.org/packages/89/b1/fbb53137f42c4bf630b1ffdfc2151a62d1d1b903b249f030d2b1c0280af8/scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e", size = 36885140, upload-time = "2025-05-08T16:06:39.249Z" }, - { url = "https://files.pythonhosted.org/packages/2e/2e/025e39e339f5090df1ff266d021892694dbb7e63568edcfe43f892fa381d/scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539", size = 39710549, upload-time = "2025-05-08T16:06:45.729Z" }, - { url = "https://files.pythonhosted.org/packages/e6/eb/3bf6ea8ab7f1503dca3a10df2e4b9c3f6b3316df07f6c0ded94b281c7101/scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed", size = 40966184, upload-time = "2025-05-08T16:06:52.623Z" }, - { url = "https://files.pythonhosted.org/packages/73/18/ec27848c9baae6e0d6573eda6e01a602e5649ee72c27c3a8aad673ebecfd/scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759", size = 38728256, upload-time = "2025-05-08T16:06:58.696Z" }, - { url = "https://files.pythonhosted.org/packages/74/cd/1aef2184948728b4b6e21267d53b3339762c285a46a274ebb7863c9e4742/scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62", size = 30109540, upload-time = "2025-05-08T16:07:04.209Z" }, - { url = "https://files.pythonhosted.org/packages/5b/d8/59e452c0a255ec352bd0a833537a3bc1bfb679944c4938ab375b0a6b3a3e/scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb", size = 22383115, upload-time = "2025-05-08T16:07:08.998Z" }, - { url = "https://files.pythonhosted.org/packages/08/f5/456f56bbbfccf696263b47095291040655e3cbaf05d063bdc7c7517f32ac/scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730", size = 25163884, upload-time = "2025-05-08T16:07:14.091Z" }, - { url = "https://files.pythonhosted.org/packages/a2/66/a9618b6a435a0f0c0b8a6d0a2efb32d4ec5a85f023c2b79d39512040355b/scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825", size = 35174018, upload-time = "2025-05-08T16:07:19.427Z" }, - { url = "https://files.pythonhosted.org/packages/b5/09/c5b6734a50ad4882432b6bb7c02baf757f5b2f256041da5df242e2d7e6b6/scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7", size = 37269716, upload-time = "2025-05-08T16:07:25.712Z" }, - { url = "https://files.pythonhosted.org/packages/77/0a/eac00ff741f23bcabd352731ed9b8995a0a60ef57f5fd788d611d43d69a1/scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11", size = 36872342, upload-time = "2025-05-08T16:07:31.468Z" }, - { url = "https://files.pythonhosted.org/packages/fe/54/4379be86dd74b6ad81551689107360d9a3e18f24d20767a2d5b9253a3f0a/scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126", size = 39670869, upload-time = "2025-05-08T16:07:38.002Z" }, - { url = "https://files.pythonhosted.org/packages/87/2e/892ad2862ba54f084ffe8cc4a22667eaf9c2bcec6d2bff1d15713c6c0703/scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163", size = 40988851, upload-time = "2025-05-08T16:08:33.671Z" }, - { url = "https://files.pythonhosted.org/packages/1b/e9/7a879c137f7e55b30d75d90ce3eb468197646bc7b443ac036ae3fe109055/scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8", size = 38863011, upload-time = "2025-05-08T16:07:44.039Z" }, - { url = "https://files.pythonhosted.org/packages/51/d1/226a806bbd69f62ce5ef5f3ffadc35286e9fbc802f606a07eb83bf2359de/scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5", size = 30266407, upload-time = "2025-05-08T16:07:49.891Z" }, - { url = "https://files.pythonhosted.org/packages/e5/9b/f32d1d6093ab9eeabbd839b0f7619c62e46cc4b7b6dbf05b6e615bbd4400/scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e", size = 22540030, upload-time = "2025-05-08T16:07:54.121Z" }, - { url = "https://files.pythonhosted.org/packages/e7/29/c278f699b095c1a884f29fda126340fcc201461ee8bfea5c8bdb1c7c958b/scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb", size = 25218709, upload-time = "2025-05-08T16:07:58.506Z" }, - { url = "https://files.pythonhosted.org/packages/24/18/9e5374b617aba742a990581373cd6b68a2945d65cc588482749ef2e64467/scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723", size = 34809045, upload-time = "2025-05-08T16:08:03.929Z" }, - { url = "https://files.pythonhosted.org/packages/e1/fe/9c4361e7ba2927074360856db6135ef4904d505e9b3afbbcb073c4008328/scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb", size = 36703062, upload-time = "2025-05-08T16:08:09.558Z" }, - { url = "https://files.pythonhosted.org/packages/b7/8e/038ccfe29d272b30086b25a4960f757f97122cb2ec42e62b460d02fe98e9/scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4", size = 36393132, upload-time = "2025-05-08T16:08:15.34Z" }, - { url = "https://files.pythonhosted.org/packages/10/7e/5c12285452970be5bdbe8352c619250b97ebf7917d7a9a9e96b8a8140f17/scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5", size = 38979503, upload-time = "2025-05-08T16:08:21.513Z" }, - { url = "https://files.pythonhosted.org/packages/81/06/0a5e5349474e1cbc5757975b21bd4fad0e72ebf138c5592f191646154e06/scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca", size = 40308097, upload-time = "2025-05-08T16:08:27.627Z" }, -] - [[package]] name = "scipy" version = "1.17.1" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", + "python_full_version < '3.12'", ] dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } wheels = [ @@ -5217,15 +4409,11 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.12' and python_full_version < '3.14'", ] dependencies = [ - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" } wheels = [ @@ -5277,13 +4465,10 @@ version = "5.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "huggingface-hub" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "scikit-learn", version = "1.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scikit-learn", version = "1.9.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "scikit-learn" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "scipy", version = "1.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "torch" }, { name = "tqdm" }, @@ -5301,14 +4486,6 @@ version = "0.2.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/15/15/2e7a025fc62d764b151ae6d0f2a92f8081755ebe8d4a64099accc6f77ba6/sentencepiece-0.2.1.tar.gz", hash = "sha256:8138cec27c2f2282f4a34d9a016e3374cd40e5c6e9cb335063db66a0a3b71fad", size = 3228515, upload-time = "2025-08-12T07:00:51.718Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/af/31/5b7cccb307b485db1a2372d6d2980b0a65d067f8be5ca943a103b4acd5b3/sentencepiece-0.2.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e10fa50bdbaa5e2445dbd387979980d391760faf0ec99a09bd7780ff37eaec44", size = 1942557, upload-time = "2025-08-12T06:59:12.379Z" }, - { url = "https://files.pythonhosted.org/packages/1f/41/0ac923a8e685ad290c5afc8ae55c5844977b8d75076fcc04302b9a324274/sentencepiece-0.2.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2f27ae6deea72efdb6f361750c92f6c21fd0ad087445082770cc34015213c526", size = 1325384, upload-time = "2025-08-12T06:59:14.334Z" }, - { url = "https://files.pythonhosted.org/packages/fc/ef/3751555d67daf9003384978f169d31c775cb5c7baf28633caaf1eb2b2b4d/sentencepiece-0.2.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:60937c959e6f44159fdd9f56fbdd302501f96114a5ba436829496d5f32d8de3f", size = 1253317, upload-time = "2025-08-12T06:59:16.247Z" }, - { url = "https://files.pythonhosted.org/packages/46/a5/742c69b7bd144eb32b6e5fd50dbd8abbbc7a95fce2fe16e50156fa400e3b/sentencepiece-0.2.1-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d8b1d91545578852f128650b8cce4ec20f93d39b378ff554ebe66290f2dabb92", size = 1316379, upload-time = "2025-08-12T06:59:17.825Z" }, - { url = "https://files.pythonhosted.org/packages/c8/89/8deeafbba2871e8fa10f20f17447786f4ac38085925335728d360eaf4cae/sentencepiece-0.2.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:27e38eee653abc3d387862e67bc5c8b6f428cd604e688b85d29170b7e725c26c", size = 1387926, upload-time = "2025-08-12T06:59:19.395Z" }, - { url = "https://files.pythonhosted.org/packages/c3/ca/67fe73005f0ab617c6a970b199754e28e524b6873aa7025224fad3cda252/sentencepiece-0.2.1-cp310-cp310-win32.whl", hash = "sha256:251874d720ac7f28024a168501f3c7bb15d1802245f6e66de565f18bbb9b5eaa", size = 999550, upload-time = "2025-08-12T06:59:20.844Z" }, - { url = "https://files.pythonhosted.org/packages/6d/33/dc5b54042050d2dda4229c3ce1f862541c99966390b6aa20f54d520d2dc2/sentencepiece-0.2.1-cp310-cp310-win_amd64.whl", hash = "sha256:e52144670738b4b477fade6c2a9b6af71a8d0094514c9853ac9f6fc1fcfabae7", size = 1054613, upload-time = "2025-08-12T06:59:22.255Z" }, - { url = "https://files.pythonhosted.org/packages/fa/19/1ea47f46ff97fe04422b78997da1a37cd632f414aae042d27a9009c5b733/sentencepiece-0.2.1-cp310-cp310-win_arm64.whl", hash = "sha256:9076430ac25dfa7147d9d05751dbc66a04bc1aaac371c07f84952979ea59f0d0", size = 1033884, upload-time = "2025-08-12T06:59:24.194Z" }, { url = "https://files.pythonhosted.org/packages/d8/15/46afbab00733d81788b64be430ca1b93011bb9388527958e26cc31832de5/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6356d0986b8b8dc351b943150fcd81a1c6e6e4d439772e8584c64230e58ca987", size = 1942560, upload-time = "2025-08-12T06:59:25.82Z" }, { url = "https://files.pythonhosted.org/packages/fa/79/7c01b8ef98a0567e9d84a4e7a910f8e7074fcbf398a5cd76f93f4b9316f9/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8f8ba89a3acb3dc1ae90f65ec1894b0b9596fdb98ab003ff38e058f898b39bc7", size = 1325385, upload-time = "2025-08-12T06:59:27.722Z" }, { url = "https://files.pythonhosted.org/packages/bb/88/2b41e07bd24f33dcf2f18ec3b74247aa4af3526bad8907b8727ea3caba03/sentencepiece-0.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:02593eca45440ef39247cee8c47322a34bdcc1d8ae83ad28ba5a899a2cf8d79a", size = 1253319, upload-time = "2025-08-12T06:59:29.306Z" }, @@ -5509,64 +4686,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fd/18/a545c4ea42af3df6effd7d13d250ba77a0a86fb20393143bbb9a92e434d4/tokenizers-0.22.2-cp39-abi3-win32.whl", hash = "sha256:a6bf3f88c554a2b653af81f3204491c818ae2ac6fbc09e76ef4773351292bc92", size = 2502363, upload-time = "2026-01-05T10:45:20.593Z" }, { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" }, { url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" }, - { url = "https://files.pythonhosted.org/packages/84/04/655b79dbcc9b3ac5f1479f18e931a344af67e5b7d3b251d2dcdcd7558592/tokenizers-0.22.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:753d47ebd4542742ef9261d9da92cd545b2cacbb48349a1225466745bb866ec4", size = 3282301, upload-time = "2026-01-05T10:40:34.858Z" }, - { url = "https://files.pythonhosted.org/packages/46/cd/e4851401f3d8f6f45d8480262ab6a5c8cb9c4302a790a35aa14eeed6d2fd/tokenizers-0.22.2-pp310-pypy310_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e10bf9113d209be7cd046d40fbabbaf3278ff6d18eb4da4c500443185dc1896c", size = 3161308, upload-time = "2026-01-05T10:40:40.737Z" }, - { url = "https://files.pythonhosted.org/packages/6f/6e/55553992a89982cd12d4a66dddb5e02126c58677ea3931efcbe601d419db/tokenizers-0.22.2-pp310-pypy310_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:64d94e84f6660764e64e7e0b22baa72f6cd942279fdbb21d46abd70d179f0195", size = 3718964, upload-time = "2026-01-05T10:40:46.56Z" }, - { url = "https://files.pythonhosted.org/packages/59/8c/b1c87148aa15e099243ec9f0cf9d0e970cc2234c3257d558c25a2c5304e6/tokenizers-0.22.2-pp310-pypy310_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f01a9c019878532f98927d2bacb79bbb404b43d3437455522a00a30718cdedb5", size = 3373542, upload-time = "2026-01-05T10:40:52.803Z" }, -] - -[[package]] -name = "tomli" -version = "2.4.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/22/de/48c59722572767841493b26183a0d1cc411d54fd759c5607c4590b6563a6/tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f", size = 17543, upload-time = "2026-03-25T20:22:03.828Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f4/11/db3d5885d8528263d8adc260bb2d28ebf1270b96e98f0e0268d32b8d9900/tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30", size = 154704, upload-time = "2026-03-25T20:21:10.473Z" }, - { url = "https://files.pythonhosted.org/packages/6d/f7/675db52c7e46064a9aa928885a9b20f4124ecb9bc2e1ce74c9106648d202/tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a", size = 149454, upload-time = "2026-03-25T20:21:12.036Z" }, - { url = "https://files.pythonhosted.org/packages/61/71/81c50943cf953efa35bce7646caab3cf457a7d8c030b27cfb40d7235f9ee/tomli-2.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96481a5786729fd470164b47cdb3e0e58062a496f455ee41b4403be77cb5a076", size = 237561, upload-time = "2026-03-25T20:21:13.098Z" }, - { url = "https://files.pythonhosted.org/packages/48/c1/f41d9cb618acccca7df82aaf682f9b49013c9397212cb9f53219e3abac37/tomli-2.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a881ab208c0baf688221f8cecc5401bd291d67e38a1ac884d6736cbcd8247e9", size = 243824, upload-time = "2026-03-25T20:21:14.569Z" }, - { url = "https://files.pythonhosted.org/packages/22/e4/5a816ecdd1f8ca51fb756ef684b90f2780afc52fc67f987e3c61d800a46d/tomli-2.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:47149d5bd38761ac8be13a84864bf0b7b70bc051806bc3669ab1cbc56216b23c", size = 242227, upload-time = "2026-03-25T20:21:15.712Z" }, - { url = "https://files.pythonhosted.org/packages/6b/49/2b2a0ef529aa6eec245d25f0c703e020a73955ad7edf73e7f54ddc608aa5/tomli-2.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ec9bfaf3ad2df51ace80688143a6a4ebc09a248f6ff781a9945e51937008fcbc", size = 247859, upload-time = "2026-03-25T20:21:17.001Z" }, - { url = "https://files.pythonhosted.org/packages/83/bd/6c1a630eaca337e1e78c5903104f831bda934c426f9231429396ce3c3467/tomli-2.4.1-cp311-cp311-win32.whl", hash = "sha256:ff2983983d34813c1aeb0fa89091e76c3a22889ee83ab27c5eeb45100560c049", size = 97204, upload-time = "2026-03-25T20:21:18.079Z" }, - { url = "https://files.pythonhosted.org/packages/42/59/71461df1a885647e10b6bb7802d0b8e66480c61f3f43079e0dcd315b3954/tomli-2.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:5ee18d9ebdb417e384b58fe414e8d6af9f4e7a0ae761519fb50f721de398dd4e", size = 108084, upload-time = "2026-03-25T20:21:18.978Z" }, - { url = "https://files.pythonhosted.org/packages/b8/83/dceca96142499c069475b790e7913b1044c1a4337e700751f48ed723f883/tomli-2.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:c2541745709bad0264b7d4705ad453b76ccd191e64aa6f0fc66b69a293a45ece", size = 95285, upload-time = "2026-03-25T20:21:20.309Z" }, - { url = "https://files.pythonhosted.org/packages/c1/ba/42f134a3fe2b370f555f44b1d72feebb94debcab01676bf918d0cb70e9aa/tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a", size = 155924, upload-time = "2026-03-25T20:21:21.626Z" }, - { url = "https://files.pythonhosted.org/packages/dc/c7/62d7a17c26487ade21c5422b646110f2162f1fcc95980ef7f63e73c68f14/tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085", size = 150018, upload-time = "2026-03-25T20:21:23.002Z" }, - { url = "https://files.pythonhosted.org/packages/5c/05/79d13d7c15f13bdef410bdd49a6485b1c37d28968314eabee452c22a7fda/tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9", size = 244948, upload-time = "2026-03-25T20:21:24.04Z" }, - { url = "https://files.pythonhosted.org/packages/10/90/d62ce007a1c80d0b2c93e02cab211224756240884751b94ca72df8a875ca/tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5", size = 253341, upload-time = "2026-03-25T20:21:25.177Z" }, - { url = "https://files.pythonhosted.org/packages/1a/7e/caf6496d60152ad4ed09282c1885cca4eea150bfd007da84aea07bcc0a3e/tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585", size = 248159, upload-time = "2026-03-25T20:21:26.364Z" }, - { url = "https://files.pythonhosted.org/packages/99/e7/c6f69c3120de34bbd882c6fba7975f3d7a746e9218e56ab46a1bc4b42552/tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1", size = 253290, upload-time = "2026-03-25T20:21:27.46Z" }, - { url = "https://files.pythonhosted.org/packages/d6/2f/4a3c322f22c5c66c4b836ec58211641a4067364f5dcdd7b974b4c5da300c/tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917", size = 98141, upload-time = "2026-03-25T20:21:28.492Z" }, - { url = "https://files.pythonhosted.org/packages/24/22/4daacd05391b92c55759d55eaee21e1dfaea86ce5c571f10083360adf534/tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9", size = 108847, upload-time = "2026-03-25T20:21:29.386Z" }, - { url = "https://files.pythonhosted.org/packages/68/fd/70e768887666ddd9e9f5d85129e84910f2db2796f9096aa02b721a53098d/tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257", size = 95088, upload-time = "2026-03-25T20:21:30.677Z" }, - { url = "https://files.pythonhosted.org/packages/07/06/b823a7e818c756d9a7123ba2cda7d07bc2dd32835648d1a7b7b7a05d848d/tomli-2.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:36d2bd2ad5fb9eaddba5226aa02c8ec3fa4f192631e347b3ed28186d43be6b54", size = 155866, upload-time = "2026-03-25T20:21:31.65Z" }, - { url = "https://files.pythonhosted.org/packages/14/6f/12645cf7f08e1a20c7eb8c297c6f11d31c1b50f316a7e7e1e1de6e2e7b7e/tomli-2.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eb0dc4e38e6a1fd579e5d50369aa2e10acfc9cace504579b2faabb478e76941a", size = 149887, upload-time = "2026-03-25T20:21:33.028Z" }, - { url = "https://files.pythonhosted.org/packages/5c/e0/90637574e5e7212c09099c67ad349b04ec4d6020324539297b634a0192b0/tomli-2.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7f2c7f2b9ca6bdeef8f0fa897f8e05085923eb091721675170254cbc5b02897", size = 243704, upload-time = "2026-03-25T20:21:34.51Z" }, - { url = "https://files.pythonhosted.org/packages/10/8f/d3ddb16c5a4befdf31a23307f72828686ab2096f068eaf56631e136c1fdd/tomli-2.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f3c6818a1a86dd6dca7ddcaaf76947d5ba31aecc28cb1b67009a5877c9a64f3f", size = 251628, upload-time = "2026-03-25T20:21:36.012Z" }, - { url = "https://files.pythonhosted.org/packages/e3/f1/dbeeb9116715abee2485bf0a12d07a8f31af94d71608c171c45f64c0469d/tomli-2.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d312ef37c91508b0ab2cee7da26ec0b3ed2f03ce12bd87a588d771ae15dcf82d", size = 247180, upload-time = "2026-03-25T20:21:37.136Z" }, - { url = "https://files.pythonhosted.org/packages/d3/74/16336ffd19ed4da28a70959f92f506233bd7cfc2332b20bdb01591e8b1d1/tomli-2.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:51529d40e3ca50046d7606fa99ce3956a617f9b36380da3b7f0dd3dd28e68cb5", size = 251674, upload-time = "2026-03-25T20:21:38.298Z" }, - { url = "https://files.pythonhosted.org/packages/16/f9/229fa3434c590ddf6c0aa9af64d3af4b752540686cace29e6281e3458469/tomli-2.4.1-cp313-cp313-win32.whl", hash = "sha256:2190f2e9dd7508d2a90ded5ed369255980a1bcdd58e52f7fe24b8162bf9fedbd", size = 97976, upload-time = "2026-03-25T20:21:39.316Z" }, - { url = "https://files.pythonhosted.org/packages/6a/1e/71dfd96bcc1c775420cb8befe7a9d35f2e5b1309798f009dca17b7708c1e/tomli-2.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d65a2fbf9d2f8352685bc1364177ee3923d6baf5e7f43ea4959d7d8bc326a36", size = 108755, upload-time = "2026-03-25T20:21:40.248Z" }, - { url = "https://files.pythonhosted.org/packages/83/7a/d34f422a021d62420b78f5c538e5b102f62bea616d1d75a13f0a88acb04a/tomli-2.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:4b605484e43cdc43f0954ddae319fb75f04cc10dd80d830540060ee7cd0243cd", size = 95265, upload-time = "2026-03-25T20:21:41.219Z" }, - { url = "https://files.pythonhosted.org/packages/3c/fb/9a5c8d27dbab540869f7c1f8eb0abb3244189ce780ba9cd73f3770662072/tomli-2.4.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fd0409a3653af6c147209d267a0e4243f0ae46b011aa978b1080359fddc9b6cf", size = 155726, upload-time = "2026-03-25T20:21:42.23Z" }, - { url = "https://files.pythonhosted.org/packages/62/05/d2f816630cc771ad836af54f5001f47a6f611d2d39535364f148b6a92d6b/tomli-2.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a120733b01c45e9a0c34aeef92bf0cf1d56cfe81ed9d47d562f9ed591a9828ac", size = 149859, upload-time = "2026-03-25T20:21:43.386Z" }, - { url = "https://files.pythonhosted.org/packages/ce/48/66341bdb858ad9bd0ceab5a86f90eddab127cf8b046418009f2125630ecb/tomli-2.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:559db847dc486944896521f68d8190be1c9e719fced785720d2216fe7022b662", size = 244713, upload-time = "2026-03-25T20:21:44.474Z" }, - { url = "https://files.pythonhosted.org/packages/df/6d/c5fad00d82b3c7a3ab6189bd4b10e60466f22cfe8a08a9394185c8a8111c/tomli-2.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01f520d4f53ef97964a240a035ec2a869fe1a37dde002b57ebc4417a27ccd853", size = 252084, upload-time = "2026-03-25T20:21:45.62Z" }, - { url = "https://files.pythonhosted.org/packages/00/71/3a69e86f3eafe8c7a59d008d245888051005bd657760e96d5fbfb0b740c2/tomli-2.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f94b27a62cfad8496c8d2513e1a222dd446f095fca8987fceef261225538a15", size = 247973, upload-time = "2026-03-25T20:21:46.937Z" }, - { url = "https://files.pythonhosted.org/packages/67/50/361e986652847fec4bd5e4a0208752fbe64689c603c7ae5ea7cb16b1c0ca/tomli-2.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede3e6487c5ef5d28634ba3f31f989030ad6af71edfb0055cbbd14189ff240ba", size = 256223, upload-time = "2026-03-25T20:21:48.467Z" }, - { url = "https://files.pythonhosted.org/packages/8c/9a/b4173689a9203472e5467217e0154b00e260621caa227b6fa01feab16998/tomli-2.4.1-cp314-cp314-win32.whl", hash = "sha256:3d48a93ee1c9b79c04bb38772ee1b64dcf18ff43085896ea460ca8dec96f35f6", size = 98973, upload-time = "2026-03-25T20:21:49.526Z" }, - { url = "https://files.pythonhosted.org/packages/14/58/640ac93bf230cd27d002462c9af0d837779f8773bc03dee06b5835208214/tomli-2.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:88dceee75c2c63af144e456745e10101eb67361050196b0b6af5d717254dddf7", size = 109082, upload-time = "2026-03-25T20:21:50.506Z" }, - { url = "https://files.pythonhosted.org/packages/d5/2f/702d5e05b227401c1068f0d386d79a589bb12bf64c3d2c72ce0631e3bc49/tomli-2.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:b8c198f8c1805dc42708689ed6864951fd2494f924149d3e4bce7710f8eb5232", size = 96490, upload-time = "2026-03-25T20:21:51.474Z" }, - { url = "https://files.pythonhosted.org/packages/45/4b/b877b05c8ba62927d9865dd980e34a755de541eb65fffba52b4cc495d4d2/tomli-2.4.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d4d8fe59808a54658fcc0160ecfb1b30f9089906c50b23bcb4c69eddc19ec2b4", size = 164263, upload-time = "2026-03-25T20:21:52.543Z" }, - { url = "https://files.pythonhosted.org/packages/24/79/6ab420d37a270b89f7195dec5448f79400d9e9c1826df982f3f8e97b24fd/tomli-2.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7008df2e7655c495dd12d2a4ad038ff878d4ca4b81fccaf82b714e07eae4402c", size = 160736, upload-time = "2026-03-25T20:21:53.674Z" }, - { url = "https://files.pythonhosted.org/packages/02/e0/3630057d8eb170310785723ed5adcdfb7d50cb7e6455f85ba8a3deed642b/tomli-2.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d8591993e228b0c930c4bb0db464bdad97b3289fb981255d6c9a41aedc84b2d", size = 270717, upload-time = "2026-03-25T20:21:55.129Z" }, - { url = "https://files.pythonhosted.org/packages/7a/b4/1613716072e544d1a7891f548d8f9ec6ce2faf42ca65acae01d76ea06bb0/tomli-2.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:734e20b57ba95624ecf1841e72b53f6e186355e216e5412de414e3c51e5e3c41", size = 278461, upload-time = "2026-03-25T20:21:56.228Z" }, - { url = "https://files.pythonhosted.org/packages/05/38/30f541baf6a3f6df77b3df16b01ba319221389e2da59427e221ef417ac0c/tomli-2.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8a650c2dbafa08d42e51ba0b62740dae4ecb9338eefa093aa5c78ceb546fcd5c", size = 274855, upload-time = "2026-03-25T20:21:57.653Z" }, - { url = "https://files.pythonhosted.org/packages/77/a3/ec9dd4fd2c38e98de34223b995a3b34813e6bdadf86c75314c928350ed14/tomli-2.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:504aa796fe0569bb43171066009ead363de03675276d2d121ac1a4572397870f", size = 283144, upload-time = "2026-03-25T20:21:59.089Z" }, - { url = "https://files.pythonhosted.org/packages/ef/be/605a6261cac79fba2ec0c9827e986e00323a1945700969b8ee0b30d85453/tomli-2.4.1-cp314-cp314t-win32.whl", hash = "sha256:b1d22e6e9387bf4739fbe23bfa80e93f6b0373a7f1b96c6227c32bef95a4d7a8", size = 108683, upload-time = "2026-03-25T20:22:00.214Z" }, - { url = "https://files.pythonhosted.org/packages/12/64/da524626d3b9cc40c168a13da8335fe1c51be12c0a63685cc6db7308daae/tomli-2.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:2c1c351919aca02858f740c6d33adea0c5deea37f9ecca1cc1ef9e884a619d26", size = 121196, upload-time = "2026-03-25T20:22:01.169Z" }, - { url = "https://files.pythonhosted.org/packages/5a/cd/e80b62269fc78fc36c9af5a6b89c835baa8af28ff5ad28c7028d60860320/tomli-2.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:eab21f45c7f66c13f2a9e0e1535309cee140182a9cdae1e041d02e47291e8396", size = 100393, upload-time = "2026-03-25T20:22:02.137Z" }, - { url = "https://files.pythonhosted.org/packages/7b/61/cceae43728b7de99d9b847560c262873a1f6c98202171fd5ed62640b494b/tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe", size = 14583, upload-time = "2026-03-25T20:22:03.012Z" }, ] [[package]] @@ -5579,8 +4698,7 @@ dependencies = [ { name = "filelock" }, { name = "fsspec" }, { name = "jinja2" }, - { name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "networkx", version = "3.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "networkx" }, { name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'" }, { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux'" }, { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux'" }, @@ -5591,10 +4709,6 @@ dependencies = [ { name = "typing-extensions" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/ac/f2/c1690994afe461aae2d0cac62251e6802a703dec0a6c549c02ecd0de92a9/torch-2.11.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2c0d7fcfbc0c4e8bb5ebc3907cbc0c6a0da1b8f82b1fc6e14e914fa0b9baf74e", size = 80526521, upload-time = "2026-03-23T18:12:06.86Z" }, - { url = "https://files.pythonhosted.org/packages/a4/f0/98ae802fa8c09d3149b0c8690741f3f5753c90e779bd28c9613257295945/torch-2.11.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:4cf8687f4aec3900f748d553483ef40e0ac38411c3c48d0a86a438f6d7a99b18", size = 419723025, upload-time = "2026-03-23T18:11:43.774Z" }, - { url = "https://files.pythonhosted.org/packages/f9/1e/18a9b10b4bd34f12d4e561c52b0ae7158707b8193c6cfc0aad2b48167090/torch-2.11.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:1b32ceda909818a03b112006709b02be1877240c31750a8d9c6b7bf5f2d8a6e5", size = 530589207, upload-time = "2026-03-23T18:11:23.756Z" }, - { url = "https://files.pythonhosted.org/packages/35/40/2d532e8c0e23705be9d1debce5bc37b68d59a39bda7584c26fe9668076fe/torch-2.11.0-cp310-cp310-win_amd64.whl", hash = "sha256:b3c712ae6fb8e7a949051a953fc412fe0a6940337336c3b6f905e905dac5157f", size = 114518313, upload-time = "2026-03-23T18:11:58.281Z" }, { url = "https://files.pythonhosted.org/packages/ae/0d/98b410492609e34a155fa8b121b55c7dca229f39636851c3a9ec20edea21/torch-2.11.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7b6a60d48062809f58595509c524b88e6ddec3ebe25833d6462eeab81e5f2ce4", size = 80529712, upload-time = "2026-03-23T18:12:02.608Z" }, { url = "https://files.pythonhosted.org/packages/84/03/acea680005f098f79fd70c1d9d5ccc0cb4296ec2af539a0450108232fc0c/torch-2.11.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:d91aac77f24082809d2c5a93f52a5f085032740a1ebc9252a7b052ef5a4fddc6", size = 419718178, upload-time = "2026-03-23T18:10:46.675Z" }, { url = "https://files.pythonhosted.org/packages/8c/8b/d7be22fbec9ffee6cff31a39f8750d4b3a65d349a286cf4aec74c2375662/torch-2.11.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:7aa2f9bbc6d4595ba72138026b2074be1233186150e9292865e04b7a63b8c67a", size = 530604548, upload-time = "2026-03-23T18:10:03.569Z" }, @@ -5626,17 +4740,12 @@ name = "torchvision" version = "0.26.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "pillow" }, { name = "torch" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/74/b4/cdfee31e0402ea035135462cb0ab496e974d56fab6b4e7a1f0cbccb8cd28/torchvision-0.26.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a06d4772a8e13e772906ed736cc53ec6639e5e60554f8e5fa6ca165aabebc464", size = 1863503, upload-time = "2026-03-23T18:13:01.384Z" }, - { url = "https://files.pythonhosted.org/packages/e4/74/11fee109841e80ad14e5ca2d80bff6b10eb11b7838ff06f35bfeaa9f7251/torchvision-0.26.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:2adfbe438473236191ff077a4a9a0c767436879c89628aa97137e959b0c11a94", size = 7766423, upload-time = "2026-03-23T18:12:56.049Z" }, - { url = "https://files.pythonhosted.org/packages/5e/00/24d8c7845c3f270153fb81395a5135b2778e2538e81d14c6aea5106c689c/torchvision-0.26.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:b6f9ad1ecc0eab52647298b379ee9426845f8903703e6127973f8f3d049a798b", size = 7518249, upload-time = "2026-03-23T18:12:51.743Z" }, - { url = "https://files.pythonhosted.org/packages/d7/ed/e53cd7c0da7ae002e5e929c1796ebbe7ec0c700c29f7a0a6696497fb3d8b/torchvision-0.26.0-cp310-cp310-win_amd64.whl", hash = "sha256:f13f12b3791a266de2d599cb8162925261622a037d87fc03132848343cf68f75", size = 3669784, upload-time = "2026-03-23T18:12:49.949Z" }, { url = "https://files.pythonhosted.org/packages/b4/bd/d552a2521bade3295b2c6e7a4a0d1022261cab7ca7011f4e2a330dbb3caa/torchvision-0.26.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:55bd6ad4ae77be01ba67a410b05b51f53b0d0ee45f146eb6a0dfb9007e70ab3c", size = 1863499, upload-time = "2026-03-23T18:12:58.696Z" }, { url = "https://files.pythonhosted.org/packages/33/bf/21b899792b08cae7a298551c68398a79e333697479ed311b3b067aab4bdc/torchvision-0.26.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:1c55dc8affbcc0eb2060fbabbe996ae9e5839b24bb6419777f17848945a411b1", size = 7767527, upload-time = "2026-03-23T18:12:44.348Z" }, { url = "https://files.pythonhosted.org/packages/9a/45/57bbf9e216850d065e66dd31a50f57424b607f1d878ab8956e56a1f4e36b/torchvision-0.26.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:fd10b5f994c210f4f6d6761cf686f82d748554adf486cb0979770c3252868c8f", size = 7519925, upload-time = "2026-03-23T18:12:53.283Z" }, @@ -5707,8 +4816,7 @@ version = "5.13.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "huggingface-hub" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "packaging" }, { name = "pyyaml" }, @@ -5728,8 +4836,6 @@ name = "triton" version = "3.6.0" source = { registry = "https://pypi.org/simple" } wheels = [ - { url = "https://files.pythonhosted.org/packages/44/ba/b1b04f4b291a3205d95ebd24465de0e5bf010a2df27a4e58a9b5f039d8f2/triton-3.6.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6c723cfb12f6842a0ae94ac307dba7e7a44741d720a40cf0e270ed4a4e3be781", size = 175972180, upload-time = "2026-01-20T16:15:53.664Z" }, - { url = "https://files.pythonhosted.org/packages/8c/f7/f1c9d3424ab199ac53c2da567b859bcddbb9c9e7154805119f8bd95ec36f/triton-3.6.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a6550fae429e0667e397e5de64b332d1e5695b73650ee75a6146e2e902770bea", size = 188105201, upload-time = "2026-01-20T16:00:29.272Z" }, { url = "https://files.pythonhosted.org/packages/0f/2c/96f92f3c60387e14cc45aed49487f3486f89ea27106c1b1376913c62abe4/triton-3.6.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49df5ef37379c0c2b5c0012286f80174fcf0e073e5ade1ca9a86c36814553651", size = 176081190, upload-time = "2026-01-20T16:16:00.523Z" }, { url = "https://files.pythonhosted.org/packages/e0/12/b05ba554d2c623bffa59922b94b0775673de251f468a9609bc9e45de95e9/triton-3.6.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e8e323d608e3a9bfcc2d9efcc90ceefb764a82b99dea12a86d643c72539ad5d3", size = 188214640, upload-time = "2026-01-20T16:00:35.869Z" }, { url = "https://files.pythonhosted.org/packages/17/5d/08201db32823bdf77a0e2b9039540080b2e5c23a20706ddba942924ebcd6/triton-3.6.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:374f52c11a711fd062b4bfbb201fd9ac0a5febd28a96fb41b4a0f51dde3157f4", size = 176128243, upload-time = "2026-01-20T16:16:07.857Z" }, @@ -5803,11 +4909,11 @@ wheels = [ [[package]] name = "urllib3" -version = "2.7.0" +version = "2.8.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" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, ] [[package]] @@ -5819,7 +4925,6 @@ dependencies = [ { name = "filelock" }, { name = "platformdirs" }, { name = "python-discovery" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/74/65/ec1d92091671e6407d3e7c1f5801413bb7b2b57630a50cae7750456ba0ed/virtualenv-21.6.0.tar.gz", hash = "sha256:e18a4d750f2b64dea73e72ffde3922f3c52365fabdc8157ebd3da20d031c4734", size = 5526111, upload-time = "2026-07-06T22:49:56.972Z" } wheels = [ @@ -5832,9 +4937,6 @@ 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/0c/56/90994d789c61df619bfc5ce2ecdabd5eeff564e1eb47512bd01b5e019569/watchdog-6.0.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d1cdb490583ebd691c012b3d6dae011000fe42edb7a82ece80965b42abd61f26", size = 96390, upload-time = "2024-11-01T14:06:24.793Z" }, - { url = "https://files.pythonhosted.org/packages/55/46/9a67ee697342ddf3c6daa97e3a587a56d6c4052f881ed926a849fcf7371c/watchdog-6.0.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bc64ab3bdb6a04d69d4023b29422170b74681784ffb9463ed4870cf2f3e66112", size = 88389, upload-time = "2024-11-01T14:06:27.112Z" }, - { url = "https://files.pythonhosted.org/packages/44/65/91b0985747c52064d8701e1075eb96f8c40a79df889e59a399453adfb882/watchdog-6.0.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c897ac1b55c5a1461e16dae288d22bb2e412ba9807df8397a635d88f671d36c3", size = 89020, upload-time = "2024-11-01T14:06:29.876Z" }, { url = "https://files.pythonhosted.org/packages/e0/24/d9be5cd6642a6aa68352ded4b4b10fb0d7889cb7f45814fb92cecd35f101/watchdog-6.0.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6eb11feb5a0d452ee41f824e271ca311a09e250441c262ca2fd7ebcf2461a06c", size = 96393, upload-time = "2024-11-01T14:06:31.756Z" }, { url = "https://files.pythonhosted.org/packages/63/7a/6013b0d8dbc56adca7fdd4f0beed381c59f6752341b12fa0886fa7afc78b/watchdog-6.0.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ef810fbf7b781a5a593894e4f439773830bdecb885e6880d957d5b9382a960d2", size = 88392, upload-time = "2024-11-01T14:06:32.99Z" }, { url = "https://files.pythonhosted.org/packages/d1/40/b75381494851556de56281e053700e46bff5b37bf4c7267e858640af5a7f/watchdog-6.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:afd0fe1b2270917c5e23c2a65ce50c2a4abb63daafb0d419fde368e272a76b7c", size = 89019, upload-time = "2024-11-01T14:06:34.963Z" }, @@ -5844,8 +4946,6 @@ wheels = [ { 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/30/ad/d17b5d42e28a8b91f8ed01cb949da092827afb9995d4559fd448d0472763/watchdog-6.0.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:c7ac31a19f4545dd92fc25d200694098f42c9a8e391bc00bdd362c5736dbf881", size = 87902, upload-time = "2024-11-01T14:06:53.119Z" }, - { url = "https://files.pythonhosted.org/packages/5c/ca/c3649991d140ff6ab67bfc85ab42b165ead119c9e12211e08089d763ece5/watchdog-6.0.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:9513f27a1a582d9808cf21a07dae516f0fab1cf2d7683a742c498b93eedabb11", size = 88380, upload-time = "2024-11-01T14:06:55.19Z" }, { 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" }, @@ -5882,15 +4982,6 @@ version = "16.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/04/24/4b2031d72e840ce4c1ccb255f693b15c334757fc50023e4db9537080b8c4/websockets-16.0.tar.gz", hash = "sha256:5f6261a5e56e8d5c42a4497b364ea24d94d9563e8fbd44e78ac40879c60179b5", size = 179346, upload-time = "2026-01-10T09:23:47.181Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/20/74/221f58decd852f4b59cc3354cccaf87e8ef695fede361d03dc9a7396573b/websockets-16.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:04cdd5d2d1dacbad0a7bf36ccbcd3ccd5a30ee188f2560b7a62a30d14107b31a", size = 177343, upload-time = "2026-01-10T09:22:21.28Z" }, - { url = "https://files.pythonhosted.org/packages/19/0f/22ef6107ee52ab7f0b710d55d36f5a5d3ef19e8a205541a6d7ffa7994e5a/websockets-16.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:8ff32bb86522a9e5e31439a58addbb0166f0204d64066fb955265c4e214160f0", size = 175021, upload-time = "2026-01-10T09:22:22.696Z" }, - { url = "https://files.pythonhosted.org/packages/10/40/904a4cb30d9b61c0e278899bf36342e9b0208eb3c470324a9ecbaac2a30f/websockets-16.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:583b7c42688636f930688d712885cf1531326ee05effd982028212ccc13e5957", size = 175320, upload-time = "2026-01-10T09:22:23.94Z" }, - { url = "https://files.pythonhosted.org/packages/9d/2f/4b3ca7e106bc608744b1cdae041e005e446124bebb037b18799c2d356864/websockets-16.0-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:7d837379b647c0c4c2355c2499723f82f1635fd2c26510e1f587d89bc2199e72", size = 183815, upload-time = "2026-01-10T09:22:25.469Z" }, - { url = "https://files.pythonhosted.org/packages/86/26/d40eaa2a46d4302becec8d15b0fc5e45bdde05191e7628405a19cf491ccd/websockets-16.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:df57afc692e517a85e65b72e165356ed1df12386ecb879ad5693be08fac65dde", size = 185054, upload-time = "2026-01-10T09:22:27.101Z" }, - { url = "https://files.pythonhosted.org/packages/b0/ba/6500a0efc94f7373ee8fefa8c271acdfd4dca8bd49a90d4be7ccabfc397e/websockets-16.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:2b9f1e0d69bc60a4a87349d50c09a037a2607918746f07de04df9e43252c77a3", size = 184565, upload-time = "2026-01-10T09:22:28.293Z" }, - { url = "https://files.pythonhosted.org/packages/04/b4/96bf2cee7c8d8102389374a2616200574f5f01128d1082f44102140344cc/websockets-16.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:335c23addf3d5e6a8633f9f8eda77efad001671e80b95c491dd0924587ece0b3", size = 183848, upload-time = "2026-01-10T09:22:30.394Z" }, - { url = "https://files.pythonhosted.org/packages/02/8e/81f40fb00fd125357814e8c3025738fc4ffc3da4b6b4a4472a82ba304b41/websockets-16.0-cp310-cp310-win32.whl", hash = "sha256:37b31c1623c6605e4c00d466c9d633f9b812ea430c11c8a278774a1fde1acfa9", size = 178249, upload-time = "2026-01-10T09:22:32.083Z" }, - { url = "https://files.pythonhosted.org/packages/b4/5f/7e40efe8df57db9b91c88a43690ac66f7b7aa73a11aa6a66b927e44f26fa/websockets-16.0-cp310-cp310-win_amd64.whl", hash = "sha256:8e1dab317b6e77424356e11e99a432b7cb2f3ec8c5ab4dabbcee6add48f72b35", size = 178685, upload-time = "2026-01-10T09:22:33.345Z" }, { url = "https://files.pythonhosted.org/packages/f2/db/de907251b4ff46ae804ad0409809504153b3f30984daf82a1d84a9875830/websockets-16.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:31a52addea25187bde0797a97d6fc3d2f92b6f72a9370792d65a6e84615ac8a8", size = 177340, upload-time = "2026-01-10T09:22:34.539Z" }, { url = "https://files.pythonhosted.org/packages/f3/fa/abe89019d8d8815c8781e90d697dec52523fb8ebe308bf11664e8de1877e/websockets-16.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:417b28978cdccab24f46400586d128366313e8a96312e4b9362a4af504f3bbad", size = 175022, upload-time = "2026-01-10T09:22:36.332Z" }, { url = "https://files.pythonhosted.org/packages/58/5d/88ea17ed1ded2079358b40d31d48abe90a73c9e5819dbcde1606e991e2ad/websockets-16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:af80d74d4edfa3cb9ed973a0a5ba2b2a549371f8a741e0800cb07becdd20f23d", size = 175319, upload-time = "2026-01-10T09:22:37.602Z" }, @@ -5955,23 +5046,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/79/12/1e8f37460ea0f7eb59c221fdaf0ed75e7ac43e97f8093b9c6f411df50a78/yarl-1.24.2.tar.gz", hash = "sha256:9ac374123c6fd7abf64d1fec93962b0bd4ee2c19751755a762a72dd96c0378f8", size = 210798, upload-time = "2026-05-19T21:31:05.599Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3f/df/f1c7a3de0831cd83194f1a85c5bb431b13f81e6b45079314c86d1c4ef3f2/yarl-1.24.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:5249a113065c2b7a958bc699759e359cd61cfc81e3069662208f48f191b7ed12", size = 129057, upload-time = "2026-05-19T21:27:47.564Z" }, - { url = "https://files.pythonhosted.org/packages/48/41/7daafb32dd7562bf45b1ce56562e7e1a9146f6479b6456873eb8a3413c40/yarl-1.24.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7f4425fa244fbf530b006d0c5f79ce920114cfff5b4f5f6056e669f8e160fdc0", size = 91545, upload-time = "2026-05-19T21:27:50.089Z" }, - { url = "https://files.pythonhosted.org/packages/a8/8f/7b3ec212f1ea0683f55f978e3246bc313c38818664edfc97a9f349a4901e/yarl-1.24.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:15c0b5e49d3c44e2a0b93e6a49476c5edad0a7686b92c395765a7ea775572a75", size = 91380, upload-time = "2026-05-19T21:27:51.953Z" }, - { url = "https://files.pythonhosted.org/packages/8a/1b/8bafab7db23b0567ae9db749099b329d91e3b82bc6028b2050ba583e116c/yarl-1.24.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:246d32a53a947c8f0189f5d699cbd4c7036de45d9359e13ba238d1239678c727", size = 105957, upload-time = "2026-05-19T21:27:53.98Z" }, - { url = "https://files.pythonhosted.org/packages/7f/77/21030c2f8d21d21559719beafc772ada2014be933418ed1eaed9cc800e42/yarl-1.24.2-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:64480fb3e4d4ed9ed71c48a91a477384fc342a50ca30071d2f8a88d51d9c9413", size = 97242, upload-time = "2026-05-19T21:27:55.981Z" }, - { url = "https://files.pythonhosted.org/packages/50/d8/f9ea63d1b6aa910a866e089d871fff6cbd49caab29b86b35221a62dfa0d5/yarl-1.24.2-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:349de4701dc3760b6e876628423a8f147ef4f5599d10aba1e10702075d424ed9", size = 114719, upload-time = "2026-05-19T21:27:58.037Z" }, - { url = "https://files.pythonhosted.org/packages/e9/a3/04e0ee98ac58a249ea7ed75223f5f901ba81a834f0b4921b58e5cec11757/yarl-1.24.2-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d162677af8d5d3d6ebab8394b021f4d041ac107a4b705873148a77a49dc9e1b2", size = 112140, upload-time = "2026-05-19T21:27:59.618Z" }, - { url = "https://files.pythonhosted.org/packages/02/ad/0b9cc9f38a7324a7eb1d80f834eaa5283d17e9271bbda3186e598dddaeac/yarl-1.24.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f5f5c6ec23a9043f2d139cc072f53dd23168d202a334b9b2fda8de4c3e890d90", size = 106721, upload-time = "2026-05-19T21:28:02.586Z" }, - { url = "https://files.pythonhosted.org/packages/65/e7/a52478ebfc66ec989e085c6ae038b9f1bfa4190baa193b133b669c709e2f/yarl-1.24.2-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:60de6742447fbbf697f16f070b8a443f1b5fe6ca3826fbef9fe70ecd5328e643", size = 106478, upload-time = "2026-05-19T21:28:04.523Z" }, - { url = "https://files.pythonhosted.org/packages/04/d8/5508530fea8472542de00013ae280765fc938ee196fc4030c43a498afb36/yarl-1.24.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:acf93187c3710e422368eb768aee98db551ec7c85adc250207a95c16548ab7ac", size = 105423, upload-time = "2026-05-19T21:28:06.515Z" }, - { url = "https://files.pythonhosted.org/packages/84/f1/ece28505e9628e8b756e11bb4f28864a17cc33b6b44db4d2aaf0622bf630/yarl-1.24.2-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:f4b0352fd41fd34b6651934606268816afd6914d09626f9bcbbf018edb0afb3f", size = 99878, upload-time = "2026-05-19T21:28:08.637Z" }, - { url = "https://files.pythonhosted.org/packages/3f/52/fb5d34529b46dd84013afcfb30b8d2bc2832ed03d412736f577d604fa393/yarl-1.24.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:6b208bb939099b4b297438da4e9b25357f0b1c791888669b963e45b203ea9f36", size = 114025, upload-time = "2026-05-19T21:28:10.64Z" }, - { url = "https://files.pythonhosted.org/packages/43/f0/ff9d31aaab024f7a251c0ed308a98ae29bf9f7dc344e78f28b1322431ca2/yarl-1.24.2-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:4b85b8825e631295ff4bc8943f7471d54c533a9360bbe15ebb38e018b555bb8a", size = 105613, upload-time = "2026-05-19T21:28:12.784Z" }, - { url = "https://files.pythonhosted.org/packages/31/7d/3296fb3f3ecd52bf9ae6c16b0895c1cda7e9170a2083861552b683f70264/yarl-1.24.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:e26acf20c26cb4fefc631fdb75aca2a6b8fa8b7b5d7f204fb6a8f1e63c706f53", size = 111665, upload-time = "2026-05-19T21:28:14.393Z" }, - { url = "https://files.pythonhosted.org/packages/1a/74/77aa6ddaca4fbf42e45e675a465c43956dd40702281049975a2aa04eae59/yarl-1.24.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:819ca24f8eafcfb683c1bd5f44f2f488cea1274eb8944731ffd2e1f10f619342", size = 106914, upload-time = "2026-05-19T21:28:15.893Z" }, - { url = "https://files.pythonhosted.org/packages/d8/02/7611f22cd1d4ed7373eb7f9ee21fde1046edba2e7c0e514880d760352f48/yarl-1.24.2-cp310-cp310-win_amd64.whl", hash = "sha256:5cb0f995a901c36be096ccbf4c673591c2faabbe96279598ffaec8c030f85bf4", size = 92658, upload-time = "2026-05-19T21:28:17.471Z" }, - { url = "https://files.pythonhosted.org/packages/91/00/671d0add79938127292839ae44506ce2f7fe8909c72d5a931864f128fd0b/yarl-1.24.2-cp310-cp310-win_arm64.whl", hash = "sha256:f408eace7e22a68b467a0562e0d27d322f91fe3eaaa6f466b962c6cfaea9fa39", size = 87887, upload-time = "2026-05-19T21:28:19.021Z" }, { url = "https://files.pythonhosted.org/packages/c5/c5/1ce244152ff2839645e7cae92f90e7bafcb2c52bea7ff586ac714f14f5df/yarl-1.24.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:36348bebb147b83818b9d7e673ea4debc75970afc6ffdc7e3975ad05ce5a58c1", size = 128971, upload-time = "2026-05-19T21:28:20.543Z" }, { url = "https://files.pythonhosted.org/packages/87/5a/00f36967203ed89cb3acd2c8ed526cc3fed9418eb70ce128160a911c8499/yarl-1.24.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1a97e42c8a2233f2f279ecadd9e4a037bcb5d813b78435e8eedd4db5a9e9708c", size = 91507, upload-time = "2026-05-19T21:28:22.556Z" }, { url = "https://files.pythonhosted.org/packages/31/d0/1fb0c1cd27288f39f6974da4318c32768d72c9890984541fdf1e2e32a51d/yarl-1.24.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8d027d56f1035e339d1001ac33eceab5b2ec8e42e449787bb75e289fb9a5cd1d", size = 91343, upload-time = "2026-05-19T21:28:24.092Z" }, diff --git a/release_process.md b/release_process.md index 55521774e..145427cee 100644 --- a/release_process.md +++ b/release_process.md @@ -170,6 +170,51 @@ the publishing job replaces assets with matching names on an existing release. Verify beta releases remain marked as prereleases and do not take the latest release designation. +### Python CLI wheels + +Run the **CLI Python wheels** workflow with a published CLI tag to build the +`lancedb-tools` wheels. It verifies the release archives against `SHA256SUMS`, +bundles the native executable and its notices, and saves the three wheels as +the `lancedb-tools-wheels` Actions artifact. Python package versions follow +PEP 440 (for example, CLI `v0.42.0-beta.30` becomes `0.42.0b30`). + +The workflow tests `uvx` and `pipx` against the artifact on each supported +platform. To try a downloaded wheel on a matching machine, substitute its +local path for `"$wheel"`: + +```sh +uvx --from "$wheel" lancedb --version +pipx install "$wheel" +lancedb profile list +``` + +This workflow produces review artifacts. Publishing the first stable wheels +to PyPI is a separate release step. + +### Homebrew tap updates + +After a stable GitHub release publishes, the `homebrew` job reads its +`SHA256SUMS` and opens a PR against `lancedb/homebrew-tap`. Review the +version and three checksums, wait for the tap's install tests, then merge the +PR manually. Rerunning the failed job reuses the release-specific branch. + +Before enabling the job, land the initial `Formula/lancedb.rb` on the tap's +`main` branch and configure the release credentials: + +1. Register a private GitHub App under the LanceDB organization. Grant repository + permissions **Contents** and **Pull requests** (both read and write). Leave + webhooks disabled. Install the App on the selected repository + `lancedb/homebrew-tap`. +2. In `lancedb/lancedb`, create a GitHub Actions environment named + `homebrew-tap`. Under deployment branches and tags, select tags matching + `v*`. Add the App's **Client ID** as the environment variable + `HOMEBREW_TAP_APP_CLIENT_ID` and its generated PEM private key as the + environment secret `HOMEBREW_TAP_APP_PRIVATE_KEY`. + +The release job exchanges the key for a short-lived tap installation token. +If opening the tap PR fails, fix the configuration and rerun the failed job +against the already published release. + ## Breaking changes We try to avoid breaking changes, but sometimes they are necessary. When there diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 398f3f015..b73c15e3c 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,2 @@ [toolchain] -channel = "1.97.0" +channel = "1.98.0" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 2d246bf39..529a7812e 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.4" +version = "0.42.0-beta.37" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true @@ -118,7 +118,7 @@ lance-testing = { workspace = true } # production remote feature so Python wheels do not resolve its Axum 0.7 stack. lance-namespace-impls = { workspace = true, features = ["rest-adapter"] } tempfile = { workspace = true } -random_word = { version = "0.4.3", features = ["en"] } +random_word = { version = "1.0.0", features = ["en"] } tokio = { workspace = true, features = ["io-util", "macros", "net", "test-util"] } uuid = { workspace = true } walkdir = "2" @@ -140,6 +140,8 @@ pprof = { version = "0.14", features = ["flamegraph"] } [features] default = [] +# Shared golden data for downstream compatibility tests. +test-fixtures = [] # Local SQL computed columns and materialized-view creation/refresh. # Remote clients and shared server primitives do not require this feature. experimental-functions = [] diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 49499fe22..11c70510d 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.4" +version = "0.42.0-beta.37" edition = "2021" license.workspace = true repository.workspace = true diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index a8a816fdd..7a381b8ee 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -204,6 +204,30 @@ impl BlobFile { lance::dataset::BlobFile::new_external(object_store, path, uri, position, size).into() } + /// Default sequential read-ahead window, in bytes. + pub const DEFAULT_READ_BUFFER_SIZE: usize = 512 * 1024; + + /// Set sequential read-ahead bytes. `0` disables read-ahead. + /// + /// Changing the size discards unused prefetched bytes without moving the + /// cursor. [`Self::read_range`] and [`Self::read_ranges`] bypass read-ahead. + /// The default is [`Self::DEFAULT_READ_BUFFER_SIZE`]. + /// + /// ``` + /// # async fn sparse_read(file: &lancedb::blob::BlobFile) -> lance_core::Result<()> { + /// file.set_buffer_size(0).await?; + /// let header = file.read_up_to(16).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn set_buffer_size(&self, size: usize) -> lance_core::Result<()> { + match &self.inner { + BlobFileInner::Native(file) => file.set_buffer_size(size).await, + #[cfg(feature = "remote")] + BlobFileInner::Remote(file) => file.set_buffer_size(size).await, + } + } + /// Close the handle. pub async fn close(&self) -> lance_core::Result<()> { match &self.inner { @@ -332,7 +356,7 @@ impl BlobFile { /// /// `row_id` is obtained from a query with row ids enabled. /// `offset` and `length` are relative to the beginning of the logical blob. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct BlobRangeRequest { /// Row id of the blob value to read. pub row_id: u64, @@ -632,7 +656,9 @@ fn missing_blob_row_ids_error(column: &str, requested: usize, missing: &[u64]) - Error::InvalidInput { message: format!( "blob read for column '{column}' requested {requested} row ids but some \ - do not exist in the table{detail}; pass row ids collected from this table" + do not exist in the table{detail}; pass row ids collected from this table. \ + If these were row positions, call take_offsets(offsets, with_row_id=True) \ + first and pass the resulting row ids" ), } } diff --git a/rust/lancedb/src/catalog.rs b/rust/lancedb/src/catalog.rs index df80b6de6..dcea8fd90 100644 --- a/rust/lancedb/src/catalog.rs +++ b/rust/lancedb/src/catalog.rs @@ -349,6 +349,18 @@ impl ConnectCatalogBuilder { self.options.client_config = config; self } + /// Set storage options inherited by the catalog's remote database connections. + pub fn storage_options( + mut self, + options: impl IntoIterator, impl Into)>, + ) -> Self { + self.options.storage_options.extend( + options + .into_iter() + .map(|(key, value)| (key.into(), value.into())), + ); + self + } /// Set the SQL service endpoint inherited by database connections. /// /// Required to execute SQL when the catalog endpoint uses HTTPS. The SQL diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 7d751bdb7..ac742eec7 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; use std::sync::Arc; +use std::time::Duration; use arrow_array::RecordBatch; use arrow_schema::SchemaRef; @@ -23,8 +24,8 @@ use crate::connection::create_table::CreateTableBuilder; use crate::data::scannable::Scannable; use crate::database::listing::ListingDatabase; use crate::database::{ - CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, OpenTableRequest, - PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest, + CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, JobListFilter, + OpenTableRequest, PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest, }; use crate::embeddings::{EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; @@ -51,7 +52,13 @@ pub use lance_file::version::LanceFileVersion; use lance_io::object_store::StorageOptions; use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; +mod create_secret; mod create_table; +mod create_view; + +pub use create_view::CreateViewBuilder; + +pub use create_secret::CreateSecretBuilder; pub(crate) fn merge_storage_options( store_params: &mut ObjectStoreParams, @@ -84,6 +91,75 @@ fn set_storage_options_provider( store_params.storage_options_accessor = Some(Arc::new(accessor)); } +/// Preserve caller-supplied options across provider refreshes. +/// +/// Namespace providers return a fresh credential map and replace the accessor +/// cache, so a plain initial-options accessor would drop caller-only settings +/// after the first refresh. This wrapper merges the caller options into every +/// provider result, with provider values winning overlapping keys. +#[derive(Debug)] +pub(crate) struct LayeredStorageOptionsProvider { + caller_options: HashMap, + inner: Arc, +} + +impl LayeredStorageOptionsProvider { + pub(crate) fn new( + caller_options: HashMap, + inner: Arc, + ) -> Self { + Self { + caller_options, + inner, + } + } + + fn layer( + &self, + mut options: Option>, + ) -> Option> { + let mut merged = self.caller_options.clone(); + match options.take() { + Some(options) => { + merged.extend(options); + Some(merged) + } + None if merged.is_empty() => None, + None => Some(merged), + } + } +} + +#[async_trait::async_trait] +impl StorageOptionsProvider for LayeredStorageOptionsProvider { + async fn fetch_storage_options(&self) -> lance_core::Result>> { + Ok(self.layer(self.inner.fetch_storage_options().await?)) + } + + async fn force_fetch_storage_options( + &self, + ) -> lance_core::Result>> { + Ok(self.layer(self.inner.force_fetch_storage_options().await?)) + } + + fn provider_id(&self) -> String { + use std::hash::{Hash, Hasher}; + + let mut entries: Vec<_> = self.caller_options.iter().collect(); + entries.sort_by_key(|(key, _)| *key); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for (key, value) in entries { + key.hash(&mut hasher); + value.hash(&mut hasher); + } + format!( + "layered(caller_options={:x},{})", + hasher.finish(), + self.inner.provider_id() + ) + } +} + /// A builder for configuring a [`Connection::table_names`] operation pub struct TableNamesBuilder { parent: Arc, @@ -352,6 +428,33 @@ impl ExecuteQueryAsyncBuilder { } } + /// Limit this execution from submission through result consumption. + /// + /// Expiry stops result reads and attempts to cancel Flight execution, even + /// if no reader was opened. It does not cancel durable server-side jobs. + /// Without this option, the connection's existing timeout settings apply. + pub fn timeout(mut self, timeout: Duration) -> Self { + self.request.options.timeout = Some(timeout); + self + } + + /// Override the connection's timeout for each server read on this query. + pub fn read_timeout(mut self, timeout: Duration) -> Self { + self.request.options.read_timeout = Some(timeout); + self + } + + /// Cancel deferred Flight execution when its unread handle or reader is dropped. + /// + /// This is best effort and requires the submitting Tokio runtime to remain + /// alive. Defaults to false, allowing deferred queries to be detached. + /// Directly streamed queries already stop on drop. Durable jobs require + /// explicit job cancellation regardless of this setting. + pub fn cancel_on_drop(mut self, cancel: bool) -> Self { + self.request.options.cancel_on_drop = cancel; + self + } + /// Set the namespace used for unqualified table names. /// /// An empty path is treated as `public`, which is the SQL name for the @@ -375,7 +478,10 @@ impl ExecuteQueryAsyncBuilder { /// /// Every placeholder needs a value and every parameter must be used by a /// placeholder. Parameters are supported in queries (`SELECT`, and - /// `EXPLAIN` of one), not in DDL or DML, nor in table-function arguments. + /// `EXPLAIN` of one) and, on compatible Enterprise servers, filter values in + /// `PREWARM` and `EXPLAIN PREWARM`. Prewarm bindings must be scalars. + /// Support for other statements depends on the server; table-function + /// arguments do not accept parameters. /// Do not follow a named placeholder directly with `$`: `$a$` starts a /// dollar-quoted string. /// @@ -427,6 +533,21 @@ impl CloneTableBuilder { } } + /// Preserve an existing target without reading or cloning the source. + /// Defaults to false, which reports a duplicate-name error. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let table = db.clone_table("snapshot", "s3://bucket/source.lance") + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.request.exist_ok = exist_ok; + self + } + /// Set the source version to clone from pub fn source_version(mut self, version: u64) -> Self { self.request.source_version = Some(version); @@ -627,7 +748,8 @@ impl Connection { /// Creates a new table by cloning from an existing source table. /// By default, this performs a shallow clone where the new table shares /// the underlying data files with the source table. - /// The target table name must be unused. An existing table is left unchanged. + /// The target table name must be unused by default. Use + /// [`CloneTableBuilder::exist_ok`] to open an existing target unchanged. /// /// # Parameters /// - `target_table_name`: The name of the new table to create @@ -668,9 +790,10 @@ impl Connection { /// Look up one exact immutable Function version in the remote catalog. /// - /// Both the logical name and server-assigned version id are required; - /// mutable aliases and latest-version lookup are intentionally absent. - /// LanceDB Embedded databases return [`Error::NotSupported`]. + /// Both the logical name and server-assigned version id are required. + /// Use [`Self::get_function_latest`] when the caller wants the latest + /// currently visible revision. LanceDB Embedded databases return + /// [`Error::NotSupported`]. pub async fn get_function( &self, name: impl AsRef, @@ -682,6 +805,22 @@ impl Connection { .await } + /// Look up the latest currently visible immutable Function version. + /// + /// The server resolves and returns one exact version document. This is a + /// resolution point, not a mutable alias: later registrations do not + /// change the returned object. LanceDB Embedded databases return + /// [`Error::NotSupported`]. + pub async fn get_function_latest( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result { + self.internal + .get_function_latest(name.as_ref(), namespace_path) + .await + } + /// List every published immutable Function version in `namespace_path` of /// the remote catalog. Functions in child namespaces are not included. /// @@ -738,6 +877,21 @@ impl Connection { .await } + /// Internal bridge for the Python binding to preserve the public bool API + /// while forwarding advisory SQL warnings to Python's existing warning + /// mechanism. + #[doc(hidden)] + pub async fn drop_function_with_warnings( + &self, + name: impl AsRef, + version: impl AsRef, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + self.internal + .drop_function_with_warnings(name.as_ref(), version.as_ref(), namespace_path) + .await + } + /// Drop one Function revision and return its SQL query handle. /// /// The boolean reports removal of the requested revision from the catalog. @@ -821,20 +975,30 @@ impl Connection { /// Create a named Secret in this database. /// - /// Fails if the name is taken, so a create can never silently become a - /// rotation. There is no API that reads a stored credential back; the only + /// Fails if the name is taken unless [`CreateSecretBuilder::exist_ok`] is true, + /// in which case the existing value is left unchanged. There is no API that + /// reads a stored credential back; the only /// consumer is a Function that binds the Secret by name. LanceDB Embedded databases /// return [`Error::NotSupported`]. - pub async fn create_secret( + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// connection.create_secret("api-key", "credential", &[]).exist_ok(true).await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_secret( &self, name: impl AsRef, value: impl AsRef, namespace_path: &[String], - ) -> Result<()> { - validate_secret_reference(name.as_ref(), namespace_path)?; - self.internal - .create_secret(name.as_ref(), value.as_ref(), namespace_path) - .await + ) -> CreateSecretBuilder { + CreateSecretBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + value.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// Replace the credential behind an existing Secret. @@ -931,9 +1095,10 @@ impl Connection { /// refused now rather than at the first read. A view holds no rows, and /// its readers see its sources as they are at read time. /// - /// There is no replace: a name already taken is an error, and changing a - /// view is a drop followed by a create, each authorized against what it - /// actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. + /// A name already taken is an error unless [`CreateViewBuilder::exist_ok`] is + /// true, which returns the stored definition and schema without changing them. + /// Changing a view is a drop followed by a create, each authorized against what + /// it actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// # Example /// @@ -966,16 +1131,18 @@ impl Connection { /// # Ok(()) /// # } /// ``` - pub async fn create_view( + pub fn create_view( &self, name: impl AsRef, query: impl AsRef, namespace_path: &[String], - ) -> Result { - validate_view_reference(name.as_ref(), namespace_path)?; - self.internal - .create_view(name.as_ref(), query.as_ref(), namespace_path) - .await + ) -> CreateViewBuilder { + CreateViewBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + query.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// What this database records about one view: its defining query and the @@ -1258,6 +1425,24 @@ impl Connection { self.database().list_gpu_classes().await } + /// Read the responding server's build and Function runtime information. + /// + /// This request does not submit a query, Function, or job. It requires + /// System Usage permission. Embedded databases and older servers without + /// `GET /v1/server/info` return [`Error::NotSupported`]. During a rolling + /// upgrade, separate requests can report different query-node builds. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let info = db.server_info().await?; + /// println!("{:?}", info.query_node); + /// # Ok(()) + /// # } + /// ``` + pub async fn server_info(&self) -> Result { + self.database().server_info().await + } + /// List server-side jobs across the database's tables. /// /// Results are fetched lazily, one page at a time. See [`Listing`] @@ -1281,6 +1466,37 @@ impl Connection { }) } + /// List jobs using server-side filters, without scanning all history in the client. + /// + /// Filters are preserved on every page, including when resuming with a saved + /// token. Requests and errors occur during iteration, as with [`Self::list_jobs`]. + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// use lancedb::{database::JobListFilter, listing::ListingOptions}; + /// let mut filter = JobListFilter::default(); + /// filter.table = Some("events".into()); + /// let mut jobs = connection.list_jobs_filtered(filter, ListingOptions::default().page_limit(5)); + /// if let Some(job) = jobs.try_next().await? { + /// println!("{}", job.job_id); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn list_jobs_filtered( + &self, + filter: JobListFilter, + options: ListingOptions, + ) -> Listing { + let database = self.database().clone(); + Listing::new(options, move |options| { + let database = database.clone(); + let filter = filter.clone(); + async move { database.list_jobs_filtered(filter, options).await } + }) + } + /// Request cancellation of a server-side job by id. Returns true if the /// server accepted the cancellation, false if no such job exists. pub async fn cancel_job(&self, job_id: impl AsRef) -> Result { @@ -1950,6 +2166,9 @@ use std::collections::HashSet; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum NamespaceClientPushdownOperation { /// Execute queries on the namespace server via `query_table()` instead of locally. + /// + /// Queries with a nonempty `order_by` execute locally and require client access + /// to the table storage. QueryTable, /// Execute table creation on the namespace server via `create_table()` /// instead of using `declare_table` + local write. @@ -2065,6 +2284,10 @@ impl ConnectNamespaceBuilder { /// - [`NamespaceClientPushdownOperation::QueryTable`]: Execute queries via `namespace.query_table()` /// - [`NamespaceClientPushdownOperation::CreateTable`]: Execute table creation via `namespace.create_table()` /// + /// Some query options cannot be represented in the namespace request. A query + /// with a nonempty `order_by` executes locally and requires client access to + /// the table storage. + /// /// By default, no operations are pushed down (all executed locally). pub fn pushdown_operation(mut self, operation: NamespaceClientPushdownOperation) -> Self { self.pushdown_operations.insert(operation); @@ -2718,6 +2941,14 @@ mod tests { "unexpected clone error: {err:?}" ); + let preserved = db + .clone_table(target, "missing-source.lance") + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(preserved.name(), target); + // Reopen both tables to verify that the failed clone left their data and versions intact. for (name, expected_data) in [("source", source_data), ("target", target_data)] { let table = db.open_table(name).execute().await.unwrap(); @@ -2735,8 +2966,9 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { let tmp_dir = tempdir().unwrap(); let uri = tmp_dir.path().to_str().unwrap(); let db = connect(uri).execute().await.unwrap(); @@ -2761,6 +2993,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table("cloned_table", source_uri) + .exist_ok(exist_ok) .execute() .await .unwrap(); diff --git a/rust/lancedb/src/connection/create_secret.rs b/rust/lancedb/src/connection/create_secret.rs new file mode 100644 index 000000000..265b97571 --- /dev/null +++ b/rust/lancedb/src/connection/create_secret.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_secret_reference; + +/// Configure creation of a named Secret with [`super::Connection::create_secret`]. +#[must_use] +pub struct CreateSecretBuilder { + database: Arc, + name: String, + value: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateSecretBuilder { + pub(super) fn new( + database: Arc, + name: String, + value: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + value, + namespace_path, + exist_ok: false, + } + } + + /// Succeed without changing the stored value when the Secret already exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the Secret, preserving any existing value when `exist_ok` is true. + pub async fn execute(self) -> Result<()> { + validate_secret_reference(&self.name, &self.namespace_path)?; + self.database + .create_secret(&self.name, &self.value, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateSecretBuilder { + type Output = Result<()>; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/connection/create_table.rs b/rust/lancedb/src/connection/create_table.rs index 95b0643c6..77003dc30 100644 --- a/rust/lancedb/src/connection/create_table.rs +++ b/rust/lancedb/src/connection/create_table.rs @@ -3,6 +3,8 @@ use std::sync::Arc; +use lance::dataset::WriteParams; +use lance::table::format::BasePath; use lance_io::object_store::StorageOptionsProvider; use crate::{ @@ -53,6 +55,67 @@ impl CreateTableBuilder { self } + /// Register additional base paths in the new table's manifest. + /// + /// The bases are written in the same commit that creates the table, so a + /// create with data stays a single atomic operation. Blob URIs that fall + /// under a registered base are stored relative to it instead of as absolute + /// URIs; see [`Table::fetch_blobs`]. + /// + /// Set [`BasePath::id`] to `0` to let Lance assign an ID, or to a unique + /// non-zero value. Pass an empty list to leave the request unchanged. + /// + /// When supplying IDs for multiple bases, use distinct explicit non-zero + /// IDs. The pinned Lance release can collide when one base asks for + /// automatic allocation (`0`) and another supplies an explicit ID: the + /// create fails, the table name can remain listed but unopenable, and + /// retrying with distinct explicit IDs succeeds. Automatic allocation for + /// every base is supported. + /// + /// LanceDB Embedded only. + /// + /// [`Table::fetch_blobs`]: crate::table::Table::fetch_blobs + pub fn initial_bases(mut self, bases: Vec) -> Self { + let empty = bases.is_empty(); + self.update_lance_write_params(!empty, |params| { + params.initial_bases = (!empty).then_some(bases); + }); + self + } + + /// Store blob URIs that sit outside registered blob bases. + /// + /// The row keeps a reference, so the object has to stay readable. + /// [`Table::fetch_blobs`] reads from that location. Defaults to `false`. + /// + /// The opt-in covers only the rows written by this create. A later `add` + /// must enable it again. + /// + /// LanceDB Embedded only. + /// + /// [`Table::fetch_blobs`]: crate::table::Table::fetch_blobs + pub fn allow_external_blob_outside_bases(mut self, allow: bool) -> Self { + self.update_lance_write_params(allow, |params| { + params.allow_external_blob_outside_bases = allow; + }); + self + } + + /// Apply `update` to the Lance write parameters, creating them only when + /// `create` is set. A no-op call on a request that has no write parameters + /// leaves it that way, so default creation does not look customized. + fn update_lance_write_params(&mut self, create: bool, update: impl FnOnce(&mut WriteParams)) { + if !create && self.request.write_options.lance_write_params.is_none() { + return; + } + update( + self.request + .write_options + .lance_write_params + .get_or_insert_default(), + ); + } + /// Set an option for the storage layer. /// /// Options already set on the connection will be inherited by the table, @@ -218,6 +281,24 @@ mod tests { assert_eq!(table.count_rows(None).await.unwrap(), 3); } + #[tokio::test] + async fn create_table_with_default_blob_base_options() { + // Explicit empty bases and opt-out follow the ordinary create path: no + // write parameters are attached just because the fluent methods ran. + let db = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("id", Int64, [1, 2, 3])).unwrap(); + + let table = db + .create_table("no_bases", batch) + .initial_bases(Vec::new()) + .allow_external_blob_outside_bases(false) + .execute() + .await + .unwrap(); + + assert_eq!(table.count_rows(None).await.unwrap(), 3); + } + async fn test_create_table_with_data(data: T) where T: Scannable + 'static, diff --git a/rust/lancedb/src/connection/create_view.rs b/rust/lancedb/src/connection/create_view.rs new file mode 100644 index 000000000..bd80ca6e7 --- /dev/null +++ b/rust/lancedb/src/connection/create_view.rs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_view_reference; +use crate::view::ViewDescription; + +/// Configure creation of a view with [`super::Connection::create_view`]. +#[must_use] +pub struct CreateViewBuilder { + database: Arc, + name: String, + query: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateViewBuilder { + pub(super) fn new( + database: Arc, + name: String, + query: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + query, + namespace_path, + exist_ok: false, + } + } + + /// Return the existing view without changing its definition if it exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the view or return the existing view when `exist_ok` is true. + pub async fn execute(self) -> Result { + validate_view_reference(&self.name, &self.namespace_path)?; + self.database + .create_view(&self.name, &self.query, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateViewBuilder { + type Output = Result; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/data/scannable.rs b/rust/lancedb/src/data/scannable.rs index 0f810941a..cfad157b8 100644 --- a/rust/lancedb/src/data/scannable.rs +++ b/rust/lancedb/src/data/scannable.rs @@ -504,7 +504,7 @@ impl Scannable for PeekedScannable { /// when known; otherwise `sample_rows` row count is used as a lower bound /// estimate. /// -/// Targets roughly 1 million rows or 2 GB per partition, capped at +/// Targets roughly 1 million rows or 64 MiB per partition, capped at /// `max_partitions` (typically the number of available CPU cores). pub(crate) fn estimate_write_partitions( sample_bytes: usize, @@ -519,7 +519,7 @@ pub(crate) fn estimate_write_partitions( let total_rows = total_rows_hint.unwrap_or(sample_rows); let total_bytes = total_rows * bytes_per_row; let by_rows = total_rows.div_ceil(1_000_000); - let by_bytes = total_bytes.div_ceil(2 * 1024 * 1024 * 1024); + let by_bytes = total_bytes.div_ceil(64 * 1024 * 1024); by_rows.max(by_bytes).max(1).min(max_partitions) } @@ -813,8 +813,8 @@ mod tests { #[test] fn test_scales_by_byte_size() { - // 100k rows at 40KB/row = ~4GB total → ceil(4GB / 2GB) = 2 - let sample_bytes = 40_000 * 10; + // 100k rows at 1KB/row exceeds one 64 MiB partition. + let sample_bytes = 1_000 * 10; assert_eq!( estimate_write_partitions(sample_bytes, 10, Some(100_000), 8), 2 diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index daa7f3f29..b021bf0ee 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -163,6 +163,8 @@ impl CreateTableRequest { /// sharing the same data, deletion, and index files. #[derive(Clone, Debug)] pub struct CloneTableRequest { + /// Preserve an existing target rather than returning a duplicate-name error. + pub exist_ok: bool, /// The name of the target table to create pub target_table_name: String, /// The namespace path for the target table. Empty list represents root namespace. @@ -184,6 +186,7 @@ pub struct CloneTableRequest { impl CloneTableRequest { pub fn new(target_table_name: String, source_uri: String) -> Self { Self { + exist_ok: false, target_table_name, target_namespace_path: vec![], source_uri, @@ -209,6 +212,8 @@ pub struct ExecuteQueryRequest { /// also binds `$`. See /// [`ExecuteQueryAsyncBuilder::parameters`](crate::connection::ExecuteQueryAsyncBuilder::parameters). pub parameters: Option, + /// Execution limits and cancellation behavior for this statement. + pub options: crate::sql::QueryOptions, } impl ExecuteQueryRequest { @@ -217,6 +222,7 @@ impl ExecuteQueryRequest { query: query.into(), default_namespace_path: vec!["public".to_string()], parameters: None, + options: Default::default(), } } } @@ -235,6 +241,45 @@ pub enum ReadConsistency { Strong, } +/// Registry lifecycle states accepted when filtering jobs. +#[derive(Clone, Copy, Debug, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum JobListState { + /// A job that has not reached a terminal state. + InProgress, + /// A job that completed successfully. + Succeeded, + /// A job that failed. + Failed, + /// A job that was canceled. + Canceled, + /// A job that exceeded its timeout. + TimedOut, +} + +/// Server-side filters applied before job pagination. +/// +/// Continuation tokens must be resumed with the same filters. Creation times +/// are Unix timestamps in milliseconds; the lower bound is inclusive and the +/// upper bound is exclusive. +#[derive(Clone, Debug, Default)] +#[non_exhaustive] +pub struct JobListFilter { + /// Table name within `namespace_path`, including all its branches; absent means all tables. + pub table: Option, + /// Namespace of `table`; requires a table name. + pub namespace_path: Vec, + /// Registry state, such as `in_progress`, `succeeded`, or `failed`. + /// These are server states, rather than the labels in [`JobInfo::state`]. + pub state: Option, + /// Include jobs of any of these types; empty means all types. + pub job_types: Vec, + /// Inclusive creation-time lower bound. + pub created_at_gte_millis: Option, + /// Exclusive creation-time upper bound. + pub created_at_lt_millis: Option, +} + /// A row from [`Database::list_jobs`]: one server-side job (index build, /// compaction, column refresh, ...). #[derive(Debug, Clone)] @@ -249,6 +294,20 @@ pub struct JobInfo { pub state: String, /// When the job was created, in milliseconds since the epoch. pub created_at_millis: i64, + /// Terminal timestamp, in milliseconds since the epoch; unknown on older servers. + pub completed_at_millis: Option, + /// Creation-to-completion wall time, including queueing and pauses. + /// Absent for unfinished jobs or when the server cannot establish the duration. + pub duration_millis: Option, + /// Columns affected by this job. Empty when unavailable or not column-scoped. + pub columns: Vec, + /// Pinned Function catalog name, with namespace segments joined by `$`. + /// Present for computed column refreshes when supplied by the server. + pub function_name: Option, + /// Pinned Function version, when supplied by the server. + pub function_version: Option, + /// Durable failure summary; absent when unavailable or the job did not fail. + pub failure: Option, /// Latest progress sample for a job type that reports structured progress. pub progress: Option, /// Coarse server-derived phase, including phases introduced by newer @@ -284,6 +343,20 @@ impl JobInfo { #[derive(Debug, Clone)] pub struct JobDescription { pub job_id: String, + /// Exact selected attempt when job_id is a durable operation handle. + pub attempt_job_id: Option, + /// Root identity shared by the explicit retry lineage, when reported. + pub operation_id: Option, + /// One-based attempt ordinal, when reported. + pub attempt: Option, + /// Immediate predecessor attempt, when reported. + pub retry_of: Option, + /// Detailed state before folding it into legacy client labels. + pub lifecycle_state: Option, + /// Pinned source snapshot, when reported. + pub source_table_version: Option, + /// Most recent execution's fencing token, when reported. + pub execution_epoch: Option, pub job_type: String, /// Lifecycle state: "running", "finished", "failed", or "cancelled". pub state: String, @@ -343,6 +416,28 @@ impl JobDescription { snapshot.insert(key.clone(), value.clone()); } } + if let Some(operation_id) = &self.operation_id { + snapshot.insert("operation_id".to_string(), operation_id.clone().into()); + } + snapshot.insert("job_id".to_string(), self.job_id.clone().into()); + if let Some(attempt_job_id) = &self.attempt_job_id { + snapshot.insert("attempt_job_id".to_string(), attempt_job_id.clone().into()); + } + if let Some(attempt) = self.attempt { + snapshot.insert("attempt".to_string(), attempt.into()); + } + if let Some(retry_of) = &self.retry_of { + snapshot.insert("retry_of".to_string(), retry_of.clone().into()); + } + if let Some(state) = &self.lifecycle_state { + snapshot.insert("lifecycle_state".to_string(), state.as_str().into()); + } + if let Some(version) = self.source_table_version { + snapshot.insert("source_table_version".to_string(), version.into()); + } + if let Some(epoch) = self.execution_epoch { + snapshot.insert("execution_epoch".to_string(), epoch.into()); + } serde_json::Value::Object(snapshot) } } @@ -479,6 +574,13 @@ pub trait Database: async fn list_gpu_classes(&self) -> Result> { gpu_class_catalog_not_supported() } + + /// Read the responding remote server's build identity. + async fn server_info(&self) -> Result { + Err(crate::Error::NotSupported { + message: "Server build discovery requires a remote LanceDB connection".into(), + }) + } /// Create a materialized view through a remote catalog and return its /// initial-population job. Local connections use the native declaration /// path directly. @@ -552,6 +654,14 @@ pub trait Database: ) -> Result { function_catalog_not_supported() } + /// Look up the latest currently visible immutable Function version. + async fn get_function_latest( + &self, + _name: &str, + _namespace_path: &[String], + ) -> Result { + function_catalog_not_supported() + } /// Fetch one page of published immutable Function versions in one namespace. async fn list_functions( &self, @@ -581,6 +691,18 @@ pub trait Database: let dropped = self.drop_function(name, version, namespace_path).await?; Ok((dropped, crate::job::Job::new_done())) } + /// Internal bridge for the Python binding to preserve the public bool API + /// while making advisory SQL warnings available to the wrapper. + #[doc(hidden)] + async fn drop_function_with_warnings( + &self, + name: &str, + version: &str, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + let dropped = self.drop_function(name, version, namespace_path).await?; + Ok((dropped, Vec::new())) + } /// Create a database-owned storage integration in a namespace. async fn create_storage_integration( &self, @@ -615,13 +737,14 @@ pub trait Database: secret_catalog_not_supported() } - /// Create a named Secret in this database. Fails if the name is taken, so - /// a create can never silently become a rotation. + /// Create a named Secret in this database. If the name is taken, fail unless + /// `exist_ok` is true, in which case the stored value is left unchanged. async fn create_secret( &self, _name: &str, _value: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result<()> { secret_catalog_not_supported() } @@ -665,6 +788,7 @@ pub trait Database: _name: &str, _query: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result { view_ops_not_supported() } @@ -749,6 +873,14 @@ pub trait Database: async fn list_jobs(&self, _options: ListingOptions) -> Result> { job_op_not_supported("list_jobs") } + /// Fetch one page of jobs matching server-side filters. + async fn list_jobs_filtered( + &self, + _filter: JobListFilter, + _options: ListingOptions, + ) -> Result> { + job_op_not_supported("list_jobs_filtered") + } /// Request cancellation of a job by id. Returns true if the server /// accepted the cancellation, false if no such job exists. Cancelling an /// already-terminal job is a no-op success. diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index d5749f974..17ecfadff 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -22,7 +22,7 @@ use crate::blob::ensure_blob_storage_version; use crate::connection::ConnectRequest; use crate::database::ReadConsistency; use crate::database::namespace::LanceNamespaceDatabase; -use crate::error::{CreateDirSnafu, Error, Result}; +use crate::error::{BoxError, CreateDirSnafu, Error, Result, TableNotFoundHint}; use crate::io::object_store::MirroringObjectStoreWrapper; use crate::table::NativeTable; use crate::utils::validate_table_name; @@ -698,6 +698,22 @@ impl ListingDatabase { Ok(()) } + /// Explain a miss caused by connecting to a Lance dataset as if it were a + /// database directory. The connection URI is enough to name the parent and + /// table stem, so this needs no storage probe. + fn lance_dataset_path_hint(&self) -> Option { + let uri = self.uri.trim_end_matches(['/', '\\']); + let (parent, file_name) = uri.rsplit_once(['/', '\\'])?; + let stem = file_name.strip_suffix(".lance")?; + if stem.is_empty() { + return None; + } + let parent = if parent.is_empty() { "." } else { parent }; + Some(format!( + ". The connection URI ends with '.lance', which points to a Lance dataset rather than a database directory. Connect to the parent directory '{parent}' and open table '{stem}' instead." + )) + } + /// Get the URI of a table in the database. fn table_uri(&self, name: &str) -> Result { validate_table_name(name)?; @@ -1119,40 +1135,47 @@ impl Database for ListingDatabase { }; let target_uri = self.table_uri(&request.target_table_name)?; - match DatasetBuilder::from_uri(&target_uri) + let exists = match DatasetBuilder::from_uri(&target_uri) .with_read_params(read_params.clone()) .load() .await { - Ok(_) => { + Ok(_) if !request.exist_ok => { return Err(Error::TableAlreadyExists { name: request.target_table_name, }); } - Err(lance::Error::DatasetNotFound { .. }) => {} + Ok(_) => true, + Err(lance::Error::DatasetNotFound { .. }) => false, Err(err) => return Err(err.into()), + }; + + if !exists { + let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) + .with_read_params(read_params.clone()) + .load() + .await + .map_err(|e| -> Error { e.into() })?; + + let version_ref = match (request.source_version, request.source_tag) { + (Some(v), None) => Ok(Ref::Version(None, Some(v))), + (None, Some(tag)) => Ok(Ref::Tag(tag)), + (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), + _ => Err(Error::InvalidInput { + message: "Cannot specify both source_version and source_tag".to_string(), + }), + }?; + + match source_dataset + .shallow_clone(&target_uri, version_ref, Some(storage_params)) + .await + { + Ok(_) => {} + Err(lance::Error::DatasetAlreadyExists { .. }) if request.exist_ok => {} + Err(error) => return Err(error.into()), + } } - let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) - .with_read_params(read_params.clone()) - .load() - .await - .map_err(|e| -> Error { e.into() })?; - - let version_ref = match (request.source_version, request.source_tag) { - (Some(v), None) => Ok(Ref::Version(None, Some(v))), - (None, Some(tag)) => Ok(Ref::Tag(tag)), - (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), - _ => Err(Error::InvalidInput { - message: "Cannot specify both source_version and source_tag".to_string(), - }), - }?; - - source_dataset - .shallow_clone(&target_uri, version_ref, Some(storage_params)) - .await - .map_err(|e| -> Error { e.into() })?; - let cloned_table = NativeTable::open_with_params( &target_uri, &request.target_table_name, @@ -1173,6 +1196,7 @@ impl Database for ListingDatabase { if !request.namespace_path.is_empty() { return self.namespace_database().open_table(request).await; } + let derived_location = request.location.is_none(); // Use provided location if available, otherwise derive from table name let table_uri = match request.location.clone() { Some(location) => location, @@ -1226,20 +1250,29 @@ impl Database for ListingDatabase { }); read_params.session(self.session.clone()); - let native_table = Arc::new( - NativeTable::open_with_params( - &table_uri, - &request.name, - request.namespace_path, - self.store_wrapper.clone(), - Some(read_params), - self.read_consistency_interval, - request.namespace_client, - HashSet::new(), // listing database doesn't support server-side queries - request.managed_versioning, // Pass through managed_versioning from request - ) - .await?, - ); + let native_table = match NativeTable::open_with_params( + &table_uri, + &request.name, + request.namespace_path, + self.store_wrapper.clone(), + Some(read_params), + self.read_consistency_interval, + request.namespace_client, + HashSet::new(), // listing database doesn't support server-side queries + request.managed_versioning, // Pass through managed_versioning from request + ) + .await + { + Ok(table) => Arc::new(table), + Err(Error::TableNotFound { name, source }) if derived_location => { + let source: BoxError = match self.lance_dataset_path_hint() { + Some(hint) => Box::new(TableNotFoundHint::new(hint, source)), + None => source, + }; + return Err(Error::TableNotFound { name, source }); + } + Err(error) => return Err(error), + }; Ok(native_table) } @@ -1836,10 +1869,100 @@ mod tests { } } - async fn setup_database() -> (tempfile::TempDir, ListingDatabase) { + /// A connection made to a dataset path cannot also be a database directory. The + /// miss names the parent and table stem so the caller can fix the connection. + #[tokio::test] + async fn test_open_table_dataset_path_hint() { let tempdir = tempdir().unwrap(); - let uri = tempdir.path().to_str().unwrap(); + let data_dir = tempdir.path().join("data"); + let data_db = setup_database_at(data_dir.to_str().unwrap()).await; + create_tables(&data_db, &["embeddings"]).await; + let dataset_path = data_dir.join("embeddings.lance"); + let dataset_db = setup_database_at(dataset_path.to_str().unwrap()).await; + let error = dataset_db + .open_table(OpenTableRequest { + name: "embeddings".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap_err(); + + assert!( + matches!(&error, Error::TableNotFound { name, .. } if name == "embeddings"), + "the dataset path miss changed classification: {error:?}" + ); + let message = error.to_string(); + assert!( + message.contains("points to a Lance dataset rather than a database directory"), + "the hint did not explain the dataset path: {message}" + ); + assert!( + message.contains(&format!("parent directory '{}'", data_dir.display())), + "the hint did not name the parent directory: {message}" + ); + assert!( + message.contains("open table 'embeddings' instead"), + "the hint did not name the table stem: {message}" + ); + } + + /// The hint belongs only to a derived URI. An explicit location is the caller's + /// own choice, so a miss there keeps the original message. + #[tokio::test] + async fn test_open_table_explicit_location_skips_dataset_path_hint() { + let tempdir = tempdir().unwrap(); + let data_dir = tempdir.path().join("data"); + let data_db = setup_database_at(data_dir.to_str().unwrap()).await; + create_tables(&data_db, &["embeddings"]).await; + let dataset_path = data_dir.join("embeddings.lance"); + let dataset_db = setup_database_at(dataset_path.to_str().unwrap()).await; + + let table = dataset_db + .open_table(OpenTableRequest { + name: "alias".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: Some(dataset_path.to_str().unwrap().to_string()), + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 0); + + let missing_path = tempdir.path().join("missing.lance"); + let error = dataset_db + .open_table(OpenTableRequest { + name: "missing".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: Some(missing_path.to_str().unwrap().to_string()), + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap_err(); + assert!( + matches!(&error, Error::TableNotFound { name, .. } if name == "missing"), + "the explicit location miss changed classification: {error:?}" + ); + assert!( + !error + .to_string() + .contains("points to a Lance dataset rather than a database directory"), + "an explicit location still received the connection hint: {error}" + ); + } + + async fn setup_database_at(uri: &str) -> ListingDatabase { let request = ConnectRequest { uri: uri.to_string(), #[cfg(feature = "remote")] @@ -1850,11 +1973,14 @@ mod tests { read_consistency_interval: None, session: None, }; - - let db = ListingDatabase::connect_with_options(&request) + ListingDatabase::connect_with_options(&request) .await - .unwrap(); + .unwrap() + } + async fn setup_database() -> (tempfile::TempDir, ListingDatabase) { + let tempdir = tempdir().unwrap(); + let db = setup_database_at(tempdir.path().to_str().unwrap()).await; (tempdir, db) } @@ -2252,6 +2378,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_table".to_string(), target_namespace_path: vec![], source_uri: source_uri.clone(), @@ -2313,6 +2440,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_with_data".to_string(), target_namespace_path: vec![], source_uri, @@ -2375,6 +2503,7 @@ mod tests { // Clone should work with storage options let cloned = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2412,6 +2541,7 @@ mod tests { // Try deep clone (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2453,6 +2583,7 @@ mod tests { // Try clone with namespace (should fail for listing database) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec!["namespace".to_string()], // Non-empty namespace source_uri, @@ -2494,6 +2625,7 @@ mod tests { // Try clone with invalid target name let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "invalid/name".to_string(), // Invalid name with slash target_namespace_path: vec![], source_uri, @@ -2514,6 +2646,7 @@ mod tests { // Try to clone from non-existent source let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri: "/nonexistent/table.lance".to_string(), @@ -2551,6 +2684,7 @@ mod tests { // Try clone with both version and tag (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2625,6 +2759,7 @@ mod tests { // Clone from the initial version (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_version".to_string(), target_namespace_path: vec![], source_uri, @@ -2704,6 +2839,7 @@ mod tests { // Clone from the tag (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_tag".to_string(), target_namespace_path: vec![], source_uri, @@ -2756,6 +2892,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "independent_clone".to_string(), target_namespace_path: vec![], source_uri, @@ -2849,6 +2986,7 @@ mod tests { // Clone without specifying version or tag (should get latest) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_latest".to_string(), target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index d93f73c64..d603a878b 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -9,7 +9,10 @@ use std::sync::{Arc, Mutex}; use async_trait::async_trait; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; -use lance_io::object_store::{ObjectStoreParams, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, ObjectStoreParams, StorageOptionsAccessor, + StorageOptionsProvider, +}; use lance_namespace::{ LanceNamespace, error::{ErrorCode, NamespaceError}, @@ -25,7 +28,9 @@ use lance_table::io::commit::CommitHandler; use lance_table::io::commit::external_manifest::ExternalManifestCommitHandler; use crate::blob::ensure_blob_storage_version; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{ + LayeredStorageOptionsProvider, NamespaceClientPushdownOperation, merge_storage_options, +}; use crate::database::ReadConsistency; use crate::database::listing::{NewTableConfig, take_request_creation_overrides}; use crate::database::read_freshness::{ @@ -336,6 +341,9 @@ impl Database for LanceNamespaceDatabase { // Refuse a bad declaration before the namespace records a table. crate::table::computed_columns::ensure_declarations_are_planned( &request.data.arrow_schema(), + self.session + .as_deref() + .and_then(lance::session::Session::datafusion_session), )?; let mut table_id = request.namespace_path.clone(); table_id.push(request.name.clone()); @@ -462,13 +470,29 @@ impl Database for LanceNamespaceDatabase { params.mode = WriteMode::Overwrite; } - // Set up storage options if provided + // Set up storage options if provided. Namespace options take + // precedence for overlapping keys, but must not discard caller-only + // options supplied with the create request. + let store_params = params + .store_params + .get_or_insert_with(ObjectStoreParams::default); + let caller_storage_options = store_params.storage_options().cloned().unwrap_or_default(); if let Some(storage_opts) = initial_storage_options { - let store_params = params - .store_params - .get_or_insert_with(ObjectStoreParams::default); + merge_storage_options(store_params, storage_opts); + } + if let Some(initial_options) = store_params + .storage_options() + .cloned() + .filter(|options| !options.is_empty()) + { + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(self.namespace.clone(), table_id.clone()), + ); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(caller_storage_options, namespace_provider), + ); store_params.storage_options_accessor = Some(Arc::new( - StorageOptionsAccessor::with_static_options(storage_opts), + StorageOptionsAccessor::with_initial_and_provider(initial_options, provider), )); } @@ -615,6 +639,7 @@ mod tests { use arrow_array::{Int32Array, RecordBatch, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; + use lance_io::object_store::StorageOptionsAccessor; use tempfile::tempdir; #[derive(Debug)] diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 15f8c3cd3..93efb130f 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -15,7 +15,7 @@ use crate::{ Error, Result, Table, arrow::{SendableRecordBatchStream, SendableRecordBatchStreamExt, SimpleRecordBatchStream}, connect, - database::{CreateTableRequest, Database}, + database::{CreateTableMode, CreateTableRequest, Database}, dataloader::permutation::{ shuffle::{Shuffler, ShufflerConfig}, split::{SPLIT_ID_COLUMN, SplitStrategy, Splitter}, @@ -43,7 +43,34 @@ enum PermutationDestination { #[default] Temporary, /// The permutation table is a permanent table in a database - Permanent(Arc, String), + Permanent { + database: Arc, + table_name: String, + namespace_path: Vec, + mode: PermutationPersistMode, + }, +} + +/// How a persisted permutation table handles an existing table of the same name. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum PermutationPersistMode { + /// Fail if the destination table already exists. + #[default] + Create, + /// Replace the destination table with the new plan. + /// + /// The previous table version remains readable by handles that were already + /// opened against it. + Overwrite, +} + +/// Options for storing a permutation table in a database. +#[derive(Debug, Clone, Default)] +pub struct PermutationPersistOptions { + /// The namespace path to create the table in. Empty means the root namespace. + pub namespace_path: Vec, + /// Whether an existing table may be replaced. + pub mode: PermutationPersistMode, } /// Configuration for creating a permutation table @@ -161,9 +188,29 @@ impl PermutationBuilder { /// Stores the permutation as a table in a database /// /// By default, the permutation is stored in memory. If this method is called then - /// the permutation will be stored as a table in the given database. - pub fn persist(mut self, database: Arc, table_name: String) -> Self { - self.config.destination = PermutationDestination::Permanent(database, table_name); + /// the permutation will be stored as a table in the given database. The table is + /// created in the root namespace and an existing table is not replaced; use + /// [`Self::persist_with_options`] to choose a namespace or overwrite mode. + pub fn persist(self, database: Arc, table_name: String) -> Self { + self.persist_with_options(database, table_name, PermutationPersistOptions::default()) + } + + /// Stores the permutation as a table in a database with explicit options. + /// + /// This is the same as [`Self::persist`] but lets the caller select the target + /// namespace and whether an existing table may be overwritten. + pub fn persist_with_options( + mut self, + database: Arc, + table_name: String, + options: PermutationPersistOptions, + ) -> Self { + self.config.destination = PermutationDestination::Permanent { + database, + table_name, + namespace_path: options.namespace_path, + mode: options.mode, + }; self } @@ -249,10 +296,10 @@ impl PermutationBuilder { /// Builds the permutation table and stores it in the given database. pub async fn build(mut self) -> Result
      { - // Remote tables resolve latest independently for each request. Use a - // separate pinned handle so count, projection, and scan all refer to one - // snapshot without changing the caller's table checkout state. Native - // tables return `None` here and retain their existing behavior. + // Remote tables resolve latest independently for each request, and a + // native handle can refresh or answer a query from a namespace server. + // Use a separate pinned handle so count, projection, and scan all refer + // to one snapshot without changing the caller's table checkout state. if let Some(snapshot) = self .base_table .base_table() @@ -369,17 +416,31 @@ impl PermutationBuilder { let streaming_data = Self::add_config_metadata(renamed, metadata)?; let (name, database) = match &self.config.destination { - PermutationDestination::Permanent(database, table_name) => { - (table_name.as_str(), database.clone()) - } + PermutationDestination::Permanent { + database, + table_name, + .. + } => (table_name.as_str(), database.clone()), PermutationDestination::Temporary => { let conn = connect("memory:///").execute().await?; ("permutation", conn.database().clone()) } }; - let create_table_request = + let mut create_table_request = CreateTableRequest::new(name.to_string(), Box::new(streaming_data)); + if let PermutationDestination::Permanent { + namespace_path, + mode, + .. + } = &self.config.destination + { + create_table_request.namespace_path = namespace_path.clone(); + create_table_request.mode = match mode { + PermutationPersistMode::Create => CreateTableMode::Create, + PermutationPersistMode::Overwrite => CreateTableMode::Overwrite, + }; + } let table = database.create_table(create_table_request).await?; @@ -396,6 +457,51 @@ mod tests { use super::*; + /// Stands in for a namespace server whose table has advanced past the local + /// dataset. A pushed-down query reads this newer row instead of the local + /// snapshot. + #[derive(Debug, Default)] + struct ServerLatestNamespace { + query_table_calls: std::sync::atomic::AtomicUsize, + latest_row_id: u64, + } + + #[async_trait::async_trait] + impl lance_namespace::LanceNamespace for ServerLatestNamespace { + fn namespace_id(&self) -> String { + "server-latest".to_string() + } + + async fn query_table( + &self, + _request: lance_namespace::models::QueryTableRequest, + ) -> lance::Result { + self.query_table_calls + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + use arrow_array::UInt64Array; + use arrow_schema::{DataType, Field, Schema}; + + let schema = Arc::new(Schema::new(vec![Field::new( + ROW_ID, + DataType::UInt64, + false, + )])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(UInt64Array::from(vec![self.latest_row_id]))], + ) + .unwrap(); + let mut body = Vec::new(); + { + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + Ok(bytes::Bytes::from(body)) + } + } + #[tokio::test] async fn test_permutation_table_only_stores_row_id_and_split_id() { let temp_dir = tempfile::tempdir().unwrap(); @@ -451,6 +557,140 @@ mod tests { // Native tables skip the canonicalizing sort; remote does not. assert!(table.base_table().scan_order_is_deterministic()); + + // A main/latest handle may answer from a namespace server, and its + // QueryTable request carries no order. The local native scan guarantee + // does not extend to that path. + let mut pushed_down = table.as_native().unwrap().clone(); + pushed_down.namespace_client = Some(Arc::new(ServerLatestNamespace::default())); + pushed_down + .pushdown_operations + .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable); + let pushed_down: Arc = Arc::new(pushed_down); + let pushed_down = Table::from(pushed_down); + assert!(!pushed_down.base_table().scan_order_is_deterministic()); + } + + /// The builder must pin one native snapshot before it counts or scans. A + /// namespace-backed latest handle can otherwise count local rows, scan + /// server-latest rows, and record the local version as if they agreed. + #[tokio::test] + async fn test_native_permutation_builder_pins_namespace_pushdown() { + use std::sync::atomic::Ordering; + + use arrow_array::{cast::AsArray, types::UInt64Type}; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let namespace = Arc::new(ServerLatestNamespace { + latest_row_id: 10, + ..Default::default() + }); + let mut native = table.as_native().unwrap().clone(); + native.namespace_client = Some(namespace.clone()); + native + .pushdown_operations + .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable); + let native: Arc = Arc::new(native); + let table = Table::from(native); + + let permutation = PermutationBuilder::new(table.clone()) + .build() + .await + .unwrap(); + + assert_eq!( + namespace.query_table_calls.load(Ordering::SeqCst), + 0, + "the builder must read its pinned local snapshot, not server-latest rows" + ); + assert_eq!(permutation.count_rows(None).await.unwrap(), 10); + + let batches: Vec = permutation + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch[SRC_ROW_ID_COL] + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(ids, (0..10).collect::>()); + + let recorded = permutation + .schema() + .await + .unwrap() + .metadata + .get(BASE_VERSION_CONFIG_KEY) + .expect("permutation should record its base version") + .parse::() + .unwrap(); + assert_eq!(recorded, table.version().await.unwrap()); + } + + /// `snapshot_at_current_version` is the builder's one-snapshot hook. With + /// read refresh enabled, the caller can advance while the pin stays put. + #[tokio::test] + async fn test_native_snapshot_pins_count_scan_and_version() { + use std::time::Duration; + + use crate::connection::ConnectBuilder; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = ConnectBuilder::new(temp_dir.path().to_str().unwrap()) + .read_consistency_interval(Duration::ZERO) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let snapshot = table + .base_table() + .snapshot_at_current_version() + .await + .unwrap() + .expect("native tables should provide an independent pinned handle"); + let version = snapshot.version().await.unwrap(); + assert_eq!(snapshot.count_rows(None).await.unwrap(), 10); + + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(5), BatchCount::from(1)); + table.add(more_data).execute().await.unwrap(); + assert!(table.version().await.unwrap() > version); + + assert_eq!(snapshot.version().await.unwrap(), version); + assert_eq!(snapshot.count_rows(None).await.unwrap(), 10); + let batches: Vec = Table::from(snapshot) + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 10); + assert_eq!(table.count_rows(None).await.unwrap(), 15); } #[cfg(feature = "remote")] @@ -855,4 +1095,89 @@ mod tests { ); assert!(metadata.contains_key(BASE_VERSION_CONFIG_KEY)); } + + #[tokio::test] + async fn test_permutation_persist_create_overwrite_and_namespace() { + use lance_namespace::models::CreateNamespaceRequest; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let initial_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(100), BatchCount::from(1)); + let data_table = db + .create_table("base_tbl", initial_data) + .execute() + .await + .unwrap(); + + let namespace_path = vec!["plans".to_string()]; + db.create_namespace(CreateNamespaceRequest { + id: Some(namespace_path.clone()), + ..Default::default() + }) + .await + .unwrap(); + + let persist = |mode| PermutationPersistOptions { + namespace_path: namespace_path.clone(), + mode, + }; + let first_plan = PermutationBuilder::new(data_table.clone()) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Create), + ) + .build() + .await + .unwrap(); + let first_version = first_plan.version().await.unwrap(); + assert_eq!(first_plan.count_rows(None).await.unwrap(), 100); + + let opened = db + .open_table("splits") + .namespace(namespace_path.clone()) + .execute() + .await + .unwrap(); + assert_eq!(opened.count_rows(None).await.unwrap(), 100); + + let err = PermutationBuilder::new(data_table.clone()) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Create), + ) + .build() + .await + .unwrap_err(); + assert!( + matches!(err, Error::TableAlreadyExists { .. }), + "expected TableAlreadyExists, got: {err:?}" + ); + + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(50), BatchCount::from(1)); + data_table.add(more_data).execute().await.unwrap(); + + let second_plan = PermutationBuilder::new(data_table) + .persist_with_options( + db.database().clone(), + "splits".to_string(), + persist(PermutationPersistMode::Overwrite), + ) + .build() + .await + .unwrap(); + assert_eq!(second_plan.count_rows(None).await.unwrap(), 150); + + // Overwrite creates a new table version; the old handle stays on its snapshot. + assert_eq!(first_plan.count_rows(None).await.unwrap(), 100); + assert_eq!(first_plan.version().await.unwrap(), first_version); + } } diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs index b4e5deac1..0fb7f669b 100644 --- a/rust/lancedb/src/dataloader/permutation/split.rs +++ b/rust/lancedb/src/dataloader/permutation/split.rs @@ -406,8 +406,8 @@ impl Splitter { .collect::>(); let row_ids = arrow::compute::concat(&row_id_arrays)?; // Sample against however many rows this scan actually returned, not the - // separately computed `num_rows` count checked by `validate` -- that count and - // this scan are two different queries, not pinned to one snapshot, so a + // separately computed `num_rows` count checked by `validate`. `apply` does + // not require its caller to pass a count and scan from one snapshot, so a // concurrent append or delete between them could otherwise push // `random_range` out of `row_ids`'s real bounds. let num_eligible_rows = row_ids.len() as u64; diff --git a/rust/lancedb/src/docs.rs b/rust/lancedb/src/docs.rs index ccfd1c28c..d69a1612c 100644 --- a/rust/lancedb/src/docs.rs +++ b/rust/lancedb/src/docs.rs @@ -169,7 +169,7 @@ impl DocLink { | Self::Views | Self::MaterializedViews | Self::PrewarmData - | Self::Authorization => "/enterprise", + | Self::Authorization => "/basics/embedded-vs-enterprise", } } @@ -519,6 +519,8 @@ mod tests { "DocLink::{link:?} points to a .mintignore'd page: {rel_page}" ); + // Mintlify serves MDX pages even when they are intentionally omitted + // from navigation, so docs.json membership is not required. let mdx_path = if docs_web.join(&direct_mdx).is_file() { docs_web.join(&direct_mdx) } else if docs_web.join(&index_mdx).is_file() { @@ -527,12 +529,6 @@ mod tests { panic!("DocLink::{link:?} target page does not exist under docs/web: {rel_page}"); }; - assert!( - docs_json.contains(&format!("\"{rel_page}\"")) - || docs_json.contains(&format!("\"{rel_page}/index\"")), - "DocLink::{link:?} target page is not routed in docs/web/docs.json: {rel_page}" - ); - if let Some(anchor) = link.anchor() { let raw_mdx = std::fs::read_to_string(&mdx_path) .unwrap_or_else(|e| panic!("failed to read {}: {e}", mdx_path.display())); diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index c31167148..3c8a485f9 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -27,6 +27,35 @@ pub struct HttpErrorDetails { pub namespace_path: Vec, } +/// Stable resource identity reported with a remote Flight SQL failure. +#[cfg(feature = "remote")] +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct RemoteResourceIdentity { + /// The kind of resource named by the error. + pub kind: String, + /// The leaf name of the resource. + pub name: String, + /// The parent namespace path of the resource. + pub namespace_path: Vec, +} + +#[cfg(feature = "remote")] +impl RemoteResourceIdentity { + /// Construct a resource identity as reported by a remote service. + pub fn new( + kind: impl Into, + name: impl Into, + namespace_path: Vec, + ) -> Self { + Self { + kind: kind.into(), + name: name.into(), + namespace_path, + } + } +} + /// Correlation and classification metadata reported by a remote server. /// /// Fields are absent when the server did not supply them. Diagnostic text is @@ -35,12 +64,16 @@ pub struct HttpErrorDetails { #[derive(Debug, Clone, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RemoteErrorMetadata { + /// Build of the executable that produced the error, when reported. + pub server: Option, /// Machine-readable input error code, when available. pub error_code: Option, /// SQL job that failed, when the request ran in an isolated job. pub job_id: Option, /// Request executed by the isolated SQL worker. pub job_request_id: Option, + /// Structured resource identity supplied by the server, when available. + pub resource: Option, } #[cfg(feature = "remote")] @@ -53,15 +86,44 @@ impl RemoteErrorMetadata { .map(str::to_owned) }; Self { + server: header("x-lancedb-server-build") + .and_then(|value| serde_json::from_str(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header("x-lancedb-sql-job-id"), job_request_id: header("x-job-request-id"), + resource: header("x-lancedb-resource") + .as_deref() + .and_then(parse_flight_resource_identity), } } } #[cfg(feature = "remote")] -#[derive(Debug)] +#[derive(Deserialize)] +struct FlightResourceIdentity { + kind: String, + name: String, + namespace_path: Vec, +} + +/// Decode the ASCII-safe structured resource metadata used by Flight SQL. +#[cfg(feature = "remote")] +pub(crate) fn parse_flight_resource_identity(value: &str) -> Option { + use base64::Engine as _; + + let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(value) + .ok()?; + let identity = serde_json::from_slice::(&bytes).ok()?; + Some(RemoteResourceIdentity { + kind: identity.kind, + name: identity.name, + namespace_path: identity.namespace_path, + }) +} + +#[cfg(feature = "remote")] +#[derive(Debug, Clone)] pub(crate) struct HttpErrorSource { message: String, details: Option, @@ -73,17 +135,28 @@ impl HttpErrorSource { pub(crate) fn new( message: String, response_body: Option<&str>, - metadata: RemoteErrorMetadata, + mut metadata: RemoteErrorMetadata, ) -> Self { let details = response_body.and_then(parse_http_error_details); + let body = + response_body.and_then(|body| serde_json::from_str::(body).ok()); + if metadata.server.is_none() { + metadata.server = body + .as_ref() + .and_then(|body| body.get("server").cloned()) + .and_then(|server| serde_json::from_value(server).ok()); + } let message = if metadata.error_code.is_some() { - response_body - .and_then(|body| serde_json::from_str::(body).ok()) + body.as_ref() .and_then(|body| body.get("error")?.as_str().map(str::to_owned)) .unwrap_or(message) } else { message }; + let message = match &metadata.server { + Some(server) => format!("{message} [server: {server}]"), + None => message, + }; Self { message, details, @@ -147,28 +220,96 @@ fn http_timeout_hint(source: &(dyn std::error::Error + 'static)) -> &'static str } } +/// The error that ended a streamed response. +/// +/// It is shared so that a copy of [`Error::ResponseInterrupted`] keeps it: +/// DataFusion hands one error to every partition that reads the failed input. +/// It dereferences to the underlying error, which is also the next error in the +/// source chain. +#[cfg(feature = "remote")] +#[derive(Debug, Clone)] +pub struct InterruptionSource(Arc); + +#[cfg(feature = "remote")] +impl From for InterruptionSource { + fn from(source: BoxError) -> Self { + Self(source.into()) + } +} + +#[cfg(feature = "remote")] +impl std::ops::Deref for InterruptionSource { + type Target = dyn std::error::Error + Send + Sync; + + fn deref(&self) -> &Self::Target { + self.0.as_ref() + } +} + +#[cfg(feature = "remote")] +impl Display for InterruptionSource { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +// Not `Error`: an `Arc` in the source chain hides the error it holds from +// `downcast_ref`, and so would a wrapper that implements `Error`. +#[cfg(feature = "remote")] +impl snafu::AsErrorSource for InterruptionSource { + fn as_error_source(&self) -> &(dyn std::error::Error + 'static) { + self.0.as_ref() + } +} + /// Why a job failed, to whatever precision the backend provides. /// /// A job run in this process carries the error it failed with in [`Self::source`]. /// A job run remotely carries whatever the server reported, which older servers /// do not report at all. Every field is absent rather than invented when the /// backend does not supply it. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] pub struct JobFailure { /// The stage the job was in, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub phase: Option, /// A human-readable reason, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, + /// User-code traceback, possibly truncated by the server. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub traceback: Option, /// Whether a retry could clear the failure, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub retryable: Option, /// Isolated SQL job that raised this failure, when the server supplies /// one across the Flight SQL boundary. + #[serde(default, skip_serializing_if = "Option::is_none")] pub sql_job_id: Option, /// The underlying error from a job run in this process or a structured /// remote Flight SQL failure. + #[serde(skip)] pub source: Option>, } +impl PartialEq for JobFailure { + fn eq(&self, other: &Self) -> bool { + let source_matches = match (&self.source, &other.source) { + (None, None) => true, + (Some(left), Some(right)) => Arc::ptr_eq(left, right), + _ => false, + }; + self.phase == other.phase + && self.message == other.message + && self.traceback == other.traceback + && self.retryable == other.retryable + && self.sql_job_id == other.sql_job_id + && source_matches + } +} + +impl Eq for JobFailure {} + impl JobFailure { /// A failure whose only known detail is the error that caused it. pub(crate) fn from_source(source: Arc) -> Self { @@ -191,6 +332,58 @@ impl Display for JobFailure { } } +fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static)) -> String { + #[cfg(feature = "remote")] + if let Some(server) = _source + .downcast_ref::() + .and_then(Error::remote_error_metadata) + .and_then(|metadata| metadata.server.as_ref()) + { + return format!(" [server: {server}]"); + } + String::new() +} + +/// Actionable guidance attached to a [`Error::TableNotFound`]. +/// +/// The hint is kept in the error source chain so the missing-table +/// classification and the original failure stay unchanged. +#[derive(Debug)] +pub(crate) struct TableNotFoundHint { + hint: String, + source: BoxError, +} + +impl TableNotFoundHint { + pub(crate) fn new(hint: impl Into, source: BoxError) -> Self { + Self { + hint: hint.into(), + source, + } + } +} + +impl Display for TableNotFoundHint { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str(&self.hint) + } +} + +impl std::error::Error for TableNotFoundHint { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(self.source.as_ref()) + } +} + +fn table_not_found_hint<'a>( + source: &'a (dyn std::error::Error + Send + Sync + 'static), +) -> &'a str { + source + .downcast_ref::() + .map(|hint| hint.hint.as_str()) + .unwrap_or_default() +} + #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { @@ -198,7 +391,11 @@ pub enum Error { InvalidTableName { name: String, reason: String }, #[snafu(display("Invalid input, {message}"))] InvalidInput { message: String }, - #[snafu(display("Table '{name}' was not found"))] + #[snafu(display( + "Table '{name}' was not found{}{}", + server_build_suffix(source.as_ref()), + table_not_found_hint(source.as_ref()) + ))] TableNotFound { name: String, source: BoxError }, #[snafu(display( "Table '{name}' exists but could not be loaded (it may be corrupt or incomplete): {source}" @@ -255,12 +452,12 @@ pub enum Error { #[snafu(display("Job{} failed{failure}", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobFailed { job_id: Option, - failure: JobFailure, + failure: Box, }, #[snafu(display("Job{} was cancelled", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobCancelled { job_id: Option }, - #[snafu(display("Job '{job_id}' was not found"))] - JobNotFound { job_id: String }, + #[snafu(display("Job '{job_id}' was not found{}", server_build_suffix(source.as_ref())))] + JobNotFound { job_id: String, source: BoxError }, // 3rd party / external errors #[snafu(display("object_store error: {source}"))] @@ -302,6 +499,27 @@ pub enum Error { source: Box, status_code: Option, }, + /// A streamed response stopped before the server signalled that it was complete. + /// + /// The batches already returned are valid, but the result is incomplete. The + /// request is not retried, because re-issuing it would return those batches + /// again. `table_version` is the table version the response reflected, when + /// the server reported one, so a caller can re-issue the request against it. + #[cfg(feature = "remote")] + #[snafu(display( + "Response for request_id={request_id} interrupted after {batches} batches \ + ({rows} rows): {source}{}", + http_timeout_hint(&**source) + ))] + ResponseInterrupted { + request_id: String, + /// Batches returned before the interruption. + batches: u64, + /// Rows in those batches. + rows: u64, + table_version: Option, + source: InterruptionSource, + }, #[snafu(display("Arrow error: {source}"))] Arrow { source: ArrowError }, #[snafu(display("LanceDBError: not supported: {message}"))] @@ -333,6 +551,20 @@ impl From for Error { match source { DataFusionError::ArrowError(source, _) => (*source).into(), DataFusionError::External(source) => Self::from_box_error(source), + // DataFusion adds context to an error, and shares one error between + // the partitions that read a failed input. An error of ours beneath + // either keeps its type; other errors keep the wrapper's message. + DataFusionError::Context(_, inner) if find_error(inner.as_ref()).is_some() => { + (*inner).into() + } + DataFusionError::Shared(shared) => match Arc::try_unwrap(shared) { + Ok(inner) => inner.into(), + Err(shared) => find_error(shared.as_ref()) + .and_then(Self::clone_shared) + .unwrap_or_else(|| Self::External { + source: Box::new(DataFusionError::Shared(shared)), + }), + }, other => Self::External { source: Box::new(other), }, @@ -340,6 +572,12 @@ impl From for Error { } } +/// The first error of ours in an error's source chain. +fn find_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Error> { + std::iter::successors(Some(error), |error| error.source()) + .find_map(|error| error.downcast_ref::()) +} + impl From for Error { fn from(source: lance::Error) -> Self { if has_unsupported_local_filesystem_source(&source) { @@ -400,6 +638,25 @@ fn has_unsupported_local_filesystem_source(error: &(dyn std::error::Error + 'sta } impl Error { + /// HTTP status associated with a remote request error. + /// + /// Retry wrappers preserve the underlying status. Other error variants do + /// not represent an HTTP response and return `None`. + #[cfg(feature = "remote")] + pub fn status_code(&self) -> Option { + match self { + Self::Http { status_code, .. } => *status_code, + Self::Retry { status_code, .. } => *status_code, + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => { + source.downcast_ref::().and_then(Self::status_code) + } + Self::JobFailed { failure, .. } => { + failure.source.as_deref().and_then(Self::status_code) + } + _ => None, + } + } + /// Structured resource details reported by a remote HTTP error. /// /// Older servers do not include these fields, in which case this returns @@ -437,7 +694,7 @@ impl Error { Self::Retry { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), - Self::TableNotFound { source, .. } => source + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), Self::JobFailed { failure, .. } => failure @@ -449,6 +706,55 @@ impl Error { } } + /// Copy supported errors without flattening sources retained by a shared plan + /// or schema cache. + pub(crate) fn clone_shared(&self) -> Option { + #[cfg(feature = "remote")] + match self { + Self::Http { + source, + request_id, + status_code, + } => { + return source + .downcast_ref::() + .map(|source| Self::Http { + source: Box::new(source.clone()), + request_id: request_id.clone(), + status_code: *status_code, + }); + } + Self::TableNotFound { name, source } => { + return source + .downcast_ref::() + .and_then(Self::clone_shared) + .map(|source| Self::TableNotFound { + name: name.clone(), + source: Box::new(source), + }); + } + _ => {} + } + #[cfg(feature = "remote")] + if let Self::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = self + { + return Some(Self::ResponseInterrupted { + request_id: request_id.clone(), + batches: *batches, + rows: *rows, + table_version: *table_version, + source: source.clone(), + }); + } + None + } + fn from_box_error(mut source: Box) -> Self { source = match source.downcast::() { Ok(e) => match *e { @@ -559,6 +865,67 @@ mod tests { assert!(matches!(Error::from(source), Error::InvalidInput { .. })); } + /// DataFusion shares an error between the partitions that read a failed + /// input, and may add context to it. Whether or not another partition still + /// holds it, an interrupted response keeps its fields and its source. + #[cfg(feature = "remote")] + #[rstest::rstest] + fn shared_interruption_keeps_its_type_and_source( + #[values(false, true)] still_held: bool, + #[values(false, true)] with_context: bool, + ) { + let reset = BoxError::from(std::io::Error::from(std::io::ErrorKind::ConnectionReset)); + let interrupted = Error::ResponseInterrupted { + request_id: "req-1".into(), + batches: 2, + rows: 2048, + table_version: Some(7), + source: reset.into(), + }; + let shared = Arc::new(DataFusionError::External(Box::new(interrupted))); + let held = still_held.then(|| shared.clone()); + let mut error = DataFusionError::Shared(shared); + if with_context { + error = error.context("merging query results"); + } + + let error = Error::from(error); + + assert!( + matches!( + &error, + Error::ResponseInterrupted { + request_id, + batches: 2, + rows: 2048, + table_version: Some(7), + .. + } if request_id == "req-1" + ), + "{error:?}" + ); + let source = std::error::Error::source(&error).unwrap(); + assert_eq!( + source.downcast_ref::().map(|e| e.kind()), + Some(std::io::ErrorKind::ConnectionReset) + ); + drop(held); + } + + #[test] + fn other_shared_errors_keep_their_message() { + let shared = Arc::new(DataFusionError::Execution("boom".into())); + let _held = shared.clone(); + + let error = Error::from(DataFusionError::Shared(shared).context("merging")); + + assert!(matches!(error, Error::External { .. }), "{error:?}"); + assert_eq!( + error.to_string(), + "merging\ncaused by\nExecution error: boom" + ); + } + #[cfg(feature = "remote")] #[test] fn non_timeout_http_error_message_is_unchanged() { diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 8933d0b37..5e50abecb 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -16,6 +16,9 @@ use serde_json::Value; use crate::secrets::SecretBinding; use crate::{Error, Result}; +mod retry; +pub use retry::{FunctionErrorPolicy, FunctionRetryPolicy}; + /// Semantic Function type for a Blob v2 value. pub const FUNCTION_BLOB_V2_TYPE: &str = "blob_v2"; @@ -108,7 +111,7 @@ fn from_json(json: &str) -> Result { serde_json::from_str(json).map_err(invalid_json) } -fn validate_literal(value: &Value) -> Result<()> { +pub(crate) fn validate_literal(value: &Value) -> Result<()> { match value { Value::Number(number) if number.is_f64() => Err(Error::InvalidInput { message: "floating-point Function literals are not part of the Slice 1 canonical wire contract" @@ -159,15 +162,23 @@ fn application_has_unknown_nested_fields(value: &Value) -> bool { return true; } application.get("output").is_some_and(|output| { - has_unknown_keys(output, &["kind", "arrow_type", "nullable", "fields"]) - || output - .get("fields") - .and_then(Value::as_array) - .is_some_and(|fields| { - fields - .iter() - .any(|field| has_unknown_keys(field, &["name", "arrow_type", "nullable"])) - }) + has_unknown_keys( + output, + &[ + "kind", + "arrow_type", + "nullable", + "fields", + "blob_writer_paths", + ], + ) || output + .get("fields") + .and_then(Value::as_array) + .is_some_and(|fields| { + fields + .iter() + .any(|field| has_unknown_keys(field, &["name", "arrow_type", "nullable"])) + }) }) } @@ -221,6 +232,23 @@ pub struct FunctionResultField { pub nullable: bool, } +/// One step from the Function result root to a writer-capable Blob v2 leaf. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(untagged, deny_unknown_fields)] +pub enum BlobWriterPathStep { + /// A struct child addressed by its literal Arrow field name. + Field { field: String }, + /// A list value field, independent of its name. + ListItem(BlobWriterListItem), +} + +/// The list step in a Blob writer path, encoded as `"item"`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BlobWriterListItem { + Item, +} + /// Scalar or named-struct Function output. /// /// `kind` remains a string so unknown future result shapes can be decoded. @@ -233,6 +261,11 @@ pub struct FunctionOutput { pub nullable: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub fields: Vec, + /// Writer-capable Blob v2 leaves in `scalar_blob_writer` and + /// `named_struct_blob_writer` results. An empty path denotes a scalar + /// Blob result; an empty list denotes a result with no writer leaves. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub blob_writer_paths: Vec>, } /// Ordered language-neutral Function signature. @@ -302,6 +335,7 @@ pub enum PythonRuntimeSpec { /// }, /// env: BTreeMap::new(), /// gpu_class: Some("a10g".to_string()), + /// gpus_per_worker: std::num::NonZeroU32::new(2), /// }; /// assert!(runtime.requires_gpu()); /// ``` @@ -309,8 +343,10 @@ pub enum PythonRuntimeSpec { python_version: String, environment: PythonEnvironmentSpec, env: BTreeMap, - /// Operator-defined GPU class; absent uses the deployment default. + /// Operator-defined GPU class; absent accepts any eligible configured class. gpu_class: Option, + /// GPUs allocated together to each worker. + gpus_per_worker: Option, }, /// A runtime kind introduced by a newer server. /// @@ -362,17 +398,30 @@ impl PythonRuntimeSpec { matches!(self, Self::PythonV2 { .. }) } - /// Operator-defined GPU class, or `None` to use the deployment default. + /// Requested GPU class; `None` and `"any"` both accept any eligible class. + /// This does not identify the hardware selected for execution. pub fn gpu_class(&self) -> Option<&str> { match self { Self::PythonV2 { gpu_class, .. } => gpu_class.as_deref(), _ => None, } } + + /// GPUs allocated to one worker; zero for CPU runtimes. + pub fn gpus_per_worker(&self) -> u32 { + match self { + Self::PythonV2 { + gpus_per_worker, .. + } => gpus_per_worker.map_or(1, std::num::NonZeroU32::get), + _ => 0, + } + } } #[derive(Deserialize)] struct PythonRuntimeV1Wire { + #[serde(default)] + gpus_per_worker: Option, python_version: String, environment: PythonEnvironmentSpec, #[serde(default)] @@ -385,6 +434,8 @@ struct PythonRuntimeV1Wire { #[derive(Deserialize)] struct PythonRuntimeV2Wire { + #[serde(default)] + gpus_per_worker: Option, python_version: String, environment: PythonEnvironmentSpec, #[serde(default)] @@ -417,6 +468,11 @@ impl<'de> Deserialize<'de> for PythonRuntimeSpec { "python runtime with gpu_class requires kind='python_v2'", )); } + if wire.gpus_per_worker.is_some() { + return Err(de::Error::custom( + "gpus_per_worker requires kind='python_v2'", + )); + } Ok(Self::Python { python_version: wire.python_version, environment: wire.environment, @@ -437,6 +493,7 @@ impl<'de> Deserialize<'de> for PythonRuntimeSpec { environment: wire.environment, env: wire.env, gpu_class: wire.gpu_class, + gpus_per_worker: wire.gpus_per_worker, }) } _ => Ok(Self::Unrecognized { kind }), @@ -457,6 +514,8 @@ impl Serialize for PythonRuntimeSpec { gpu: Option, #[serde(skip_serializing_if = "Option::is_none")] gpu_class: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + gpus_per_worker: Option, } #[derive(Serialize)] @@ -476,6 +535,7 @@ impl Serialize for PythonRuntimeSpec { env, gpu: None, gpu_class: None, + gpus_per_worker: None, } .serialize(serializer), Self::PythonV2 { @@ -483,6 +543,7 @@ impl Serialize for PythonRuntimeSpec { environment, env, gpu_class, + gpus_per_worker, } => PythonRuntimeRef { kind: "python_v2", python_version, @@ -490,6 +551,7 @@ impl Serialize for PythonRuntimeSpec { env, gpu: Some(true), gpu_class: gpu_class.as_deref(), + gpus_per_worker: *gpus_per_worker, } .serialize(serializer), Self::Unrecognized { kind } => UnrecognizedRuntimeRef { kind }.serialize(serializer), @@ -518,6 +580,59 @@ pub struct HuggingFaceModel { pub revision: String, } +/// One installed Python distribution as measured from a Function's baked +/// environment. +/// +/// `version` is the complete version string reported by the package metadata, +/// including local labels such as `+cu130`. `source` is present only when the +/// submitted lock retained a per-package source; a missing value is unknown and +/// must not be inferred from other package indexes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedPackage { + pub name: String, + pub version: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, +} + +/// Sanitized source and accelerator provenance retained with a resolved +/// environment. +/// +/// `configured_*` records what the build was asked to use. `resolved_indexes` +/// records indexes visible in the submitted lock, so a configured source is +/// not mistaken for evidence that a package came from it. Empty lists and +/// absent fields remain absent rather than being synthesized by the client. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedEnvironmentProvenance { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub configured_index_urls: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub configured_find_links: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub resolved_indexes: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cuda_toolkit: Option, + /// The fully resolved `torch==` when torch was installed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub torch_version: Option, +} + +/// Actual installed distributions and registration warnings for one native +/// Function environment. +/// +/// A missing environment means its measurement is unknown, not an empty +/// installed-package list. The field keeps the complete versions and only the +/// provenance the producer recorded; SDK readers do not recompute package +/// policy. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedEnvironment { + pub packages: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provenance: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, +} + /// A complete OCI Function image. Its digest is independent of catalog names. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionImage { @@ -541,10 +656,76 @@ fn deserialize_object_version<'de, D: Deserializer<'de>>( } } +/// A positive, finite per-call deadline reported by the catalog. +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[serde(transparent)] +struct RowTimeoutSeconds(f64); + +impl Eq for RowTimeoutSeconds {} + +impl RowTimeoutSeconds { + fn get(self) -> f64 { + self.0 + } +} + +impl<'de> Deserialize<'de> for RowTimeoutSeconds { + fn deserialize>(deserializer: D) -> std::result::Result { + let seconds = f64::deserialize(deserializer)?; + if !seconds.is_finite() || seconds <= 0.0 { + return Err(de::Error::custom( + "row_timeout_seconds must be positive and finite", + )); + } + Ok(Self(seconds)) + } +} + +// Function inspection includes this build setting alongside the SDK's authored +// runtime spec. Keep it on the readback model so registration keeps its own wire shape. +#[derive(Debug, Clone, PartialEq, Eq)] +struct RequestedPythonRuntime { + spec: PythonRuntimeSpec, + index_url: Option, +} + +impl<'de> Deserialize<'de> for RequestedPythonRuntime { + fn deserialize>(deserializer: D) -> std::result::Result { + let document = Value::deserialize(deserializer)?; + let index_url = document + .pointer("/environment/build/index_url") + .and_then(Value::as_str) + .map(str::to_owned); + let spec: PythonRuntimeSpec = + serde_json::from_value(document).map_err(de::Error::custom)?; + let index_url = spec.environment().and(index_url); + Ok(Self { spec, index_url }) + } +} + +impl Serialize for RequestedPythonRuntime { + fn serialize(&self, serializer: S) -> std::result::Result { + let Some(index_url) = &self.index_url else { + return self.spec.serialize(serializer); + }; + let mut document = serde_json::to_value(&self.spec).map_err(serde::ser::Error::custom)?; + document["environment"]["build"] = serde_json::json!({"index_url": index_url}); + document.serialize(serializer) + } +} + /// One immutable Function object revision and its executable artifact. /// /// The Function is named by its parts, `name` and `namespace_path`, the way a /// [`SecretReference`](crate::secrets::SecretReference) names a Secret. +/// +/// Unknown top-level fields from newer servers are accepted for forward +/// decoding, but they are not part of this value and are omitted from +/// canonical JSON. Known fields retain their complete values, while unknown +/// fields inside the open [`FunctionImage::descriptor`] JSON object remain +/// available. Single-platform measurements use `resolved_environment`; +/// multiarchitecture measurements use `resolved_environments`, keyed by OCI +/// `os/architecture`, without flattening the platforms. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionVersion { name: String, @@ -560,6 +741,8 @@ pub struct FunctionVersion { image: FunctionImage, #[serde(default, skip_serializing_if = "Option::is_none")] source_digest: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime_digest: Option, signature: FunctionSignature, #[serde(default, skip_serializing_if = "Vec::is_empty")] secret_bindings: Vec, @@ -570,6 +753,66 @@ pub struct FunctionVersion { /// Operator-defined GPU class declared at registration. #[serde(default, skip_serializing_if = "Option::is_none")] gpu_class: Option, + /// Default maximum rows in one callable batch. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_batch_size" + )] + batch_size: Option, + /// Default maximum concurrent user-code calls per logical execution. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_max_concurrency" + )] + max_concurrency: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_cpu_millis" + )] + total_cpu_millis: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_memory_bytes" + )] + total_memory_bytes: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_gpu_count" + )] + total_gpu_count: Option, + /// Per-call deadline in seconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + row_timeout_seconds: Option, + /// Result-stability value declared at registration. + #[serde(default, skip_serializing_if = "Option::is_none")] + result_stability: Option, + /// The runtime requested at registration, with submitted lock bytes omitted. + /// + /// This is a specification, not the measured installation. Compare it with + /// [`Self::resolved_environment`] when the caller needs actual package + /// versions. + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime: Option, + /// Actual installed distributions, provenance, and registration warnings. + /// + /// This is the single-platform compatibility field. `None` on a + /// multiarchitecture version is expected; use + /// [`Self::resolved_environments`] for its per-platform measurements. + #[serde(default, skip_serializing_if = "Option::is_none")] + resolved_environment: Option, + /// Measurements for a multiarchitecture image, keyed by OCI + /// `os/architecture`. + /// + /// Unmeasured platforms are absent. An empty map is unknown, not an + /// aggregate of packages from the available platforms. Single-platform + /// images use [`Self::resolved_environment`] instead. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + resolved_environments: BTreeMap, } impl FunctionVersion { @@ -611,7 +854,9 @@ impl FunctionVersion { /// Digest of the registered source artifact, when provided by the server. /// /// Compare this with [`FunctionArtifactRequest::digest`] to identify matching - /// source, independently of the built image's manifest digest. + /// source, independently of the built image's manifest digest. It excludes + /// dependencies, environment variables, Python version, and GPU settings; + /// matching source alone does not establish that a version can be reused. /// /// ``` /// use lancedb::function::{FunctionArtifactRequest, FunctionVersion}; @@ -624,11 +869,94 @@ impl FunctionVersion { self.source_digest.as_deref() } + /// Digest of canonical runtime inputs, when provided by the server. + /// + /// Compare it with the digest of a locally authored runtime. The runtime + /// projection on this version can omit inputs needed to reproduce the digest. + /// A missing digest cannot establish that a local runtime matches. Reusing a + /// version also requires matching its source and other registration inputs. + pub fn runtime_digest(&self) -> Option<&str> { + self.runtime_digest.as_deref() + } + /// Operator-defined GPU class declared at registration. pub fn gpu_class(&self) -> Option<&str> { self.gpu_class.as_deref() } + /// Default total CPU budget for executions of this pinned Function. + pub fn total_cpu_millis(&self) -> Option { + self.total_cpu_millis + } + + /// Default total memory budget for executions of this pinned Function. + pub fn total_memory_bytes(&self) -> Option { + self.total_memory_bytes + } + + /// Default aggregate GPU budget, independent of the per-worker device count. + pub fn total_gpu_count(&self) -> Option { + self.total_gpu_count + } + + /// Default maximum rows in one callable batch, when declared. + pub fn batch_size(&self) -> Option { + self.batch_size + } + + /// Default maximum concurrent user-code calls, when declared. + pub fn max_concurrency(&self) -> Option { + self.max_concurrency + } + + /// Per-call deadline in seconds, when declared. + pub fn row_timeout_seconds(&self) -> Option { + self.row_timeout_seconds.map(RowTimeoutSeconds::get) + } + + /// Result-stability value declared at registration, when present. + pub fn result_stability(&self) -> Option<&str> { + self.result_stability.as_deref() + } + + /// Runtime metadata requested at registration and exposed by the server. + /// + /// This view can omit input needed to reproduce [`Self::runtime_digest`]. + /// Read the explicit primary package index with [`Self::requested_index_url`], + /// and inspect installed distributions with [`Self::resolved_environment`]. + pub fn runtime(&self) -> Option<&PythonRuntimeSpec> { + self.runtime.as_ref().map(|runtime| &runtime.spec) + } + + /// Explicit primary package index URL requested for this Function version. + /// + /// An absent value can still accompany extra indexes, other sources, or + /// service defaults. For build provenance, see [`ResolvedEnvironmentProvenance`]. + pub fn requested_index_url(&self) -> Option<&str> { + self.runtime.as_ref()?.index_url.as_deref() + } + + /// Actual installed distributions and registration warnings for a + /// single-platform image, when measured by the server. + /// + /// `None` is unknown, not an empty environment. Package versions are + /// retained verbatim, including local labels such as `+cu130`; `source` + /// remains absent when the producer did not retain it. + pub fn resolved_environment(&self) -> Option<&ResolvedEnvironment> { + self.resolved_environment.as_ref() + } + + /// Per-platform measurements for a multiarchitecture image, keyed by OCI + /// `os/architecture`. + /// + /// The map is returned without flattening or synthesis. A missing platform + /// means its measurement is unknown; an empty environment value is a + /// measured empty environment and is retained. Single-platform images use + /// [`Self::resolved_environment`] instead. + pub fn resolved_environments(&self) -> &BTreeMap { + &self.resolved_environments + } + pub fn signature(&self) -> &FunctionSignature { &self.signature } @@ -661,7 +989,7 @@ pub struct FunctionArtifactContent { /// Internal execution adapter selected for a Python callable artifact. /// -/// This is part of the executor request envelope, not the user-facing UDF +/// This is part of the executor request envelope, not the user-facing Function /// authoring mode. For version 1, the executor selects vectorized execution /// when every callable parameter is annotated as `pyarrow.Array`; it passes one /// Arrow array per declared input and requires an Arrow array matching the @@ -707,6 +1035,56 @@ where Ok(value) } +fn deserialize_total_cpu_millis<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + let value = Option::::deserialize(deserializer) + .map_err(|error| de::Error::custom(format!("total_cpu_millis: {error}")))?; + if value == Some(0) { + return Err(de::Error::custom("total_cpu_millis must be positive")); + } + Ok(value) +} + +fn deserialize_total_memory_bytes<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + let value = Option::::deserialize(deserializer) + .map_err(|error| de::Error::custom(format!("total_memory_bytes: {error}")))?; + if value == Some(0) { + return Err(de::Error::custom("total_memory_bytes must be positive")); + } + Ok(value) +} + +fn deserialize_total_gpu_count<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + Option::::deserialize(deserializer) + .map_err(|error| de::Error::custom(format!("total_gpu_count: {error}"))) +} + +fn deserialize_max_concurrency<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + let value = Option::::deserialize(deserializer) + .map_err(|error| de::Error::custom(format!("max_concurrency: {error}")))?; + validate_max_concurrency_value(value).map_err(de::Error::custom)?; + Ok(value) +} + fn validate_batch_size_value(value: Option) -> std::result::Result<(), &'static str> { if value == Some(0) { return Err("batch_size must be between 1 and u32::MAX"); @@ -714,6 +1092,13 @@ fn validate_batch_size_value(value: Option) -> std::result::Result<(), &'st Ok(()) } +fn validate_max_concurrency_value(value: Option) -> std::result::Result<(), &'static str> { + if value == Some(0) { + return Err("max_concurrency must be between 1 and u32::MAX"); + } + Ok(()) +} + fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'static str> { if value.is_some_and(|seconds| !seconds.is_finite() || seconds <= 0.0) { return Err("row_timeout_seconds must be positive and finite"); @@ -721,6 +1106,10 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s Ok(()) } +fn is_false(value: &bool) -> bool { + !*value +} + /// Stable request envelope for remote immutable Function registration. /// /// Credential values deliberately have no field here. The only secret-shaped @@ -728,9 +1117,16 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s /// database already holds, which Sophon resolves inside the remote runtime. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FunctionRegistrationRequest { + /// Preserve an existing named Function version instead of registering a new one. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, + /// Default retries of failed user-code calls. Enterprise only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retry_policy: Option, pub name: String, pub artifact: FunctionArtifactRequest, pub signature: FunctionSignature, + #[serde(deserialize_with = "deserialize_registration_runtime")] pub runtime: PythonRuntimeSpec, /// Maximum rows in one execution batch; the executor may use fewer. #[serde( @@ -739,6 +1135,36 @@ pub struct FunctionRegistrationRequest { deserialize_with = "deserialize_batch_size" )] pub batch_size: Option, + /// Default maximum concurrent user-code calls for each logical execution + /// of this Function version. Omission leaves the current behavior + /// unchanged. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_max_concurrency" + )] + pub max_concurrency: Option, + /// Default total CPU capacity for one execution, in millicores. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_cpu_millis" + )] + pub total_cpu_millis: Option, + /// Default total memory for one execution, in bytes. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_memory_bytes" + )] + pub total_memory_bytes: Option, + /// Default total GPUs across one execution's workers. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_total_gpu_count" + )] + pub total_gpu_count: Option, /// Deadline for each Python call, in seconds: one row for scalar Functions /// and one batch for vectorized Functions. It does not govern Function /// initialization. @@ -756,10 +1182,31 @@ pub struct FunctionRegistrationRequest { /// Model snapshots prepared by the service before user code runs. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, + /// Ask the service to resolve a fresh environment lock for this request + /// instead of reusing the published version's lock. Omitted when false. + #[serde(default, skip_serializing_if = "is_false")] + pub refresh_lock: bool, +} + +fn deserialize_registration_runtime<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let document = Value::deserialize(deserializer)?; + match document.pointer("/environment/build") { + None | Some(Value::Null) => {} + Some(Value::Object(build)) if build.is_empty() => {} + Some(_) => { + return Err(de::Error::custom( + "runtime.environment.build is unsupported in typed Function registration", + )); + } + } + serde_json::from_value(document).map_err(de::Error::custom) } impl FunctionRegistrationRequest { /// Decode a registration request supplied by an SDK language binding. + /// Nonempty environment build settings are rejected by this typed API. pub fn from_json(json: &str) -> Result { from_json(json) } @@ -775,8 +1222,17 @@ impl FunctionRegistrationRequest { let invalid_input = |message: &'static str| Error::InvalidInput { message: message.to_string(), }; + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { + return Err(invalid_input( + "total_cpu_millis and total_memory_bytes must be positive integers", + )); + } validate_batch_size_value(self.batch_size).map_err(invalid_input)?; + validate_max_concurrency_value(self.max_concurrency).map_err(invalid_input)?; validate_row_timeout_value(self.row_timeout_seconds).map_err(invalid_input)?; + if let Some(policy) = &self.retry_policy { + policy.validate()?; + } Ok(()) } } @@ -889,6 +1345,18 @@ pub struct InputBinding { pub nullable: bool, } +/// Constant value bound to a Function parameter for every input row. +/// +/// Values use the same canonical JSON domain as [`ApplicationInput`]. The +/// Enterprise service validates their types against the exact Function version. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LiteralInputBinding { + /// Function parameter name, distinct from all column-bound parameters. + pub parameter: String, + /// Immutable canonical JSON value. + pub value: Value, +} + /// Ordered result-field to table-field mapping for a Function binding. /// /// `nullable` describes the logical Function result. Physical computed-column @@ -903,8 +1371,8 @@ pub struct OutputMapping { pub nullable: bool, } -/// Internal physical column preserving the parent validity of a flattened -/// named-struct result. +/// Internal physical column preserving assignment of a nullable scalar result +/// or the parent validity of a flattened named-struct result. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AssignmentMapping { pub output_name: String, @@ -917,6 +1385,8 @@ pub struct FunctionBinding { binding_id: String, function: FunctionVersionRef, inputs: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + literal_inputs: Vec, outputs: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] assignment: Option, @@ -947,6 +1417,30 @@ impl FunctionBinding { &self.inputs } + /// Constants supplied for every row; these are not table dependencies. + pub fn literal_inputs(&self) -> &[LiteralInputBinding] { + &self.literal_inputs + } + + pub(crate) fn validate_inputs(&self) -> Result<()> { + let mut parameters = std::collections::HashSet::new(); + for parameter in self + .inputs + .iter() + .map(|input| &input.parameter) + .chain(self.literal_inputs.iter().map(|input| &input.parameter)) + { + if !parameters.insert(parameter) { + return Err(invalid_json(format!( + "duplicate Function parameter '{parameter}'" + ))); + } + } + self.literal_inputs + .iter() + .try_for_each(|input| validate_literal(&input.value)) + } + pub fn outputs(&self) -> &[OutputMapping] { &self.outputs } @@ -969,7 +1463,60 @@ impl FunctionBinding { } } -impl_json!(FunctionBinding); +impl FunctionBinding { + /// Decode an immutable binding, validating its canonical input values. + pub fn from_json(json: &str) -> Result { + let binding: Self = from_json(json)?; + binding.validate_inputs()?; + Ok(binding) + } + + /// Encode this binding without dropping its constant inputs. + pub fn to_canonical_json(&self) -> Result { + self.validate_inputs()?; + canonical_json(self) + } +} + +/// One byte-bounded size tier of a Function refresh plan. +/// +/// A row belongs to the first tier whose `max_row_bytes` admits its total +/// descriptor payload size. The final tier has no upper bound and carries the +/// largest configured worker class. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionRefreshTier { + /// Inclusive upper bound of the rows this tier admits. `None` on the last + /// tier, which also serves rows larger than every configured class. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_row_bytes: Option, + /// Worker resource class selected for this tier. + pub worker_class: String, + /// Worker container memory limit for `worker_class`. + pub worker_memory_bytes: u64, + /// Logical UDF executor budget derived from the worker limit. + pub executor_budget_bytes: u64, + /// Byte target for one materialized Blob input batch on this tier. + pub batch_bytes: u64, + /// Rows assigned to this tier. + pub rows: u64, + /// Byte-bounded batches the assigned rows form at `batch_bytes`. + pub batches: u64, +} + +/// Descriptor-derived tier plan for one Function refresh. +/// +/// The plan is computed from Blob descriptor sizes before any payload read. It +/// names the same worker classes the refresh supervisor uses for routing. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionRefreshPlan { + /// Worker class the supervisor starts ordinary work on. + pub default_worker_class: String, + /// Row cap supplied through the `batch_size` override, when present. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub batch_size: Option, + /// Tiers ordered from the smallest to the largest worker class. + pub tiers: Vec, +} /// Stable terminal result of an expression-backed or Function-backed column /// refresh [`crate::Job`]. @@ -978,6 +1525,12 @@ impl_json!(FunctionBinding); /// Enterprise decodes the same value from the durable job's terminal payload. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshColumnResult { + /// Grouped row failures, when the server reports them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub error_groups: Vec, + /// Whether the grouped counts omit any failures. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub error_groups_truncated: bool, /// Rows assigned a value by this refresh. pub rows_assigned: u64, /// Rows whose computation failed. @@ -989,6 +1542,10 @@ pub struct RefreshColumnResult { /// Table version made visible by the refresh, when one was published. #[serde(default, skip_serializing_if = "Option::is_none")] pub published_version: Option, + /// Descriptor-derived tier plan, when the refresh is Function-backed and + /// its inputs expose Blob descriptor sizes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, } /// Which per-row errors [`crate::Table::function_errors`] lists. Every @@ -996,6 +1553,8 @@ pub struct RefreshColumnResult { /// covers every refresh of every column. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct FunctionErrorsRequest { + /// Include retained historical errors, including repaired rows. + pub history: bool, /// Only errors recorded by this job. pub job_id: Option, /// Only errors on this column. @@ -1003,9 +1562,17 @@ pub struct FunctionErrorsRequest { /// At most this many records; the server default is 10000 and its cap /// 100000. [`FunctionErrors::truncated`] says whether the cap was hit. pub limit: Option, + /// Empty starts retained history for an exact job_id, including repaired rows. + /// A returned token continues that history regardless of `history`. + pub page_token: Option, } impl FunctionErrorsRequest { + /// Include retained historical records instead of current failures. + pub fn history(mut self, history: bool) -> Self { + self.history = history; + self + } /// A request with no filter. pub fn new() -> Self { Self::default() @@ -1028,6 +1595,13 @@ impl FunctionErrorsRequest { self.limit = Some(limit); self } + + /// Start with an empty token, then continue using the response's token. + /// Paging requires an exact job_id and a supporting backend. + pub fn page_token(mut self, token: impl Into) -> Self { + self.page_token = Some(token.into()); + self + } } /// One row a Function refresh skipped, as the server recorded it. The @@ -1035,6 +1609,21 @@ impl FunctionErrorsRequest { /// read access to the table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrorRecord { + /// Earliest retained failure time for this current failure. + #[serde(default)] + pub first_seen_at_millis: Option, + /// Most recent failure time. + #[serde(default)] + pub last_seen_at_millis: Option, + /// Whether normal refreshes skip this row until explicitly retried. + #[serde(default)] + pub quarantined: bool, + /// Source identities for a materialized-view Function invocation. + #[serde(default)] + pub input: Option, + /// Number of user-code calls for this failed invocation, when recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub attempts: Option, /// The refresh job that recorded the error. pub job_id: String, /// The fragment holding the row. @@ -1043,6 +1632,13 @@ pub struct FunctionErrorRecord { /// detail was capped and only the fragment summary remains. #[serde(default)] pub row_offset: Option, + /// Stable row identity at the table version the refresh read. + /// + /// Present only when that version used stable row IDs. It remains valid + /// across later compaction and rewrite, unlike `row_address`. `None` on + /// legacy tables and on records written before the server reported it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub row_id: Option, /// Portable physical row address, `(fragment_id << 32) | row_offset`. /// /// `None` when the record covers a fragment rather than one row, or when @@ -1061,6 +1657,9 @@ pub struct FunctionErrorRecord { pub error_type: String, /// The error's text. pub error_message: String, + /// User-code traceback, possibly truncated by the server. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub traceback: Option, /// When the error was recorded, in milliseconds since the epoch. pub created_at_millis: i64, } @@ -1082,6 +1681,12 @@ pub struct FunctionErrorFragment { /// A table's per-row Function errors; see [`crate::Table::function_errors`]. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrors { + /// Version of the server's current-failure, retry, upgrade, and quarantine contract. + #[serde(default)] + pub workflow_version: Option, + /// Grouped causes for the returned records. Counts are bounded by the listing. + #[serde(default)] + pub error_groups: Vec, /// The recorded rows, newest job first. pub records: Vec, /// Fragments whose detail was capped. @@ -1090,6 +1695,83 @@ pub struct FunctionErrors { /// Whether the listing stopped at its limit. #[serde(default)] pub truncated: bool, + /// Continue this exact job/filter, or `None` when a paged read is complete. + /// Older servers and legacy non-paged reads omit this field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub page_token: Option, +} + +/// Which existing rows to recompute when upgrading a Function column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionRecompute { + /// Recompute exactly the current failures. + Failed, + /// Recompute all live rows. + All, + /// Preserve existing values; new and changed rows use the new Function. + None, +} + +/// One cause in a Function failure listing or refresh result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionErrorGroup { + pub column: String, + pub error_type: String, + pub error_message: String, + pub rows_failed: u64, +} + +/// Selection and state for explicitly quarantining or releasing failed rows. +#[derive(Debug, Clone, Serialize)] +pub struct FunctionQuarantineOptions { + pub quarantined: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub job_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub after_attempts: Option, +} + +impl Default for FunctionQuarantineOptions { + fn default() -> Self { + Self { + quarantined: true, + job_id: None, + error_type: None, + after_attempts: None, + } + } +} + +/// Which snapshot and how much producing-version metadata to read. +#[derive(Debug, Clone, Default, Serialize)] +pub struct FunctionProvenanceOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// The Function and job that produced one stored value. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionValueProvenance { + pub job_id: String, + pub column: String, + pub function_name: String, + pub function_version: String, + pub row_id: Option, + pub row_address: Option, + pub source_version: u64, + pub published_version: u64, +} + +/// A bounded set of per-row producing-version records. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionProvenance { + pub records: Vec, + pub truncated: bool, } impl RefreshColumnResult { @@ -1106,9 +1788,54 @@ impl RefreshColumnResult { impl_json!(RefreshColumnResult); +#[cfg(test)] +mod refresh_result_tests { + use super::{FunctionRefreshPlan, FunctionRefreshTier, RefreshColumnResult}; + + fn result(plan: Option) -> RefreshColumnResult { + RefreshColumnResult { + rows_assigned: 3, + rows_failed: 0, + rows_remaining: 0, + source_version: 7, + published_version: Some(8), + plan, + error_groups: Vec::new(), + error_groups_truncated: false, + } + } + + #[test] + fn absent_plan_stays_out_of_the_terminal_payload() { + let encoded = serde_json::to_value(result(None)).unwrap(); + assert!(encoded.get("plan").is_none()); + } + + #[test] + fn descriptor_plan_round_trips_through_the_terminal_payload() { + let plan = FunctionRefreshPlan { + default_worker_class: "medium".to_string(), + batch_size: Some(1), + tiers: vec![FunctionRefreshTier { + max_row_bytes: None, + worker_class: "large".to_string(), + worker_memory_bytes: 16 << 30, + executor_budget_bytes: 11 << 30, + batch_bytes: 1 << 20, + rows: 3, + batches: 2, + }], + }; + let encoded = serde_json::to_value(result(Some(plan.clone()))).unwrap(); + let decoded: RefreshColumnResult = serde_json::from_value(encoded).unwrap(); + assert_eq!(decoded.plan, Some(plan)); + } +} + #[cfg(test)] mod conda_environment_tests { use super::{PythonEnvironmentSpec, PythonRuntimeSpec}; + use serde_json::Value; #[test] fn conda_channels_round_trip_and_pip_stays_bare() { @@ -1170,6 +1897,28 @@ mod conda_environment_tests { super::canonical_json(&runtime).unwrap(), r#"{"environment":{"kind":"pip"},"gpu":true,"gpu_class":"a10g","kind":"python_v2","python_version":"3.12"}"# ); + let runtime: PythonRuntimeSpec = serde_json::from_str( + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":true,"gpu_class":"any","gpus_per_worker":2}"#, + ).unwrap(); + assert_eq!(runtime.gpus_per_worker(), 2); + assert_eq!(runtime.gpu_class(), Some("any")); + let encoded = super::canonical_json(&runtime).unwrap(); + assert_eq!( + serde_json::from_str::(&encoded).unwrap()["gpus_per_worker"], + 2 + ); + for count in [ + serde_json::json!(0), + serde_json::json!(-1), + serde_json::json!(true), + serde_json::json!("2"), + serde_json::json!(1.5), + serde_json::json!(4294967296_u64), + ] { + let mut value: Value = serde_json::from_str(&encoded).unwrap(); + value["gpus_per_worker"] = count; + assert!(serde_json::from_value::(value).is_err()); + } for invalid in [ r#"{"kind":"python","python_version":"3.12","environment":{"kind":"pip"},"gpu":true}"#, @@ -1207,6 +1956,30 @@ mod conda_environment_tests { mod tests { use super::*; + #[test] + fn function_version_preserves_runtime_digest() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + let legacy = FunctionVersion::from_json(VERSION).unwrap(); + assert_eq!(legacy.runtime_digest(), None); + assert_eq!(legacy.to_canonical_json().unwrap(), VERSION.trim_end()); + for digest in [Value::Null, serde_json::json!("sha256:runtime-inputs")] { + document["runtime_digest"] = digest.clone(); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime_digest(), digest.as_str()); + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + if digest.is_null() { + assert!(encoded_value.get("runtime_digest").is_none()); + } else { + assert_eq!(encoded_value["runtime_digest"], digest); + } + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + } + } + #[test] fn function_version_preserves_source_digest() { const VERSION: &str = include_str!( @@ -1237,6 +2010,252 @@ mod tests { assert_eq!(version.gpu_class(), Some("a10g")); let encoded: Value = serde_json::from_str(&version.to_canonical_json().unwrap()).unwrap(); assert_eq!(encoded["gpu_class"], "a10g"); + + document["max_concurrency"] = serde_json::json!(4); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.max_concurrency(), Some(4)); + let encoded: Value = serde_json::from_str(&version.to_canonical_json().unwrap()).unwrap(); + assert_eq!(encoded["max_concurrency"], 4); + + document["max_concurrency"] = serde_json::json!(0); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); + } + + #[test] + fn function_version_exposes_the_explicit_primary_index() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + const PRIMARY: &str = "https://primary.example/simple/"; + const EXTRA: &str = "https://extra.example/simple/"; + const DIGEST: &str = "sha256:requested-runtime"; + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": {"kind": "pip", "packages": ["example==1.0"]}, + }); + document["runtime_digest"] = serde_json::json!(DIGEST); + document["resolved_environment"] = serde_json::json!({ + "packages": [], + "provenance": {"configured_index_urls": [EXTRA]}, + }); + + let legacy = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(legacy.requested_index_url(), None); + let legacy_json = legacy.to_canonical_json().unwrap(); + for (build, index) in [ + (Value::Null, None), + (serde_json::json!({}), None), + (serde_json::json!({"extra_index_urls": [EXTRA]}), None), + (serde_json::json!({"index_url": 1}), None), + (serde_json::json!("invalid-build"), None), + ( + serde_json::json!({"index_url": PRIMARY, "extra_index_urls": [EXTRA]}), + Some(PRIMARY), + ), + ] { + document["runtime"]["environment"]["build"] = build; + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.requested_index_url(), index); + assert_eq!(version.runtime_digest(), Some(DIGEST)); + let canonical = version.to_canonical_json().unwrap(); + if let Some(index) = index { + let mut expected: Value = serde_json::from_str(&legacy_json).unwrap(); + expected["runtime"]["environment"]["build"] = + serde_json::json!({"index_url": index}); + assert_eq!(serde_json::from_str::(&canonical).unwrap(), expected); + } else { + assert_eq!(canonical, legacy_json); + } + assert_eq!(FunctionVersion::from_json(&canonical).unwrap(), version); + } + } + + #[test] + fn typed_registration_rejects_environment_build_settings() { + const REQUEST: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" + ); + let mut document: Value = serde_json::from_str(REQUEST).unwrap(); + let expected = FunctionRegistrationRequest::from_json(REQUEST).unwrap(); + for build in [Value::Null, serde_json::json!({})] { + document["runtime"]["environment"]["build"] = build; + assert_eq!( + FunctionRegistrationRequest::from_json(&document.to_string()).unwrap(), + expected + ); + } + for build in [ + serde_json::json!({"index_url": "https://primary.example/simple/"}), + serde_json::json!({"extra_index_urls": ["https://extra.example/simple/"]}), + serde_json::json!("invalid-build"), + ] { + document["runtime"]["environment"]["build"] = build; + let error = FunctionRegistrationRequest::from_json(&document.to_string()).unwrap_err(); + assert!(error.to_string().contains( + "runtime.environment.build is unsupported in typed Function registration" + )); + } + } + + #[test] + fn function_version_preserves_requested_and_resolved_environments() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + let legacy = FunctionVersion::from_json(VERSION).unwrap(); + assert!(legacy.runtime().is_none()); + assert!(legacy.resolved_environment().is_none()); + assert!(legacy.resolved_environments().is_empty()); + + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": ["vllm==0.11.0"] + } + }); + document["resolved_environment"] = serde_json::json!({ + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + }, + { + "name": "transformers", + "version": "4.57.1" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "configured_find_links": ["https://downloads.example/wheels"], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "transformers resolved to transformers==4.57.1 but is not pinned exactly; add transformers==4.57.1 to pin it." + ] + }); + + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime().unwrap().kind(), "python"); + assert!(version.resolved_environments().is_empty()); + let resolved = version.resolved_environment().unwrap(); + assert_eq!(resolved.packages[0].version, "2.9.0+cu130"); + assert_eq!( + resolved.packages[0].source.as_deref(), + Some("https://packages.example/simple") + ); + assert_eq!(resolved.packages[1].source, None); + assert_eq!( + resolved + .provenance + .as_ref() + .unwrap() + .torch_version + .as_deref(), + Some("torch==2.9.0+cu130") + ); + assert_eq!(resolved.warnings.len(), 1); + + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + assert_eq!( + encoded_value["resolved_environment"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert!( + encoded_value["resolved_environment"]["packages"][1] + .get("source") + .is_none() + ); + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + + document["resolved_environment"] = serde_json::json!({"warnings": []}); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); + } + + #[test] + fn function_version_preserves_resolved_environments_by_platform() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": ["vllm==0.11.0"] + } + }); + document["resolved_environments"] = serde_json::json!({ + "linux/amd64": { + "packages": [ + {"name": "torch", "version": "2.9.0+cu130"} + ], + "warnings": ["amd64 measurement"] + }, + "linux/arm64": { + "packages": [], + "warnings": ["arm64 measurement"] + } + }); + + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!(version.resolved_environment().is_none()); + let environments = version.resolved_environments(); + assert_eq!(environments.len(), 2); + assert_eq!( + environments["linux/amd64"].packages[0].version, + "2.9.0+cu130" + ); + assert!(environments["linux/arm64"].packages.is_empty()); + assert_eq!(environments["linux/arm64"].warnings, ["arm64 measurement"]); + + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + assert!(encoded_value.get("resolved_environment").is_none()); + assert_eq!( + encoded_value["resolved_environments"]["linux/amd64"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert_eq!( + encoded_value["resolved_environments"]["linux/arm64"]["packages"], + serde_json::json!([]) + ); + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + + document["resolved_environments"] + .as_object_mut() + .unwrap() + .remove("linux/arm64"); + let missing_platform = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!( + !missing_platform + .resolved_environments() + .contains_key("linux/arm64") + ); + + document["resolved_environments"] = serde_json::json!({}); + let empty_map = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!(empty_map.resolved_environments().is_empty()); + assert!( + !empty_map + .to_canonical_json() + .unwrap() + .contains("resolved_environments") + ); + + document["resolved_environments"] = serde_json::json!({ + "linux/amd64": {"warnings": []} + }); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); } #[test] diff --git a/rust/lancedb/src/function/retry.rs b/rust/lancedb/src/function/retry.rs new file mode 100644 index 000000000..b52d59d2b --- /dev/null +++ b/rust/lancedb/src/function/retry.rs @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Client configuration for retries inside an Enterprise Function invocation. + +use serde::{Deserialize, Serialize}; + +use crate::{Error, Result}; + +/// Retry selected user-code errors without consuming a worker retry attempt. +/// +/// A retry repeats the entire failed call, so opt in only when repeating its +/// partial work is safe. Matchers are alternatives. With a batch Function and +/// `skip`, an exhausted call skips the whole batch rather than bisecting it. +/// +/// ``` +/// use lancedb::function::FunctionRetryPolicy; +/// let policy = FunctionRetryPolicy::transient(); +/// policy.validate().unwrap(); +/// ``` +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(default, deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRetryPolicy { + /// Total calls, including the first; 1 disables retries, maximum 100. + pub max_attempts: u32, + /// Initial exponential-backoff ceiling, with full jitter; default 0.2 seconds. + pub initial_backoff_seconds: f64, + /// Maximum backoff, including Retry-After; default 30 seconds, maximum 3600. + pub max_backoff_seconds: f64, + /// Exception class names, preferably qualified; subclasses also match. + pub exception_types: Vec, + /// Regular expression matched against the exception class and message. + pub message_pattern: Option, + /// Structured provider error codes or HTTP status codes, represented as strings. + pub error_codes: Vec, + /// Match connection/timeouts, HTTP 429/503, SlowDown and ServiceUnavailable. + pub transient: bool, + /// Honor Retry-After within the configured maximum; default true. + pub honor_retry_after: bool, +} + +impl Default for FunctionRetryPolicy { + fn default() -> Self { + Self { + max_attempts: 3, + initial_backoff_seconds: 0.2, + max_backoff_seconds: 30.0, + exception_types: Vec::new(), + message_pattern: None, + error_codes: Vec::new(), + transient: false, + honor_retry_after: true, + } + } +} + +impl FunctionRetryPolicy { + /// Retry known transient errors up to three calls with bounded backoff. + pub fn transient() -> Self { + Self { + transient: true, + ..Self::default() + } + } + + /// Validate before registration or refresh submission. + pub fn validate(&self) -> Result<()> { + let invalid = |message: String| Error::InvalidInput { message }; + if !(1..=100).contains(&self.max_attempts) { + return Err(invalid(format!( + "retry_policy.max_attempts must be between 1 and 100, got {}", + self.max_attempts + ))); + } + for (name, value) in [ + ("initial_backoff_seconds", self.initial_backoff_seconds), + ("max_backoff_seconds", self.max_backoff_seconds), + ] { + if !value.is_finite() || !(0.0..=3600.0).contains(&value) { + return Err(invalid(format!( + "retry_policy.{name} must be finite and between 0 and 3600, got {value}" + ))); + } + } + if self.initial_backoff_seconds > self.max_backoff_seconds { + return Err(invalid( + "retry_policy.initial_backoff_seconds exceeds max_backoff_seconds".into(), + )); + } + if self + .exception_types + .iter() + .chain(&self.error_codes) + .any(String::is_empty) + { + return Err(invalid( + "retry_policy exception_types and error_codes must contain non-empty strings" + .into(), + )); + } + if let Some(pattern) = &self.message_pattern { + regex::Regex::new(pattern).map_err(|error| { + invalid(format!("invalid retry_policy.message_pattern: {error}")) + })?; + } + if self.max_attempts > 1 + && !self.transient + && self.message_pattern.is_none() + && self.exception_types.is_empty() + && self.error_codes.is_empty() + { + return Err(invalid( + "retry_policy requires at least one error matcher".into(), + )); + } + Ok(()) + } +} + +/// What a Function refresh does after a call fails or exhausts retries. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionErrorPolicy { + /// Fail the refresh job. + Fail, + /// Write null and record the error, subject to the server's failure limits. + Skip, +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + use serde_json::json; + + #[rstest] + #[case(json!({"max_attempts": 0, "transient": true}))] + #[case(json!({"max_attempts": 101, "transient": true}))] + #[case(json!({"max_attempts": 3}))] + #[case(json!({"initial_backoff_seconds": -1, "transient": true}))] + #[case(json!({"max_backoff_seconds": 0, "transient": true}))] + #[case(json!({"exception_types": [""]}))] + #[case(json!({"message_pattern": "["}))] + fn reject_invalid_policy(#[case] value: serde_json::Value) { + let policy: FunctionRetryPolicy = serde_json::from_value(value).unwrap(); + assert!(policy.validate().is_err()); + } + + #[test] + fn policy_defaults_and_disabled_policy() { + assert!(FunctionRetryPolicy::transient().validate().is_ok()); + let policy: FunctionRetryPolicy = + serde_json::from_value(json!({"max_attempts":1})).unwrap(); + assert!(policy.validate().is_ok()); + let mut invalid = policy; + invalid.initial_backoff_seconds = f64::NAN; + assert!(invalid.validate().is_err()); + } +} diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 87eff864d..30dcee3df 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -16,7 +16,8 @@ use crate::{DistanceType, Error, Result, job::Job, table::BaseTable}; use self::{ scalar::{ BTreeIndexBuilder, BitmapIndexBuilder, BloomFilterIndexBuilder, FmIndexBuilder, - LabelListIndexBuilder, NGramIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder, + LabelListIndexBuilder, NGramIndexBuilder, PluginIndexBuilder, RTreeIndexBuilder, + ZoneMapIndexBuilder, }, vector::{ IvfHnswFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder, @@ -74,6 +75,24 @@ pub enum Index { /// Native creation requires the `geo` feature. RTree(RTreeIndexBuilder), + /// Configure a scalar index of a type recognized by a registered database plugin. + /// + /// Select the type by name and provide optional JSON parameters with + /// [`PluginIndexBuilder`]. Prefer a dedicated variant when one is available. + /// + /// ``` + /// use lancedb::index::{Index, scalar::PluginIndexBuilder}; + /// + /// # async fn create_zonemap(table: &lancedb::Table) -> lancedb::Result<()> { + /// table + /// .create_index(&["timestamp"], Index::Plugin(PluginIndexBuilder::new("zonemap")?)) + /// .execute() + /// .await?; + /// # Ok(()) + /// # } + /// ``` + Plugin(PluginIndexBuilder), + /// Full text search index using BM25. /// /// Supports strings, lists of strings, and `lance.json` logical fields @@ -220,6 +239,7 @@ pub struct IndexBuilder { pub(crate) index: Index, pub(crate) columns: Vec, pub(crate) replace: bool, + pub(crate) exist_ok: bool, pub(crate) wait_timeout: Option, pub(crate) train: bool, pub(crate) name: Option, @@ -232,6 +252,7 @@ impl IndexBuilder { index, columns, replace: true, + exist_ok: false, train: true, wait_timeout: None, name: None, @@ -324,6 +345,21 @@ impl IndexBuilder { self } + /// Preserve an existing index with the requested name. Defaults to false. + /// This takes precedence over `replace`; a skipped creation does not rebuild. + /// + /// ```no_run + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// table.create_index(&["id"], lancedb::index::Index::Auto) + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Duration of time to wait for asynchronous indexing to complete. If not set, /// `create_index()` will not wait. /// diff --git a/rust/lancedb/src/index/scalar.rs b/rust/lancedb/src/index/scalar.rs index 2555c1439..709f9cb9b 100644 --- a/rust/lancedb/src/index/scalar.rs +++ b/rust/lancedb/src/index/scalar.rs @@ -204,6 +204,110 @@ impl RTreeIndexBuilder { } } +/// Configure a scalar index of a type recognized by a registered database plugin. +/// +/// Use this for index types without a dedicated builder. Prefer a dedicated +/// builder, such as [`ZoneMapIndexBuilder`] or [`BloomFilterIndexBuilder`], when +/// one is available. +/// +/// Index type names are case-insensitive. Surrounding whitespace is ignored. +/// Parameters are optional and, if given, must be a JSON object. They are passed +/// as given. Each plugin defines its parameters and defaults; refer to the +/// plugin's documentation for guidance. +/// +/// An unknown plugin name or invalid parameters cause index creation to fail. +/// +/// ``` +/// use lancedb::index::{Index, scalar::PluginIndexBuilder}; +/// use serde_json::json; +/// +/// # async fn create_plugin_index(table: &lancedb::Table) -> lancedb::Result<()> { +/// let bloom_filter = PluginIndexBuilder::new("bloomfilter")? +/// .params(json!({"number_of_items": 4096, "probability": 0.01}))?; +/// table +/// .create_index(&["id"], Index::Plugin(bloom_filter)) +/// .execute() +/// .await?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone, PartialEq)] +pub struct PluginIndexBuilder { + pub(crate) index_type: String, + pub(crate) params: Option>, +} + +impl PluginIndexBuilder { + /// Select the scalar index type named `index_type`. + /// + /// The name is trimmed and lower-cased. Returns + /// [`Error::InvalidInput`](crate::Error::InvalidInput) if it is empty. + pub fn new(index_type: impl Into) -> crate::Result { + let index_type = index_type.into().trim().to_lowercase(); + if index_type.is_empty() { + return Err(crate::Error::InvalidInput { + message: "a scalar index plugin name must not be empty".into(), + }); + } + Ok(Self { + index_type, + params: None, + }) + } + + /// Set the index parameters, which must be a JSON object. + /// + /// Returns [`Error::InvalidInput`](crate::Error::InvalidInput) for any + /// other JSON value, including `null`. + pub fn params(mut self, params: serde_json::Value) -> crate::Result { + match params { + serde_json::Value::Object(params) => { + self.params = Some(params); + Ok(self) + } + other => Err(crate::Error::InvalidInput { + message: format!( + "scalar index plugin params must be a JSON object, got {}", + json_kind(&other) + ), + }), + } + } + + /// Set the index parameters from a JSON string, which must hold an object. + /// + /// Returns [`Error::InvalidInput`](crate::Error::InvalidInput) if the string + /// is not valid JSON or holds anything but an object. + pub fn params_json(self, params: impl AsRef) -> crate::Result { + let params = + serde_json::from_str(params.as_ref()).map_err(|e| crate::Error::InvalidInput { + message: format!("scalar index plugin params are not valid JSON: {e}"), + })?; + self.params(params) + } + + /// The index type name, trimmed and lower-cased. + pub fn index_type(&self) -> &str { + &self.index_type + } + + /// The index parameters, if set. + pub fn parameters(&self) -> Option<&serde_json::Map> { + self.params.as_ref() + } +} + +fn json_kind(value: &serde_json::Value) -> &'static str { + match value { + serde_json::Value::Null => "null", + serde_json::Value::Bool(_) => "a boolean", + serde_json::Value::Number(_) => "a number", + serde_json::Value::String(_) => "a string", + serde_json::Value::Array(_) => "an array", + serde_json::Value::Object(_) => "an object", + } +} + pub use lance_index::scalar::FullTextSearchQuery; pub use lance_index::scalar::InvertedIndexParams as FtsIndexBuilder; pub use lance_index::scalar::InvertedIndexParams; @@ -267,4 +371,66 @@ mod tests { } assert!(RTreeIndexBuilder::default().page_size(2).is_ok()); } + + #[test] + fn plugin_index_builder_normalizes_the_name() { + for name in ["zonemap", "ZoneMap", "ZONEMAP", " zonemap\t"] { + assert_eq!( + PluginIndexBuilder::new(name).unwrap().index_type(), + "zonemap" + ); + } + for name in ["", " ", "\n"] { + assert!(matches!( + PluginIndexBuilder::new(name), + Err(crate::Error::InvalidInput { .. }) + )); + } + } + + #[test] + fn plugin_index_builder_accepts_only_object_params() { + let builder = PluginIndexBuilder::new("bloomfilter").unwrap(); + assert_eq!(builder.parameters(), None); + + let expected = serde_json::json!({"number_of_items": 4096}); + let from_value = builder.clone().params(expected.clone()).unwrap(); + let from_json = builder + .clone() + .params_json(r#"{"number_of_items": 4096}"#) + .unwrap(); + assert_eq!(from_value, from_json); + assert_eq!(from_value.parameters(), Some(expected.as_object().unwrap())); + assert_eq!( + builder + .clone() + .params(serde_json::json!({})) + .unwrap() + .parameters(), + Some(&serde_json::Map::new()) + ); + + for (params, kind) in [ + (serde_json::Value::Null, "null"), + (serde_json::json!(true), "a boolean"), + (serde_json::json!(1), "a number"), + (serde_json::json!("x"), "a string"), + (serde_json::json!([1]), "an array"), + ] { + let json = params.to_string(); + for result in [ + builder.clone().params(params), + builder.clone().params_json(json), + ] { + let Err(crate::Error::InvalidInput { message }) = result else { + panic!("non-object params must be rejected"); + }; + assert!(message.ends_with(kind), "{message}"); + } + } + let Err(crate::Error::InvalidInput { message }) = builder.params_json("{not json") else { + panic!("malformed JSON must be rejected"); + }; + assert!(message.contains("not valid JSON"), "{message}"); + } } diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 823834798..5485c8905 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -3,9 +3,17 @@ //! Handles to operations a server may run asynchronously. +mod profile; + +pub use profile::{ + FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, + FunctionProfileWaitOptions, +}; + use std::future::Future; use std::pin::Pin; use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; +use std::time::Duration; use arrow_array::RecordBatch; use async_trait::async_trait; @@ -13,17 +21,66 @@ use serde::{Serialize, de::DeserializeOwned}; use serde_json::Value; use tokio::sync::watch; use tokio::task::{AbortHandle, JoinHandle}; +use tokio::time::{Instant, sleep_until, timeout_at}; use uuid::Uuid; use crate::database::JobDescription; use crate::docs::DocLink; use crate::error::{Error, JobFailure, Result}; +mod state; +pub use state::JobState; + +/// Arrow schema metadata carrying the next retained event page. +pub const JOB_EVENT_PAGE_TOKEN_METADATA_KEY: &str = "lancedb.job_coordinator.page_token"; + /// Observer called with each description fetched by a job's existing wait /// poller. Keeping this callback on the poller avoids a second lifecycle or /// retry loop just to render progress. pub type JobProgressCallback = Arc>; +/// Client-side controls for waiting on a job. A timeout stops this wait without +/// cancelling the operation; keep the handle to wait again. +#[derive(Clone, Default)] +#[non_exhaustive] +pub struct JobWaitOptions { + /// Maximum time to wait, including HTTP requests and polling backoff. + /// `None` waits indefinitely. Zero only permits an immediately ready result. + pub timeout: Option, + progress: Option, +} + +impl std::fmt::Debug for JobWaitOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("JobWaitOptions") + .field("timeout", &self.timeout) + .field("progress", &self.progress.is_some()) + .finish() + } +} + +impl JobWaitOptions { + /// Wait indefinitely without a progress callback. + pub fn new() -> Self { + Self::default() + } + + /// Bound this wait without cancelling the underlying job. + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = Some(timeout); + self + } + + /// Observe the backend's existing poller. The callback should return promptly. + pub fn progress(mut self, progress: F) -> Self + where + F: FnMut(&JobDescription) + Send + 'static, + { + self.progress = Some(Arc::new(Mutex::new(progress))); + self + } +} + /// Which of a job's events [`Job::events`] returns. /// /// The handle already knows which job to ask about, so this narrows the @@ -39,6 +96,8 @@ pub struct JobEventsRequest { /// `emitted_from`, `emitted_by`, and `claim_entity`. For example /// `state = 'claim_complete'` selects only per-claim completions. pub filter: Option, + /// Opaque continuation from the preceding page's Arrow schema metadata. + pub page_token: Option, } impl JobEventsRequest { @@ -51,6 +110,22 @@ impl JobEventsRequest { self.filter = Some(filter.into()); self } + + /// Continue a previous page without deriving a cursor from its row count. + pub fn page_token(mut self, token: impl Into) -> Self { + self.page_token = Some(token.into()); + self + } +} + +/// The continuation returned with one event page. Absence means the page is complete. +pub fn job_event_page_token(batches: &[RecordBatch]) -> Option<&str> { + batches + .first()? + .schema_ref() + .metadata() + .get(JOB_EVENT_PAGE_TOKEN_METADATA_KEY) + .map(String::as_str) } fn job_detail_not_supported(what: &str) -> Result { @@ -80,11 +155,44 @@ pub(crate) trait JobHandle: Send + Sync { self.wait().await } async fn cancel(&self) -> Result<()>; + async fn retry(&self) -> Result> { + job_detail_not_supported("retrying a job") + } /// The job's full server-side record. Backends that run the operation in /// this process have none and keep the default. async fn describe(&self) -> Result { job_detail_not_supported("describing a job") } + /// Chrome Trace Event JSON for a server-side Function job. + async fn timeline(&self) -> Result { + job_detail_not_supported("job timeline export") + } + + async fn stack(&self, _worker_id: &str) -> Result { + job_detail_not_supported("worker stack capture") + } + + async fn capture_profile( + &self, + _worker_id: &str, + _options: FunctionProfileOptions, + ) -> Result { + job_detail_not_supported("Function worker profiling") + } + + async fn profile_status(&self, _profile_id: &str) -> Result { + job_detail_not_supported("Function worker profiling") + } + + async fn profile_artifact(&self, _profile_id: &str) -> Result { + job_detail_not_supported("Function worker profiling") + } + + /// A printable report of recorded Function job metrics. + async fn stats(&self) -> Result> { + job_detail_not_supported("job statistics") + } + /// The job's recorded lifecycle events. async fn events(&self, _request: JobEventsRequest) -> Result> { job_detail_not_supported("job event history") @@ -182,7 +290,9 @@ enum JobInner { #[derive(Default)] struct JobCache { state: Option, + lifecycle_state: Option, description: Option, + local_operation_id: Option, } /// A handle to an operation that may still be running. @@ -245,7 +355,9 @@ impl Job<()> { inner: JobInner::Completed(()), cache: RwLock::new(JobCache { state: Some("finished".to_string()), + lifecycle_state: Some(JobState::Succeeded), description: None, + local_operation_id: Some(Uuid::new_v4().to_string()), }), } } @@ -268,10 +380,52 @@ impl Job<()> { { let mut cache = job.cache_write(); cache.state = Some(description.state.clone()); + cache.lifecycle_state = Some( + description + .lifecycle_state + .clone() + .unwrap_or_else(|| JobState::from(description.state.as_str())), + ); cache.description = Some(description); } job } + + /// Decode this job's terminal payload as `T` when waiting. + /// + /// Use this after [`crate::Connection::open_job`] when the job's result + /// type is known. The job identity and cached description are preserved. + /// Missing or incompatible payloads are reported by [`Job::wait`]. + /// A job that completed before its handle was created has only a unit + /// result; converting it fails immediately if `T` cannot decode JSON null. + /// + /// ```no_run + /// # async fn reopen( + /// # db: &lancedb::Connection, id: &str, + /// # ) -> lancedb::Result { + /// let job = db.open_job(id).await? + /// .into_typed::()?; + /// job.wait().await + /// # } + /// ``` + pub fn into_typed(self) -> Result> + where + T: Clone + DeserializeOwned + Send + Sync + 'static, + { + let inner = match self.inner { + JobInner::Handle { handle, .. } => JobInner::Handle { + handle, + decode: Arc::new(TerminalResult::decode::), + }, + JobInner::Completed(()) => { + JobInner::Completed(TerminalResult::local(Value::Null).decode::()?) + } + }; + Ok(Job { + inner, + cache: self.cache, + }) + } } impl Job @@ -296,7 +450,9 @@ where { /// A typed job running as a task in this process. pub(crate) fn spawned(task: JoinHandle>) -> Self { - Self::new_typed(Box::new(SpawnedJob::new(task))) + let job = Self::new_typed(Box::new(SpawnedJob::new(task))); + job.cache_write().local_operation_id = Some(Uuid::new_v4().to_string()); + job } pub(crate) fn from_query_task( @@ -309,11 +465,13 @@ where Fut: Future> + Send + 'static, { let cancellation: Cancellation = Arc::new(move || Box::pin(cancel())); - Self::new_typed(Box::new(SpawnedJob::new_with_cancellation( + let job = Self::new_typed(Box::new(SpawnedJob::new_with_cancellation( query_id, task, cancellation, - ))) + ))); + job.cache_write().local_operation_id = Some(query_id.to_string()); + job } } @@ -358,24 +516,41 @@ where }; match handle.describe().await { Ok(description) => { - let state = description.state.clone(); let mut cache = self.cache_write(); - cache.state = Some(state.clone()); + cache.state = Some(description.state.clone()); + cache.lifecycle_state = Some( + description + .lifecycle_state + .clone() + .unwrap_or_else(|| JobState::from(description.state.as_str())), + ); + let status = if cache.lifecycle_state == Some(JobState::InProgress) + && description.job_type == "function_refresh" + && description.paused_at_millis.is_none() + && description.phase.as_deref() == Some("waiting_for_capacity") + { + "waiting_for_capacity".to_owned() + } else { + description.state.clone() + }; cache.description = Some(description); - Ok(state) + Ok(status) } // An in-process job knows its own state and nothing more. Err(Error::NotSupported { .. }) => { let state = handle.status().await?; - self.cache_write().state = Some(state.clone()); + let mut cache = self.cache_write(); + cache.state = Some(state.clone()); + cache.lifecycle_state = Some(JobState::from(state.as_str())); Ok(state) } Err(err) => Err(err), } } - /// The operation's current lifecycle state: "running", "finished", - /// "failed", or "cancelled". + /// The current status, usually "running", "finished", "failed", or "cancelled". + /// A running Function refresh reports "waiting_for_capacity" while it + /// waits for execution workers. [`Job::wait`] continues polling during this wait. /// /// A point snapshot; unlike [`Job::wait`] it does not block, raise on a /// terminal failure state, or retry. States a newer server reports that @@ -400,6 +575,73 @@ where self.cache_read().state.clone() } + /// Detailed state last observed, preserving unknown future server values. + /// Local operations use the same typed states; legacy `state()` is unchanged. + pub fn lifecycle_state(&self) -> Option { + let cache = self.cache_read(); + cache + .lifecycle_state + .clone() + .or_else(|| cache.state.as_deref().map(JobState::from)) + } + + /// Refresh the state and return its forward-compatible typed form. + pub async fn status_typed(&self) -> Result { + self.refresh_state().await?; + Ok(self.lifecycle_state().expect("refresh records a state")) + } + + /// Identity of the selected attempt last observed by this handle. + /// For operation handles, [`Self::refresh`] or [`Self::status`] can select a + /// different attempt while [`Self::id`] stays unchanged. Save the returned + /// ID after refreshing and use that value throughout paged diagnostics. + /// Local identities cannot be passed to `Connection::open_job` and last + /// for the lifetime of this handle. + pub fn job_id(&self) -> Option { + self.with_description(|description| description.attempt_job_id.clone()) + .flatten() + .or_else(|| self.id().map(str::to_string)) + .or_else(|| self.cache_read().local_operation_id.clone()) + } + + /// Root of this attempt's explicit retry lineage. Older servers may omit it. + pub fn operation_id(&self) -> Option { + let cache = self.cache_read(); + cache + .description + .as_ref() + .and_then(|description| description.operation_id.clone()) + .or_else(|| cache.local_operation_id.clone()) + } + + /// One-based retry attempt. Worker replacement does not increment it. + pub fn attempt(&self) -> Option { + let cache = self.cache_read(); + cache + .description + .as_ref() + .and_then(|description| description.attempt) + .or_else(|| cache.local_operation_id.as_ref().map(|_| 1)) + } + + /// Immediate predecessor attempt, when supplied by the backend. + pub fn retry_of(&self) -> Option { + self.with_description(|description| description.retry_of.clone()) + .flatten() + } + + /// Source snapshot pinned for this attempt, when supplied by the backend. + pub fn source_table_version(&self) -> Option { + self.with_description(|description| description.source_table_version) + .flatten() + } + + /// Most recent execution's fencing token, when supplied by the backend. + pub fn execution_epoch(&self) -> Option { + self.with_description(|description| description.execution_epoch) + .flatten() + } + /// The whole server-side record this handle last observed. The accessors /// below read individual fields out of it. `None` for an in-process job, /// which has no such record. @@ -468,6 +710,234 @@ where } } + /// Collect retained event pages, following the backend's opaque cursors. + /// `limit` is the size of each page; it is not a total history limit. + pub async fn history(&self, mut request: JobEventsRequest) -> Result> { + let mut batches = Vec::new(); + loop { + let page = self.events(request.clone()).await?; + let next = job_event_page_token(&page).map(str::to_string); + let done = next.is_none(); + if next.is_some() && next == request.page_token { + return Err(Error::Runtime { + message: "job history repeated its page token".to_string(), + }); + } + batches.extend(page); + if done { + for batch in &mut batches { + batch + .schema_metadata_mut() + .remove(JOB_EVENT_PAGE_TOKEN_METADATA_KEY); + } + return Ok(batches); + } + request.page_token = next; + } + } + + /// Fetch a recorded Function job timeline as Chrome Trace Event JSON. + /// + /// The snapshot opens in Perfetto or Chrome tracing. It contains retained + /// split and positioned phase spans; batch statistics remain arguments, + /// because individual batch timestamps are not recorded. Running jobs return + /// a partial recording without waiting for completion. Requires server support; + /// in-process operations and SQL query handles do not support this operation. + /// + /// ```no_run + /// # async fn export(job: &lancedb::job::Job) -> Result<(), Box> { + /// let trace = job.timeline().await?; + /// std::fs::write("job.trace.json", trace.to_string())?; + /// # Ok(()) + /// # } + /// ``` + pub async fn timeline(&self) -> Result { + match &self.inner { + JobInner::Handle { handle, .. } => handle.timeline().await, + JobInner::Completed(_) => job_detail_not_supported("job timeline export"), + } + } + + /// Capture Python thread stacks from a running Function worker. + /// + /// Requires a server supporting stack inspection and system operate privilege. + /// The JSON response reports capture availability per session, timestamps and + /// truncation. Stacks exclude source text, locals and native frames. A server + /// may reuse a recent capture to bound sampling overhead. Unsupported local + /// operations return [`crate::Error::NotSupported`]. + /// + /// ```no_run + /// # async fn inspect(job: &lancedb::job::Job) -> Result<(), Box> { + /// let evidence = job.stack("worker-id").await?; + /// println!("{evidence}"); + /// # Ok(()) + /// # } + /// ``` + pub async fn stack(&self, worker_id: impl AsRef) -> Result { + let worker_id = worker_id.as_ref(); + if worker_id.is_empty() || worker_id.len() > 256 { + return Err(Error::InvalidInput { + message: "worker_id must contain 1 to 256 bytes".into(), + }); + } + match &self.inner { + JobInner::Handle { handle, .. } => handle.stack(worker_id).await, + JobInner::Completed(_) => job_detail_not_supported("worker stack capture"), + } + } + + /// Request an on-demand profile from a running Enterprise Function worker. + /// + /// Returns the accepted capture identity without waiting for recording to + /// finish. The server pins the worker, Python session and execution epoch. + /// Requires System Operate permission and a supporting Enterprise server. + /// Only one capture per job can be active. GPU traces require initialized + /// PyTorch CUDA/CUPTI; CPU sampling requires readable per-thread procfs. + /// Captures add workload-dependent overhead. + /// + /// ```no_run + /// # async fn capture(job: &lancedb::job::Job) -> Result<(), Box> { + /// use std::time::Duration; + /// use lancedb::job::{FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions}; + /// let profile = job.capture_profile("worker-id", + /// FunctionProfileOptions::new(FunctionProfileKind::Gpu) + /// .duration(Duration::from_secs(2))).await?; + /// job.wait_for_profile(&profile.profile_id, FunctionProfileWaitOptions::new()).await?; + /// let artifact = job.profile_artifact(&profile.profile_id).await?; + /// std::fs::write("gpu.trace.json", serde_json::to_vec(&artifact)?)?; + /// # Ok(()) + /// # } + /// ``` + pub async fn capture_profile( + &self, + worker_id: impl AsRef, + options: FunctionProfileOptions, + ) -> Result { + let worker_id = worker_id.as_ref(); + options.validate(worker_id)?; + match &self.inner { + JobInner::Handle { handle, .. } => handle.capture_profile(worker_id, options).await, + JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"), + } + } + + /// Fetch the capture's current identity and status without waiting. + /// + /// Capture failures are returned as [`FunctionProfileStatus::Failed`] with + /// the server's reason. This does not change the parent job's cached state. + /// Retained captures can be looked up after the refresh job completes. + pub async fn profile_status(&self, profile_id: impl AsRef) -> Result { + let profile_id = profile_id.as_ref(); + profile::validate_profile_id(profile_id)?; + match &self.inner { + JobInner::Handle { handle, .. } => handle.profile_status(profile_id).await, + JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"), + } + } + + /// Wait for a capture to finish, independently of the Function refresh job. + /// + /// Returns [`Error::Timeout`] when the client deadline elapses and + /// [`Error::Runtime`] when capture fails. Neither cancels the capture or + /// refresh job. Keep the profile ID to wait again or retrieve it later. + pub async fn wait_for_profile( + &self, + profile_id: impl AsRef, + options: FunctionProfileWaitOptions, + ) -> Result { + let profile_id = profile_id.as_ref(); + profile::validate_profile_id(profile_id)?; + if options.poll_interval.is_zero() { + return Err(Error::InvalidInput { + message: "profile poll interval must be greater than zero".into(), + }); + } + let deadline = + Instant::now() + .checked_add(options.timeout) + .ok_or_else(|| Error::InvalidInput { + message: "profile wait timeout is too large".into(), + })?; + let wait = async { + let mut previous: Option = None; + loop { + let profile = self.profile_status(profile_id).await?; + if previous + .as_ref() + .is_some_and(|old| !old.same_capture(&profile)) + { + return Err(Error::Runtime { + message: "profile response changed the capture's execution identity".into(), + }); + } + match profile.status { + FunctionProfileStatus::Complete => return Ok(profile), + FunctionProfileStatus::Failed => { + return Err(Error::Runtime { + message: format!( + "Function worker profile {} failed: {}", + profile.profile_id, + profile.error.as_deref().unwrap_or("no reason reported") + ), + }); + } + FunctionProfileStatus::Pending | FunctionProfileStatus::Capturing => {} + } + previous = Some(profile); + let next_poll = Instant::now() + .checked_add(options.poll_interval) + .unwrap_or(deadline) + .min(deadline); + sleep_until(next_poll).await; + } + }; + timeout_at(deadline, wait) + .await + .map_err(|_| Error::Timeout { + message: format!( + "waiting for Function worker profile {profile_id}; capture and refresh job continue on the server" + ), + })? + } + + /// Retrieve the actual profile JSON, including a retained capture after refresh. + /// + /// CPU artifacts use speedscope, Python memory artifacts use tracemalloc, + /// and GPU artifacts use Chrome Trace Event JSON. GPU truncation flags are + /// preserved. Artifacts expire after at most one hour and eight captures + /// per job, or earlier when job scratch is reclaimed or archived. + pub async fn profile_artifact(&self, profile_id: impl AsRef) -> Result { + let profile_id = profile_id.as_ref(); + profile::validate_profile_id(profile_id)?; + match &self.inner { + JobInner::Handle { handle, .. } => handle.profile_artifact(profile_id).await, + JobInner::Completed(_) => job_detail_not_supported("Function worker profiling"), + } + } + + /// Fetch a printable run report for a server-side Function job. + /// + /// The server report includes recorded phase timings, finishing-supervisor + /// slot occupancy, all-attempt split execution and batch latency, and + /// accepted-row throughput. Returns `None` for running jobs or when no recorded + /// profile is available, without waiting for completion. Requires server + /// support; local operations and SQL query handles do not support reports. + /// + /// ```no_run + /// # async fn report(job: &lancedb::job::Job) -> Result<(), Box> { + /// if let Some(report) = job.stats().await? { + /// println!("{report}"); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn stats(&self) -> Result> { + match &self.inner { + JobInner::Handle { handle, .. } => handle.stats().await, + JobInner::Completed(_) => job_detail_not_supported("job statistics"), + } + } + /// Waits until the operation reaches a terminal state. /// /// Returns the endpoint's typed result. Unit-result jobs return `()`. @@ -475,7 +945,7 @@ where /// Returns [`crate::Error::JobFailed`] if the operation failed and /// [`crate::Error::JobCancelled`] if it was cancelled. pub async fn wait(&self) -> Result { - self.wait_with_progress_opt(None).await + self.wait_with_options(JobWaitOptions::default()).await } /// Wait for the operation while observing progress from the backend's @@ -486,18 +956,90 @@ where where F: FnMut(&JobDescription) + Send + 'static, { - self.wait_with_progress_opt(Some(Arc::new(Mutex::new(progress)))) + self.wait_with_options(JobWaitOptions::new().progress(progress)) .await } + /// Wait with a client-side deadline and an optional progress callback. + /// + /// Returns [`Error::Timeout`] when the deadline expires, including while a + /// status request or polling backoff is pending. This drops the wait future; + /// it does not cancel the operation or mark it failed. The same handle can + /// wait again. Registry jobs can also be reopened by ID; query IDs remain + /// connection-scoped and cannot be reopened as registry jobs. + /// + /// ```no_run + /// # async fn example(job: &lancedb::Job) -> lancedb::Result<()> { + /// use std::time::Duration; + /// use lancedb::job::JobWaitOptions; + /// job.wait_with_options(JobWaitOptions::new() + /// .timeout(Duration::from_secs(60)) + /// .progress(|description| println!("{}", description.state))) + /// .await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn wait_with_options(&self, options: JobWaitOptions) -> Result { + let Some(timeout) = options.timeout else { + return self.wait_with_progress_opt(options.progress).await; + }; + let deadline = tokio::time::Instant::now() + .checked_add(timeout) + .ok_or_else(|| Error::InvalidInput { + message: "job wait timeout is too large".to_string(), + })?; + tokio::time::timeout_at(deadline, self.wait_with_progress_opt(options.progress)) + .await + .map_err(|_| { + let operation = self + .id() + .map(|id| format!("job {id:?}")) + .unwrap_or_else(|| "operation".to_string()); + let resume = if self.id().is_some() && self.job_type().as_deref() != Some("query") { + "continue waiting on this handle or reattach with Connection::open_job" + } else { + "keep this handle to continue waiting" + }; + Error::Timeout { + message: format!( + "{operation} still running after {timeout:?}; the operation continues; {resume}" + ), + } + })? + } + async fn wait_with_progress_opt(&self, progress: Option) -> Result { match &self.inner { JobInner::Handle { handle, decode } => { - let settled = handle.wait_with_progress(progress).await; + let observed_state = Arc::new(Mutex::new(None)); + let observed = observed_state.clone(); + let observer: JobProgressCallback = + Arc::new(Mutex::new(move |description: &JobDescription| { + *observed.lock().unwrap() = Some( + description + .lifecycle_state + .clone() + .unwrap_or_else(|| JobState::from(description.state.as_str())), + ); + if let Some(progress) = &progress + && let Ok(mut callback) = progress.lock() + { + callback(description); + } + })); + let settled = handle.wait_with_progress(Some(observer)).await; // Waiting already established a terminal state; record it so // the detail accessors do not need another round trip for it. if let Some(state) = terminal_state(&settled) { - self.cache_write().state = Some(state.to_string()); + let mut cache = self.cache_write(); + cache.state = Some(state.to_string()); + cache.lifecycle_state = Some( + observed_state + .lock() + .unwrap() + .take() + .unwrap_or_else(|| JobState::from(state)), + ); } (decode)(settled?) } @@ -518,6 +1060,23 @@ where } } + /// Select a successor for this exact unsuccessful attempt. The backend + /// copies pinned inputs and coalesces repeated requests; it does not resolve + /// a newer Function alias. In-process operations cannot be retried because + /// they do not retain a replayable operation specification. + pub async fn retry(&self) -> Result { + match &self.inner { + JobInner::Handle { handle, decode } => Ok(Self { + inner: JobInner::Handle { + handle: handle.retry().await?, + decode: decode.clone(), + }, + cache: RwLock::default(), + }), + JobInner::Completed(_) => job_detail_not_supported("retrying a job"), + } + } + /// Maps a successful terminal result without changing the job lifecycle. /// The mapping may run once for each call to [`Job::wait`], so it should /// be deterministic and free of externally visible side effects. @@ -583,7 +1142,7 @@ impl Outcome { Self::Failed(source) => { let (job_id, failure) = match source.as_ref() { Error::JobFailed { job_id, failure } => (job_id.clone(), failure.clone()), - _ => (None, JobFailure::from_source(source)), + _ => (None, Box::new(JobFailure::from_source(source))), }; Err(Error::JobFailed { job_id, failure }) } @@ -715,6 +1274,186 @@ mod tests { use super::*; + struct PendingProfileStatus; + + #[async_trait] + impl JobHandle for PendingProfileStatus { + async fn status(&self) -> Result { + panic!("profile wait fetched parent status") + } + async fn wait(&self) -> Result { + panic!("profile wait waited for parent completion") + } + async fn cancel(&self) -> Result<()> { + panic!("profile wait cancelled parent job") + } + async fn profile_status(&self, _profile_id: &str) -> Result { + pending().await + } + } + + #[tokio::test(start_paused = true)] + async fn profile_timeout_bounds_pending_requests_and_rejects_deadline_overflow() { + let job = Job::new(Box::new(PendingProfileStatus)); + let started = Instant::now(); + assert!(matches!( + job.wait_for_profile( + "profile-1", + FunctionProfileWaitOptions::new().timeout(Duration::from_millis(50)) + ) + .await, + Err(Error::Timeout { .. }) + )); + assert_eq!(started.elapsed(), Duration::from_millis(50)); + assert_eq!(job.state(), None); + assert!(matches!( + job.wait_for_profile( + "profile-1", + FunctionProfileWaitOptions::new().timeout(Duration::MAX) + ) + .await, + Err(Error::InvalidInput { .. }) + )); + } + + #[tokio::test(start_paused = true)] + async fn wait_timeout_preserves_local_task_and_typed_result() { + let job = Job::spawned(tokio::spawn(async { + tokio::time::sleep(Duration::from_secs(1)).await; + Ok(41_u64) + })) + .map(|value| value + 1); + let error = job + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(10))) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { .. })); + assert!(error.to_string().contains("keep this handle")); + assert!(!error.to_string().contains("Connection::open_job")); + assert_eq!(job.state(), None); + assert_eq!(job.status().await.unwrap(), "running"); + assert_eq!( + job.wait_with_options(JobWaitOptions::new()).await.unwrap(), + 42 + ); + } + + #[tokio::test(start_paused = true)] + async fn wait_timeout_keeps_query_handle_without_requesting_cancellation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let cancellations = Arc::new(AtomicUsize::new(0)); + let observed = cancellations.clone(); + let id = Uuid::new_v4(); + let job = Job::from_query_task( + id, + tokio::spawn(async { + tokio::time::sleep(Duration::from_secs(1)).await; + Ok(42_u64) + }), + move || { + observed.fetch_add(1, Ordering::SeqCst); + async { Ok(()) } + }, + ); + let error = job + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(10))) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { .. })); + assert!(error.to_string().contains(&id.to_string())); + assert!(!error.to_string().contains("Connection::open_job")); + assert_eq!(cancellations.load(Ordering::SeqCst), 0); + assert_eq!(job.wait().await.unwrap(), 42); + } + + #[tokio::test] + async fn wait_options_handle_zero_and_unrepresentable_deadlines() { + let job = Job::new_done(); + job.wait_with_options(JobWaitOptions::new().timeout(Duration::ZERO)) + .await + .unwrap(); + assert!(matches!( + job.wait_with_options(JobWaitOptions::new().timeout(Duration::MAX)) + .await, + Err(Error::InvalidInput { .. }) + )); + } + + #[tokio::test] + async fn wait_options_preserve_operation_errors() { + let failed = Job::::spawned(tokio::spawn(async { + Err(Error::Runtime { + message: "original failure".into(), + }) + })); + let error = failed + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await + .unwrap_err(); + assert!(matches!(error, Error::JobFailed { .. })); + assert!(error.to_string().contains("original failure")); + let cancelled = Job::::spawned(tokio::spawn(pending())); + cancelled.cancel().await.unwrap(); + assert!(matches!( + cancelled + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await, + Err(Error::JobCancelled { .. }) + )); + } + + struct HistoryPages(Arc>>>); + + #[async_trait] + impl JobHandle for HistoryPages { + async fn status(&self) -> Result { + Ok("running".to_string()) + } + async fn wait(&self) -> Result { + pending().await + } + async fn cancel(&self) -> Result<()> { + Ok(()) + } + async fn events(&self, request: JobEventsRequest) -> Result> { + self.0.lock().unwrap().push(request.page_token.clone()); + let metadata = if request.page_token.is_none() { + [( + JOB_EVENT_PAGE_TOKEN_METADATA_KEY.to_string(), + "next".to_string(), + )] + .into_iter() + .collect() + } else { + Default::default() + }; + Ok(vec![RecordBatch::new_empty(Arc::new( + arrow_schema::Schema::new_with_metadata( + Vec::::new(), + metadata, + ), + ))]) + } + } + + #[tokio::test] + async fn collected_history_follows_empty_pages_and_clears_continuations() { + let requests = Arc::new(Mutex::new(Vec::new())); + let job = Job::new(Box::new(HistoryPages(requests.clone()))); + let history = job.history(JobEventsRequest::default()).await.unwrap(); + assert_eq!(history.len(), 2); + assert_eq!( + *requests.lock().unwrap(), + vec![None, Some("next".to_string())] + ); + assert!(history.iter().all(|batch| { + !batch + .schema_ref() + .metadata() + .contains_key(JOB_EVENT_PAGE_TOKEN_METADATA_KEY) + })); + } + #[test] fn local_typed_result_decode_errors_are_runtime_errors() { assert!(matches!( @@ -723,6 +1462,21 @@ mod tests { )); } + #[tokio::test] + async fn completed_unit_job_can_be_retyped_as_unit() { + let job = Job::new_done().into_typed::<()>().unwrap(); + job.wait().await.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + } + + #[test] + fn completed_unit_job_rejects_an_incompatible_result_type() { + assert!(matches!( + Job::new_done().into_typed::(), + Err(Error::Runtime { .. }) + )); + } + #[tokio::test] async fn mapped_spawned_job_reuses_outcome() { let job = Job::spawned(tokio::spawn(async { Ok(41_u64) })).map(|value| value + 1); diff --git a/rust/lancedb/src/job/profile.rs b/rust/lancedb/src/job/profile.rs new file mode 100644 index 000000000..05cdd9d08 --- /dev/null +++ b/rust/lancedb/src/job/profile.rs @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! On-demand profiling of a Function worker's Python execution session. + +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; + +pub(super) fn validate_profile_id(profile_id: &str) -> Result<()> { + if profile_id.is_empty() || profile_id.len() > 256 { + return Err(Error::InvalidInput { + message: "profile_id must contain between 1 and 256 bytes".into(), + }); + } + Ok(()) +} + +/// What to record in one Function worker process. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum FunctionProfileKind { + /// Python stack samples weighted by thread CPU time, exported as speedscope JSON. + Cpu, + /// PyTorch CUDA kernels, transfers and available CUDA host API activities. + Gpu, + /// Python allocations made during the capture and retained at its end. + Memory, +} + +impl FunctionProfileKind { + fn maximum_duration(self) -> Duration { + Duration::from_secs(if self == Self::Gpu { 5 } else { 30 }) + } +} + +/// Server-reported state of a profile capture, independent of its parent job. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum FunctionProfileStatus { + /// Waiting for the Function supervisor to dispatch the capture. + Pending, + /// Recording the selected execution session. + Capturing, + /// The artifact can be retrieved until expiry or scratch reclamation. + Complete, + /// Capture failed; inspect [`FunctionProfile::error`] for the server's reason. + Failed, +} + +/// A snapshot of a capture's identity, status and retention information. +/// +/// It describes a diagnostic capture on an existing Function refresh job, not +/// another job. Use its profile ID with [`super::Job::profile_status`] or +/// [`super::Job::profile_artifact`], including after the refresh finishes. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct FunctionProfile { + /// Retain this ID to retrieve the capture later. + pub profile_id: String, + /// The parent Function refresh job. + pub job_id: String, + /// The selected Function worker. + pub worker_id: String, + /// Execution epoch pinned by the server when accepting the capture. + pub execution_epoch: i64, + /// Python session slot; zero is the first session. + pub session_slot: usize, + /// The kind of evidence collected. + pub kind: FunctionProfileKind, + /// Requested recording window, excluding dispatch delay. + pub duration_seconds: f64, + /// Current capture state. + pub status: FunctionProfileStatus, + /// Acceptance time, in milliseconds since the Unix epoch. + pub requested_at_millis: i64, + /// Server deadline for an unfinished capture, in epoch milliseconds. + pub deadline_at_millis: i64, + /// Retention bound in epoch milliseconds; scratch reclamation may remove it sooner. + pub expires_at_millis: i64, + /// Completion time, when reported. + pub completed_at_millis: Option, + /// Server-reported failure reason, including unsupported-session errors. + pub error: Option, + /// Server artifact identity, when the capture completes. + pub artifact_id: Option, +} + +impl FunctionProfile { + pub(crate) fn same_capture(&self, other: &Self) -> bool { + self.profile_id == other.profile_id + && self.job_id == other.job_id + && self.worker_id == other.worker_id + && self.execution_epoch == other.execution_epoch + && self.session_slot == other.session_slot + && self.kind == other.kind + && self.duration_seconds == other.duration_seconds + } + + pub(crate) fn valid_for(&self, job_id: &str, profile_id: Option<&str>) -> bool { + self.job_id == job_id + && !self.profile_id.is_empty() + && self.profile_id.len() <= 256 + && profile_id.is_none_or(|id| id == self.profile_id) + && !self.worker_id.is_empty() + && self.worker_id.len() <= 256 + && self.duration_seconds.is_finite() + && (1.0..=self.kind.maximum_duration().as_secs_f64()).contains(&self.duration_seconds) + && (self.status != FunctionProfileStatus::Complete + || self.artifact_id.as_ref().is_some_and(|id| !id.is_empty())) + } +} + +/// Options for [`super::Job::capture_profile`]. +/// +/// CPU and memory captures allow 1–30 seconds; GPU captures allow 1–5. +/// Omitting the duration selects 10 seconds for CPU/memory and 5 for GPU. +#[derive(Debug, Clone)] +pub struct FunctionProfileOptions { + pub(crate) kind: FunctionProfileKind, + pub(crate) duration: Option, + pub(crate) session_slot: usize, +} + +impl Default for FunctionProfileOptions { + fn default() -> Self { + Self::new(FunctionProfileKind::Cpu) + } +} + +impl FunctionProfileOptions { + /// Select the kind of capture, using its default duration and session zero. + pub fn new(kind: FunctionProfileKind) -> Self { + Self { + kind, + duration: None, + session_slot: 0, + } + } + + /// Set the recording window. Dispatch time is additional. + pub fn duration(mut self, duration: Duration) -> Self { + self.duration = Some(duration); + self + } + + /// Select the Python session within the worker. + pub fn session_slot(mut self, slot: usize) -> Self { + self.session_slot = slot; + self + } + + pub(crate) fn duration_seconds(&self) -> f64 { + self.duration + .unwrap_or_else(|| { + Duration::from_secs(if self.kind == FunctionProfileKind::Gpu { + 5 + } else { + 10 + }) + }) + .as_secs_f64() + } + + pub(crate) fn validate(&self, worker_id: &str) -> Result<()> { + if worker_id.is_empty() || worker_id.len() > 256 { + return Err(Error::InvalidInput { + message: "worker_id must contain between 1 and 256 bytes".into(), + }); + } + if !(1.0..=self.kind.maximum_duration().as_secs_f64()).contains(&self.duration_seconds()) { + return Err(Error::InvalidInput { + message: format!( + "profile duration must be between 1 and {} seconds", + self.kind.maximum_duration().as_secs() + ), + }); + } + Ok(()) + } +} + +/// Client controls for [`super::Job::wait_for_profile`]. +/// +/// Defaults to a 60-second timeout and two seconds between status requests. +/// The timeout includes requests and sleeps, and never cancels the capture or job. +#[derive(Debug, Clone)] +pub struct FunctionProfileWaitOptions { + pub(crate) timeout: Duration, + pub(crate) poll_interval: Duration, +} + +impl Default for FunctionProfileWaitOptions { + fn default() -> Self { + Self { + timeout: Duration::from_secs(60), + poll_interval: Duration::from_secs(2), + } + } +} + +impl FunctionProfileWaitOptions { + /// Use the default timeout and polling interval. + pub fn new() -> Self { + Self::default() + } + + /// Bound this wait without cancelling server-side work. + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self + } + + /// Delay between status requests; must be greater than zero. + pub fn poll_interval(mut self, interval: Duration) -> Self { + self.poll_interval = interval; + self + } +} diff --git a/rust/lancedb/src/job/state.rs b/rust/lancedb/src/job/state.rs new file mode 100644 index 000000000..c55e17d90 --- /dev/null +++ b/rust/lancedb/src/job/state.rs @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/// Detailed lifecycle of one job attempt. +/// +/// Unknown server values are retained and are never considered successful or +/// terminal. Legacy client and server labels are accepted by [`Self::from`]. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum JobState { + Created, + Queued, + InProgress, + Succeeded, + Failed, + Canceled, + TimedOut, + Unknown(String), +} + +impl JobState { + /// The canonical wire spelling, or the unrecognized value unchanged. + pub fn as_str(&self) -> &str { + match self { + Self::Created => "created", + Self::Queued => "queued", + Self::InProgress => "in_progress", + Self::Succeeded => "succeeded", + Self::Failed => "failed", + Self::Canceled => "canceled", + Self::TimedOut => "timed_out", + Self::Unknown(value) => value, + } + } + + /// Whether this is a recognized terminal state. + pub fn is_terminal(&self) -> bool { + matches!( + self, + Self::Succeeded | Self::Failed | Self::Canceled | Self::TimedOut + ) + } + + /// Only recognized success establishes that the operation completed. + pub fn is_success(&self) -> bool { + matches!(self, Self::Succeeded) + } +} + +impl From<&str> for JobState { + fn from(value: &str) -> Self { + match value { + "created" | "CREATED" => Self::Created, + "queued" | "QUEUED" => Self::Queued, + "running" | "in_progress" | "IN_PROGRESS" => Self::InProgress, + "finished" | "done" | "DONE" | "succeeded" | "SUCCEEDED" => Self::Succeeded, + "failed" | "FAILED" => Self::Failed, + "canceled" | "CANCELED" | "cancelled" | "CANCELLED" => Self::Canceled, + "timed_out" | "TIMED_OUT" => Self::TimedOut, + other => Self::Unknown(other.to_string()), + } + } +} diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 0f02d90cf..a2f271b80 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -48,6 +48,8 @@ //! Install any `metrics`-compatible recorder to collect them. //! - `metrics-otel` - Add a pull-based adapter (the `metrics_otel` module) over //! the `metrics` facade for bridging metrics into OpenTelemetry or similar. +//! - `test-fixtures` - Expose shared golden data through `test_fixtures` for +//! downstream compatibility tests. Disabled by default. //! //! ### Quick Start //! @@ -216,9 +218,12 @@ pub mod query; pub mod remote; pub mod rerankers; pub mod secrets; +pub mod server_info; pub mod sql; pub mod storage_integration; pub mod table; +#[cfg(any(test, feature = "test-fixtures"))] +pub mod test_fixtures; #[cfg(test)] pub mod test_utils; pub mod utils; @@ -232,7 +237,8 @@ pub use blob::{BlobRangeRequest, blob, is_blob}; pub use connection::{ConnectNamespaceBuilder, Connection}; pub use error::{Error, JobFailure, Result}; pub use function::FunctionVersion; -pub use job::Job; +pub use job::{Job, JobState}; +pub use lance::table::format::BasePath; use lance_index::vector::ApproxMode as LanceApproxMode; use lance_linalg::distance::DistanceType as LanceDistanceType; pub use materialized_view::{ diff --git a/rust/lancedb/src/listing.rs b/rust/lancedb/src/listing.rs index a0f6e5d5e..a5541b629 100644 --- a/rust/lancedb/src/listing.rs +++ b/rust/lancedb/src/listing.rs @@ -19,7 +19,10 @@ pub struct ListingOptions { /// Starting continuation token; `None` starts at the beginning. pub page_token: Option, /// Maximum results per request, not a limit on the entire listing. - /// `None` uses the backend default. Must be between 1 and `i32::MAX`. + /// `None` uses the backend default. SQL-backed catalog listings default to + /// 1,000 rows and accept 1 through 10,000. The public listing API rejects + /// zero; SQL statements can separately use `LIMIT 0`. Other backends may + /// impose different limits. pub page_limit: Option, } @@ -31,6 +34,9 @@ impl ListingOptions { } /// Set the maximum number of results requested per page. + /// + /// SQL-backed catalog listings accept 1 through 10,000. A server can return + /// fewer rows, including none, with a continuation token. pub fn page_limit(mut self, limit: u32) -> Self { self.page_limit = Some(limit); self diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 536b1c72c..0591be948 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -287,6 +287,8 @@ pub struct MaterializedViewInfo { #[doc(hidden)] #[derive(Debug, Clone, PartialEq)] pub struct CreateMaterializedViewRequest { + /// Preserve an existing materialized view without refreshing it. + pub exist_ok: bool, /// Name of the new view. pub name: String, /// Namespace in which to create the view. @@ -299,6 +301,11 @@ pub struct CreateMaterializedViewRequest { pub auto_refresh_enabled: Option, /// Refresh interval in seconds. When absent, the server determines when to refresh. pub auto_refresh_interval_seconds: Option, + pub total_cpu_millis: Option, + pub total_memory_bytes: Option, + pub total_gpu_count: Option, + pub gpu_class: Option, + pub gpu_count: Option, } /// Prefix of the internal columns holding source columns a computed column @@ -958,7 +965,7 @@ fn is_declaration(key: &str) -> bool { || crate::table::computed_columns::is_declaration_key(key) } -fn without_declarations(field: &ArrowField) -> ArrowField { +pub(crate) fn without_declarations(field: &ArrowField) -> ArrowField { let metadata: HashMap = field .metadata() .iter() @@ -1123,6 +1130,10 @@ impl PreparedDeclaration { /// are validated over the assembled schema, and read only columns the /// view holds (see [`PreparedDeclaration::input_column`]). /// + /// `session` holds the DataFusion functions a declaration may call, as + /// for [`AddColumnsBuilder::computed`](crate::table::AddColumnsBuilder::computed); + /// `None` plans against Lance's built-in functions only. + /// /// ```no_run /// # #![recursion_limit = "256"] /// # use std::collections::HashMap; @@ -1148,7 +1159,7 @@ impl PreparedDeclaration { /// (INPUTS_META_KEY.into(), format!("[\"{text}\"]")), /// ])); /// let view = prepared - /// .with_computed_columns(vec![(1, length)], &[])? + /// .with_computed_columns(vec![(1, length)], &[], None)? /// .create("lengths") /// .await?; /// view.refresh().execute().await?; // rows land with `length` NULL @@ -1160,6 +1171,7 @@ impl PreparedDeclaration { mut self, columns: Vec<(usize, ArrowField)>, bindings: &[FunctionBinding], + session: Option<&datafusion::execution::context::SessionContext>, ) -> Result { let invalid = |message: String| Error::InvalidInput { message }; if columns.is_empty() { @@ -1223,7 +1235,7 @@ impl PreparedDeclaration { } rewrite_column_definitions(&mut metadata, self.schema.as_ref(), &fields)?; let schema = ArrowSchema::new_with_metadata(fields, metadata); - ensure_declarations_are_planned(&schema)?; + ensure_declarations_are_planned(&schema, session)?; self.schema = Arc::new(schema); Ok(self) } @@ -1569,19 +1581,31 @@ async fn prepare_with( } /// Builds a materialized view. Created by -/// [`Connection::create_materialized_view`]. +/// [`Connection::create_materialized_view`] or +/// [`Connection::create_materialized_view_from_query`]. pub struct CreateMaterializedViewBuilder { connection: Connection, name: String, namespace: Vec, - source: String, + input: MaterializedViewInput, source_namespace: Vec, - projections: Vec<(String, String)>, + projections: Option>, filter: Option, limit: Option, with_no_data: bool, + exist_ok: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, +} + +enum MaterializedViewInput { + Source(String), + Query(String), } fn source_sql_identifier( @@ -1604,19 +1628,25 @@ fn source_sql_identifier( } impl CreateMaterializedViewBuilder { - pub(crate) fn new(connection: Connection, name: String, source: String) -> Self { + fn new(connection: Connection, name: String, input: MaterializedViewInput) -> Self { Self { connection, name, namespace: Vec::new(), - source, + input, source_namespace: Vec::new(), - projections: Vec::new(), + projections: None, filter: None, limit: None, with_no_data: false, + exist_ok: false, auto_refresh_enabled: None, auto_refresh_interval_seconds: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + gpu_class: None, + gpu_count: None, } } @@ -1639,10 +1669,12 @@ impl CreateMaterializedViewBuilder { mut self, columns: impl IntoIterator, impl Into)>, ) -> Self { - self.projections = columns - .into_iter() - .map(|(output, expression)| (output.into(), expression.into())) - .collect(); + self.projections = Some( + columns + .into_iter() + .map(|(output, expression)| (output.into(), expression.into())) + .collect(), + ); self } @@ -1665,6 +1697,35 @@ impl CreateMaterializedViewBuilder { self } + /// Preserve an existing view's definition, data and refresh settings. + /// Defaults to false. A skipped creation does not refresh the view. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// db.create_materialized_view("saved", "source").exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + async fn existing_view(&self) -> Result> { + match self + .connection + .open_table(&self.name) + .namespace(self.namespace.clone()) + .execute() + .await + { + Ok(table) => MaterializedView::from_table(table).await.map(Some), + Err(Error::TableNotFound { .. }) => Ok(None), + Err(error) => Err(error), + } + } + /// Enable or disable automatic refresh in LanceDB Enterprise. /// When omitted, the server determines whether automatic refresh is enabled. /// LanceDB Embedded does not support automatic refresh. @@ -1692,22 +1753,38 @@ impl CreateMaterializedViewBuilder { } fn query(&self) -> Result { + if let MaterializedViewInput::Query(query) = &self.input { + if !self.source_namespace.is_empty() + || self.projections.is_some() + || self.filter.is_some() + || self.limit.is_some() + { + return Err(Error::InvalidInput { + message: "a defining query cannot be combined with source_namespace, select, only_if or limit".into(), + }); + } + return Ok(query.clone()); + } + let MaterializedViewInput::Source(source) = &self.input else { + unreachable!() + }; fn quote(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) } - let projection = if self.projections.is_empty() { - "*".to_string() - } else { - self.projections - .iter() - .map(|(output, expression)| format!("{expression} AS {}", quote(output))) - .collect::>() - .join(", ") - }; + let projection = + if let Some(projections) = self.projections.as_ref().filter(|p| !p.is_empty()) { + projections + .iter() + .map(|(output, expression)| format!("{expression} AS {}", quote(output))) + .collect::>() + .join(", ") + } else { + "*".to_string() + }; let source = source_sql_identifier( &self.source_namespace, - &self.source, + source, self.connection.uri().starts_with("db://"), ); let mut query = format!("SELECT {projection} FROM {source}"); @@ -1721,6 +1798,36 @@ impl CreateMaterializedViewBuilder { Ok(query) } + /// Set the default total cpu millis budget for this materialized view. + pub fn total_cpu_millis(mut self, value: u64) -> Self { + self.total_cpu_millis = Some(value); + self + } + + /// Set the default total memory bytes budget for this materialized view. + pub fn total_memory_bytes(mut self, value: u64) -> Self { + self.total_memory_bytes = Some(value); + self + } + + /// Set the default total gpu count budget for this materialized view. + pub fn total_gpu_count(mut self, value: u32) -> Self { + self.total_gpu_count = Some(value); + self + } + + /// Set the default GPU pool for initial population and later refreshes. + pub fn gpu_class(mut self, class: impl Into) -> Self { + self.gpu_class = Some(class.into()); + self + } + + /// Set the default positive GPU count for each worker. + pub fn gpu_count(mut self, count: u32) -> Self { + self.gpu_count = Some(count); + self + } + /// Submit creation and initial population, returning a [`Job`] that /// settles when the view is ready. Remote creation submits SQL; the handle's /// [`Job::job_type`] is `"query"` and its ID identifies that query. @@ -1730,12 +1837,18 @@ impl CreateMaterializedViewBuilder { .connection .database() .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: self.exist_ok, name: self.name.clone(), namespace_path: self.namespace.clone(), query: self.query()?, with_no_data: self.with_no_data, auto_refresh_enabled: self.auto_refresh_enabled, auto_refresh_interval_seconds: self.auto_refresh_interval_seconds, + total_cpu_millis: self.total_cpu_millis, + total_memory_bytes: self.total_memory_bytes, + total_gpu_count: self.total_gpu_count, + gpu_class: self.gpu_class.clone(), + gpu_count: self.gpu_count, }) .await; } @@ -1764,26 +1877,60 @@ impl CreateMaterializedViewBuilder { async fn execute_native(self) -> Result { crate::require_experimental_functions()?; - if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { + if self.exist_ok + && let Some(view) = self.existing_view().await? + { + return Ok(view); + } + if self.auto_refresh_enabled == Some(true) + || self.auto_refresh_interval_seconds.is_some() + || self.total_cpu_millis.is_some() + || self.total_memory_bytes.is_some() + || self.total_gpu_count.is_some() + || self.gpu_class.is_some() + || self.gpu_count.is_some() + { return Err(Error::NotSupported { message: "automatic materialized-view refresh requires LanceDB Enterprise" .to_string(), }); } - let source = self - .connection - .open_table(&self.source) - .namespace(self.source_namespace.clone()) - .execute() - .await?; - let prepared = prepare_declaration( - &source, - (!self.projections.is_empty()).then_some(self.projections.as_slice()), - self.filter.as_deref(), - self.limit, - ) - .await?; - let view = prepared.create_in(&self.namespace, &self.name).await?; + let prepared = match &self.input { + MaterializedViewInput::Source(name) => { + let source = self + .connection + .open_table(name) + .namespace(self.source_namespace.clone()) + .execute() + .await?; + prepare_declaration( + &source, + self.projections.as_deref().filter(|p| !p.is_empty()), + self.filter.as_deref(), + self.limit, + ) + .await? + } + MaterializedViewInput::Query(_) => { + let definition = MaterializedViewDefinition::from_sql(&self.query()?)?; + let source = self + .connection + .open_table(&definition.source_table) + .namespace(definition.source_namespace.clone()) + .execute() + .await?; + prepare_definition(&source, definition).await? + } + }; + let view = match prepared.create_in(&self.namespace, &self.name).await { + Ok(view) => view, + Err(Error::TableAlreadyExists { .. }) if self.exist_ok => { + return self.existing_view().await?.ok_or_else(|| Error::Runtime { + message: "materialized view disappeared after concurrent creation".into(), + }); + } + Err(error) => return Err(error), + }; if !self.with_no_data { view.refresh().execute().await?; } @@ -1863,18 +2010,132 @@ impl MaterializedView { view: self.clone(), source_version: None, full: false, + options: Default::default(), } } } +/// Per-execution resource caps and GPU placement for Enterprise MV refreshes. +/// +/// CPU is in millicores (1000 = one core), memory is bytes, and GPUs are a +/// simultaneous cap across the refresh. Each omitted resource inherits the +/// view defaults, then Function defaults, then deployment defaults. +/// Embedded refreshes reject these options. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct RefreshMaterializedViewOptions { + pub total_cpu_millis: Option, + pub total_memory_bytes: Option, + pub total_gpu_count: Option, + pub gpu_class: Option, + pub gpu_count: Option, +} + +impl RefreshMaterializedViewOptions { + pub(crate) fn is_empty(&self) -> bool { + self.total_cpu_millis.is_none() + && self.total_memory_bytes.is_none() + && self.total_gpu_count.is_none() + && self.gpu_class.is_none() + && self.gpu_count.is_none() + } + + pub(crate) fn validate(&self) -> Result<()> { + let invalid = |message: &str| Error::InvalidInput { + message: message.into(), + }; + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { + return Err(invalid( + "total_cpu_millis and total_memory_bytes must be positive integers", + )); + } + if let Some(class) = &self.gpu_class { + crate::function::validate_gpu_class_name(class)?; + if self.total_gpu_count == Some(0) { + return Err(invalid("gpu_class requires a positive GPU budget")); + } + } + if self.gpu_count == Some(0) { + return Err(invalid("gpu_count must be positive")); + } + if self + .gpu_count + .zip(self.total_gpu_count) + .is_some_and(|(per_worker, total)| per_worker > total) + { + return Err(invalid("total_gpu_count cannot fit one Function worker")); + } + Ok(()) + } + + pub(crate) fn sql_clause(&self, full: bool) -> Result { + self.validate()?; + let mut values = Vec::new(); + if full { + values.push("full = true".to_string()); + } + if let Some(cpu) = self.total_cpu_millis { + values.push(format!("total_cpu_millis = {cpu}")); + } + if let Some(memory) = self.total_memory_bytes { + values.push(format!("total_memory_bytes = {memory}")); + } + if let Some(gpu) = self.total_gpu_count { + values.push(format!("total_gpu_count = {gpu}")); + } + if let Some(class) = &self.gpu_class { + values.push(format!("gpu_class = '{class}'")); + } + if let Some(count) = self.gpu_count { + values.push(format!("gpu_count = {count}")); + } + Ok(if values.is_empty() { + String::new() + } else { + format!(" WITH ({})", values.join(", ")) + }) + } +} + /// Builds a refresh. Created by [`MaterializedView::refresh`]. pub struct RefreshMaterializedViewBuilder { view: MaterializedView, source_version: Option, full: bool, + options: RefreshMaterializedViewOptions, } impl RefreshMaterializedViewBuilder { + /// Override total CPU capacity in millicores for this refresh. + pub fn total_cpu_millis(mut self, total_cpu_millis: u64) -> Self { + self.options.total_cpu_millis = Some(total_cpu_millis); + self + } + + /// Override total memory in bytes for this refresh. + pub fn total_memory_bytes(mut self, total_memory_bytes: u64) -> Self { + self.options.total_memory_bytes = Some(total_memory_bytes); + self + } + + /// Cap concurrent GPUs for this refresh. Zero is CPU-only. + pub fn total_gpu_count(mut self, total_gpu_count: u32) -> Self { + self.options.total_gpu_count = Some(total_gpu_count); + self + } + + /// Select an operator-configured GPU class for this execution only. + /// Set the positive number of GPUs allocated to each worker. + pub fn gpu_count(mut self, count: u32) -> Self { + self.options.gpu_count = Some(count); + self + } + + pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { + self.options.gpu_class = Some(gpu_class.into()); + self + } + /// Force a complete rebuild instead of letting the server choose /// the refresh mode. Defaults to `false`. LanceDB Embedded views always rebuild. /// @@ -1900,14 +2161,22 @@ impl RefreshMaterializedViewBuilder { /// Submit the refresh and return a job that settles with its result. pub async fn execute_async(self) -> Result> { + self.options.validate()?; if self.view.table.as_native().is_none() { return self .view .table .base_table() - .refresh_materialized_view_async(self.source_version, self.full) + .refresh_materialized_view_async_with_options( + self.source_version, + self.full, + self.options, + ) .await; } + if !self.options.is_empty() { + return Err(Error::NotSupported { message: "resource budgets and GPU placement require an Enterprise materialized-view refresh".into() }); + } crate::require_experimental_functions()?; Ok(Job::spawned(tokio::spawn(async move { refresh::execute_refresh(&self.view.table, self.source_version).await @@ -1916,6 +2185,10 @@ impl RefreshMaterializedViewBuilder { /// Refresh the view, waiting for the job to finish. pub async fn execute(self) -> Result { + self.options.validate()?; + if self.view.table.as_native().is_some() && !self.options.is_empty() { + return Err(Error::NotSupported { message: "resource budgets and GPU placement require an Enterprise materialized-view refresh".into() }); + } if self.view.table.as_native().is_some() { return refresh::execute_refresh(&self.view.table, self.source_version).await; } @@ -1949,7 +2222,41 @@ impl Connection { name: impl Into, source: impl Into, ) -> CreateMaterializedViewBuilder { - CreateMaterializedViewBuilder::new(self.clone(), name.into(), source.into()) + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Source(source.into()), + ) + } + + /// Define a materialized view using a complete SQL query. + /// + /// Embedded connections parse the query with + /// [`MaterializedViewDefinition::from_sql`]. Remote connections send the + /// query to the server, which determines the supported SQL syntax. + /// Put projections, predicates and limits in the query rather than using + /// the builder's source-specific methods. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn create(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let view = db.create_materialized_view_from_query( + /// "events_by_kind", + /// "SELECT kind, count(*) AS n FROM events GROUP BY kind", + /// ).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_materialized_view_from_query( + &self, + name: impl Into, + query: impl Into, + ) -> CreateMaterializedViewBuilder { + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Query(query.into()), + ) } /// Open the materialized view named `name`. @@ -2111,6 +2418,65 @@ mod tests { ); } + #[tokio::test] + async fn query_builder_rejects_source_clauses() { + let conn = connect("memory://").execute().await.unwrap(); + let builder = || conn.create_materialized_view_from_query("mv", "SELECT * FROM src"); + for invalid in [ + builder().select([("x", "x")]), + builder().select(Vec::<(String, String)>::new()), + builder().only_if("x > 0"), + builder().limit(0), + builder().source_namespace(vec!["ns".into()]), + ] { + assert!(matches!(invalid.query(), Err(Error::InvalidInput { .. }))); + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn create_from_query_supports_grouping_and_background_population() { + let conn = connect("memory://").execute().await.unwrap(); + conn.create_table( + "src", + record_batch!(("kind", Utf8, ["a", "a", "b"])).unwrap(), + ) + .execute() + .await + .unwrap(); + let query = "SELECT kind, count(*) AS n FROM src GROUP BY kind"; + let view = conn + .create_materialized_view_from_query("groups", query) + .with_no_data(true) + .execute() + .await + .unwrap(); + assert_eq!(view.definition_sql(), query); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + view.refresh().execute().await.unwrap(); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); + conn.create_materialized_view_from_query("background", query) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + conn.open_materialized_view("background") + .await + .unwrap() + .table() + .count_rows(None) + .await + .unwrap(), + 2 + ); + } + #[test] fn sql_definition_defaults_share_one_metadata_value() { let metadata = HashMap::from([( @@ -2151,6 +2517,15 @@ mod tests { .await .unwrap(); + assert!(matches!( + view.refresh().total_gpu_count(0).execute().await, + Err(Error::NotSupported { .. }) + )); + assert!(matches!( + view.refresh().gpu_class("h100").execute_async().await, + Err(Error::NotSupported { .. }) + )); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); assert!( view.table() @@ -2563,7 +2938,7 @@ mod tests { (INPUTS_META_KEY.into(), "[\"x\"]".into()), ])); let view = prepared - .with_computed_columns(vec![(1, doubled)], &[]) + .with_computed_columns(vec![(1, doubled)], &[], None) .unwrap() .create("m") .await diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 1072b7684..8851d071e 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -133,7 +133,7 @@ pub(crate) async fn execute_refresh( })?; let physical = Arc::new(ArrowSchema::from(view_ds.schema())); - ensure_declarations_are_planned(&physical)?; + ensure_declarations_are_planned(&physical, view_ds.session().datafusion_session())?; if let Some(field) = physical .fields() .iter() diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 10914f5f2..bc460dc35 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -17,12 +17,15 @@ use arrow_schema::{DataType, SchemaRef}; use datafusion_common::{DataFusionError, Result as DataFusionResult}; use datafusion_execution::TaskContext; use datafusion_expr::{Expr, col, lit}; -use datafusion_physical_expr::{EquivalenceProperties, Partitioning}; +use datafusion_physical_expr::{ + EquivalenceProperties, Partitioning, expressions::col as physical_col, +}; use datafusion_physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, coalesce_partitions::CoalescePartitionsExec, execution_plan::{Boundedness, EmissionType}, limit::GlobalLimitExec, + projection::ProjectionExec, stream::RecordBatchStreamAdapter, }; use futures::{FutureExt, StreamExt, TryFutureExt, TryStreamExt, stream, try_join}; @@ -39,7 +42,7 @@ use lance_index::vector::DIST_COL; use crate::error::{Error, Result}; use crate::rerankers::rrf::RRFReranker; use crate::rerankers::{NormalizeMethod, Reranker, check_reranker_result}; -use crate::table::BaseTable; +use crate::table::{BaseTable, NativeTableExt}; use crate::utils::{MaxBatchLengthStream, TimeoutStream}; use crate::{ApproxMode, DistanceType}; use crate::{ @@ -658,6 +661,10 @@ pub struct QueryExecutionOptions { /// By default, this is 1024 pub max_batch_length: u32, /// Max duration to wait for the query to execute before timing out. + /// + /// The timeout also covers reading the results, so a caller that consumes + /// the stream slowly can exceed it. For a remote table it counts from when + /// the query is sent, and the server is given the same timeout. pub timeout: Option, /// How distributed worker metrics should be displayed by /// [`ExecutableQuery::analyze_plan`]. @@ -735,8 +742,14 @@ pub trait ExecutableQuery { /// an Stream of Arrow [`arrow_array::RecordBatch`] (and you can also independently /// access the [`arrow_schema::Schema`] without polling the stream). /// - /// Note: The size of the returned batches and the order of individual rows is - /// not deterministic. + /// Note: The size of the returned batches is not deterministic. Row order + /// depends on the query shape: an ordinary unfiltered base-only scan of a + /// fixed table version in Embedded returns manifest order unless + /// [`Query::scan_in_order`] is set to `false` or a nonempty + /// [`QueryBase::order_by`] adds a sort. RTE + /// tables scan the LSM by default; use `use_rte(false)` for the base-only + /// guarantee. Ranked searches return rank order, while Enterprise and + /// namespace-pushed scans have no order guarantee. /// /// LanceDb will use many threads to calculate results and, when /// the result set is large, multiple batches will be processed at one time. @@ -744,6 +757,11 @@ pub trait ExecutableQuery { /// stream is consumed slowly (this constrains the maximum memory used by a /// single query. /// + /// A remote table decodes batches as they arrive when the server streams + /// query results. If the response stops partway, the stream ends with + /// `Error::ResponseInterrupted`. The batches already returned are valid but + /// incomplete, and the query is not retried. + /// /// For simpler access or row-based access we recommend creating extension traits /// to convert Arrow data into your internal data model. fn execute_with_options( @@ -850,6 +868,18 @@ pub struct QueryRequest { #[doc(hidden)] pub take_offsets: Option>, + /// Row IDs whose requested order and multiplicity are restored after lookup. + /// This is client-side metadata, not part of the remote query protocol. + #[doc(hidden)] + pub take_row_ids: Option>, + + /// Restore `take_offsets` occurrences in the exact requested input order. + /// + /// This is client-side execution metadata and is not sent to remote + /// services. It cannot be combined with an explicit `order_by`. + #[doc(hidden)] + pub preserve_order: bool, + /// Apply filter to the returned rows. pub filter: Option, @@ -898,6 +928,11 @@ pub struct QueryRequest { /// This allows ordering query results by one or more columns in either ascending or descending order. pub order_by: Option>, + /// Require (`Some(true)`), allow (`Some(false)`), or leave unchanged (`None`) + /// the scan order. See [`Query::scan_in_order`] for the contract and its + /// boundaries. + pub scan_in_order: Option, + /// Controls RTE read routing. When unset (the default), a query against a /// table that carries an RTE write spec (see /// [`crate::Table::enable_rte`]) is routed through the LSM scanner so @@ -919,6 +954,8 @@ impl Default for QueryRequest { limit: None, offset: None, take_offsets: None, + take_row_ids: None, + preserve_order: false, filter: None, filter_error: None, full_text_search: None, @@ -930,12 +967,17 @@ impl Default for QueryRequest { norm: None, disable_scoring_autoprojection: false, order_by: None, + scan_in_order: None, use_rte: None, } } } impl QueryRequest { + pub(crate) fn has_take(&self) -> bool { + self.take_offsets.is_some() || self.take_row_ids.is_some() + } + /// Add a filter, combining it with any existing filter using a logical AND. /// /// If the new filter cannot be combined with the existing one (because they @@ -1014,6 +1056,64 @@ impl Query { VectorQuery::new(self) } + /// Require the results to follow storage order instead of allowing an + /// unordered scan. + /// + /// An unfiltered plain base-only scan of an Embedded table, pinned to one + /// dataset version, returns rows in that version's manifest order: + /// fragments in manifest order, then rows in fragment order. Ordinary + /// unfiltered base-only scans already use Lance's ordered scan by default, + /// so leaving this unset preserves that behavior. RTE tables scan the LSM + /// by default and do not provide this guarantee unless `use_rte(false)` + /// selects the base table. Use `true` when a caller assigns meaning to row + /// positions and must fail instead of silently receiving a different order. + /// + /// Explicit `true` also disables scalar-index filter planning. Legacy + /// scalar-index plans can materialize index rows in a different sequence, + /// so filters are evaluated over the manifest-ordered scan instead. Default + /// filtered scans can still use those plans and may not preserve manifest + /// order. The filter result is unchanged, but the scan can read more data. + /// + /// Leaving this unset preserves the backend default. In particular, a + /// namespace-backed native table configured for `QueryTable` pushdown may + /// not preserve order because the request has no order field; request + /// `true` to execute against Embedded storage. + /// + /// The order is fixed only for the dataset version being scanned. + /// Compaction, updates, or opening a newer version can change it, so pin a + /// version when positions must remain stable across executions. A latest + /// handle can also observe a different version between two executions. + /// + /// - `true` requires manifest order without adding a sort. A nonempty + /// [`QueryBase::order_by`], take query, vector, full-text, hybrid, or + /// reranked query conflicts with storage order and fails with + /// [`Error::InvalidInput`]. + /// Enterprise tables and RTE/LSM reads fail with [`Error::NotSupported`] + /// because they cannot uphold the requirement; set `use_rte(false)` to + /// read the RTE base table in storage order. Namespace-backed native + /// tables execute against Embedded storage instead of using `QueryTable` + /// pushdown, which has no order field, and fail if that storage cannot be + /// read. + /// + /// # Examples + /// + /// ```no_run + /// # use lancedb::query::ExecutableQuery; + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// let rows = table.query().scan_in_order(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + /// - `false` allows the backend to scan without preserving order. An + /// explicit nonempty `order_by` still applies its sort. + /// + /// A nonempty `order_by` replaces manifest order with a global sort. Vector + /// and full-text searches return ranked results regardless of this option. + pub fn scan_in_order(mut self, ordered: bool) -> Self { + self.request.scan_in_order = Some(ordered); + self + } + /// Find the nearest vectors to the given query vector. /// /// This converts the query from a plain query to a vector query. @@ -1316,7 +1416,11 @@ impl VectorQuery { /// /// None (the default) resolves to 0.5, preserving Auto probing. At 0 the /// search starts at the caller minimum; at 1 it searches all partitions - /// within the caller maximum. Intermediate values interpolate around Auto. + /// within the caller maximum. Efforts 0.1 and 0.25 target empirical mean + /// partition-routing recall of 80% and 90%, respectively, for L2, cosine + /// and dot with k up to 100,000. The budget adapts to the metric and k; + /// this is a calibration boundary, not a limit on k. Hamming and larger k + /// retain uncalibrated behavior. Other values interpolate between tiers. /// Later probing may continue when too few candidates are found. /// Any explicit value, including 0.5, overrides [`Self::nprobes`] regardless /// of setter order. Explicit minimum and maximum bounds still apply. @@ -1538,14 +1642,32 @@ impl VectorQuery { vector_query.inner_execute_with_options(internal_options) )?; + // A reranker can replace schema metadata. Only the two producing + // streams can establish the snapshot of a remote hybrid result. + let snapshot = |schema: SchemaRef| { + schema + .metadata() + .get("lancedb:query_version") + .zip(schema.metadata().get("lancedb:query_snapshot")) + .map(|(version, identity)| (version.clone(), identity.clone())) + }; + let stream_schemas = (fts_results.schema(), vec_results.schema()); + let fts_snapshot = snapshot(stream_schemas.0.clone()); + let vec_snapshot = snapshot(stream_schemas.1.clone()); + let query_snapshot = fts_snapshot.filter(|value| Some(value) == vec_snapshot.as_ref()); + let (fts_results, vec_results) = try_join!( fts_results.try_collect::>(), vec_results.try_collect::>() )?; - // try to get the schema to use when combining batches. - // if either - let (fts_schema, vec_schema) = hybrid::query_schemas(&fts_results, &vec_results); + // Preserve remote output schemas even when a leg has no batches. + // The WAL primary-key fallback retains its synthesized score schema. + let (fts_schema, vec_schema) = if self.parent.as_native().is_none() && pk_fusion.is_none() { + stream_schemas + } else { + hybrid::query_schemas(&fts_results, &vec_results) + }; // concatenate all the batches together let mut fts_results = concat_batches(&fts_schema, fts_results.iter())?; @@ -1586,6 +1708,16 @@ impl VectorQuery { check_reranker_result(&results)?; + if self.parent.as_native().is_none() { + let metadata = results.schema_metadata_mut(); + metadata.remove("lancedb:query_version"); + metadata.remove("lancedb:query_snapshot"); + if let Some((version, identity)) = query_snapshot { + metadata.insert("lancedb:query_version".into(), version); + metadata.insert("lancedb:query_snapshot".into(), identity); + } + } + let limit = self.request.base.limit.unwrap_or(DEFAULT_TOP_K); if results.num_rows() > limit { results = results.slice(0, limit); @@ -1676,42 +1808,42 @@ impl HasQuery for VectorQuery { } } -fn take_occurrences(offsets: &[u64]) -> HashMap { - let mut occurrences = HashMap::with_capacity(offsets.len()); - for offset in offsets { - *occurrences.entry(*offset).or_insert(0) += 1; +fn take_occurrences(indices: &[u64]) -> HashMap { + let mut occurrences = HashMap::with_capacity(indices.len()); + for index in indices { + *occurrences.entry(*index).or_insert(0) += 1; } occurrences } fn restore_take_batch_with_occurrences( batch: RecordBatch, - offsets: &[u64], + indices: &[u64], occurrences: &HashMap, ordering_column: &str, drop_ordering_column: bool, preserve_order: bool, ) -> Result { - let actual_offsets = batch + let actual_indices = batch .column_by_name(ordering_column) .ok_or_else(|| Error::Schema { message: format!( "take query result did not include ordering column '{ordering_column}'" ), })?; - let actual_offsets = match actual_offsets.data_type() { - DataType::UInt64 => actual_offsets + let actual_indices = match actual_indices.data_type() { + DataType::UInt64 => actual_indices .as_primitive::() .values() .to_vec(), - DataType::Int64 => actual_offsets + DataType::Int64 => actual_indices .as_primitive::() .values() .iter() - .map(|offset| { - u64::try_from(*offset).map_err(|_| Error::Schema { + .map(|index| { + u64::try_from(*index).map_err(|_| Error::Schema { message: format!( - "take query ordering column '{ordering_column}' contained a negative offset" + "take query ordering column '{ordering_column}' contained a negative index" ), }) }) @@ -1725,26 +1857,26 @@ fn restore_take_batch_with_occurrences( } }; - let mut desired_order = Vec::with_capacity(offsets.len()); + let mut desired_order = Vec::with_capacity(indices.len()); if preserve_order { - let ordering = actual_offsets + let ordering = actual_indices .iter() .copied() .enumerate() - .map(|(index, offset)| (offset, index as u64)) + .map(|(position, index)| (index, position as u64)) .collect::>(); - // Missing offsets retain the filter-based behavior of returning no row. + // Missing indices retain the filter-based behavior of returning no row. desired_order.extend( - offsets + indices .iter() - .filter_map(|offset| ordering.get(offset).copied()), + .filter_map(|index| ordering.get(index).copied()), ); } else { - // Public take queries do not guarantee output order. Preserve the lookup's - // existing order and only restore the multiplicity of each matching row. - for (index, offset) in actual_offsets.iter().enumerate() { - if let Some(count) = occurrences.get(offset) { - desired_order.extend(std::iter::repeat_n(index as u64, *count)); + // Unordered offset takes and explicitly sorted queries retain the lookup's + // order while restoring the multiplicity of each matching row. + for (position, index) in actual_indices.iter().enumerate() { + if let Some(count) = occurrences.get(index) { + desired_order.extend(std::iter::repeat_n(position as u64, *count)); } } } @@ -1761,7 +1893,15 @@ fn restore_take_batch_with_occurrences( }; if drop_ordering_column { - ordered_batch = ordered_batch.drop_column(ordering_column)?; + // Project preserves the row count even when no user columns were selected. + let columns = ordered_batch + .schema() + .fields() + .iter() + .enumerate() + .filter_map(|(i, field)| (field.name() != ordering_column).then_some(i)) + .collect::>(); + ordered_batch = ordered_batch.project(&columns)?; } Ok(ordered_batch) @@ -1770,32 +1910,32 @@ fn restore_take_batch_with_occurrences( #[cfg(test)] fn restore_take_batch( batch: RecordBatch, - offsets: &[u64], + indices: &[u64], ordering_column: &str, drop_ordering_column: bool, preserve_order: bool, ) -> Result { restore_take_batch_with_occurrences( batch, - offsets, - &take_occurrences(offsets), + indices, + &take_occurrences(indices), ordering_column, drop_ordering_column, preserve_order, ) } -/// Restores the logical offset occurrence sequence above the physical lookup plan. +/// Restores the logical index occurrence sequence above the physical lookup plan. /// /// The lookup plan returns each matching row at most once. For ordinary unordered /// takes this operator expands each input batch incrementally and preserves the -/// lookup's partitioning. The explicitly ordered reader path collects one coalesced +/// lookup's partitioning. Ordered takes collect one coalesced /// input before restoring requested order. Pagination must remain above this operator /// so it applies to occurrences. #[derive(Debug)] struct TakeRestoreExec { input: Arc, - offsets: Vec, + indices: Vec, occurrences: Arc>, ordering_column: String, drop_ordering_column: bool, @@ -1807,15 +1947,20 @@ struct TakeRestoreExec { impl TakeRestoreExec { fn try_new( input: Arc, - offsets: Vec, + indices: Vec, ordering_column: String, drop_ordering_column: bool, preserve_order: bool, ) -> Result { let schema = if drop_ordering_column { - RecordBatch::new_empty(input.schema()) - .drop_column(&ordering_column)? - .schema() + let schema = input.schema(); + let columns = schema + .fields() + .iter() + .enumerate() + .filter_map(|(i, field)| (field.name() != &ordering_column).then_some(i)) + .collect::>(); + Arc::new(schema.project(&columns)?) } else { input.schema() }; @@ -1838,8 +1983,8 @@ impl TakeRestoreExec { Ok(Self { input, - occurrences: Arc::new(take_occurrences(&offsets)), - offsets, + occurrences: Arc::new(take_occurrences(&indices)), + indices, ordering_column, drop_ordering_column, preserve_order, @@ -1858,7 +2003,7 @@ impl DisplayAs for TakeRestoreExec { write!( formatter, "TakeRestoreExec: occurrences={}", - self.offsets.len() + self.indices.len() ) } } @@ -1907,7 +2052,7 @@ impl ExecutionPlan for TakeRestoreExec { let child = children.into_iter().next().unwrap(); let plan = Self::try_new( child, - self.offsets.clone(), + self.indices.clone(), self.ordering_column.clone(), self.drop_ordering_column, self.preserve_order, @@ -1930,7 +2075,7 @@ impl ExecutionPlan for TakeRestoreExec { let input = self.input.execute(partition, context)?; let output_schema = self.schema.clone(); - let offsets = self.offsets.clone(); + let indices = self.indices.clone(); let occurrences = self.occurrences.clone(); let ordering_column = self.ordering_column.clone(); let drop_ordering_column = self.drop_ordering_column; @@ -1947,7 +2092,7 @@ impl ExecutionPlan for TakeRestoreExec { }; restore_take_batch_with_occurrences( batch, - &offsets, + &indices, &occurrences, &ordering_column, drop_ordering_column, @@ -1960,7 +2105,7 @@ impl ExecutionPlan for TakeRestoreExec { batch.and_then(|batch| { restore_take_batch_with_occurrences( batch, - &offsets, + &indices, &occurrences, &ordering_column, drop_ordering_column, @@ -1998,8 +2143,31 @@ impl ExecutionPlan for TakeRestoreExec { pub struct TakeQuery { parent: Arc, request: QueryRequest, - offsets: Option>, +} + +struct TakeLookup { + request: QueryRequest, + indices: Vec, + ordering_column: String, + drop_ordering_column: bool, + output_offset: usize, + output_limit: Option, preserve_order: bool, + output_projection: Option>, +} + +/// Take queries restore rows in the requested offset or row-id order, so an +/// explicit storage-order requirement cannot be honored. Check this before the +/// lookup strips the take selectors and hands the inner request to a scan. +pub(crate) fn validate_take_scan_in_order(request: &QueryRequest) -> Result<()> { + if request.scan_in_order == Some(true) { + return Err(Error::InvalidInput { + message: "scan_in_order(true) conflicts with take by row id or offset, which \ + defines its own result order" + .to_string(), + }); + } + Ok(()) } impl TakeQuery { @@ -2020,11 +2188,9 @@ impl TakeQuery { filter: Some(QueryFilter::Datafusion( col("_rowoffset").in_list(in_list, false), )), - take_offsets: Some(offsets.clone()), + take_offsets: Some(offsets), ..Default::default() }, - offsets: Some(offsets), - preserve_order: false, } } @@ -2032,24 +2198,31 @@ impl TakeQuery { /// /// See [`crate::Table::take_row_ids`] for more details. pub fn from_row_ids(parent: Arc, row_ids: Vec) -> Self { - let in_list: Vec = row_ids.iter().map(|id| lit(*id)).collect(); + let mut seen = HashSet::with_capacity(row_ids.len()); + let in_list = row_ids + .iter() + .copied() + .filter(|id| seen.insert(*id)) + .map(lit) + .collect(); Self { parent, request: QueryRequest { filter: Some(QueryFilter::Datafusion(col(ROW_ID).in_list(in_list, false))), + take_row_ids: Some(row_ids), ..Default::default() }, - offsets: None, - preserve_order: false, } } /// Preserve the requested offset order when restoring duplicate occurrences. /// - /// This is reserved for readers whose API explicitly guarantees ordering. - pub(crate) fn preserve_order(mut self) -> Self { - debug_assert!(self.offsets.is_some()); - self.preserve_order = true; + /// Found rows follow the input order, including repeated offsets. Missing + /// non-negative offsets are omitted. This cannot be combined with an + /// explicit `order_by`. + pub fn preserve_order(mut self) -> Self { + debug_assert!(self.request.take_offsets.is_some()); + self.request.preserve_order = true; self } @@ -2106,29 +2279,142 @@ impl TakeQuery { Ok((request, ordering_column, drop_ordering_column)) } - async fn prepare_offsets_lookup( + async fn prepare_take_lookup( parent: &dyn BaseTable, request: &QueryRequest, - ) -> Result<(QueryRequest, String, bool, usize, Option)> { - let (mut request, ordering_column, drop_ordering_column) = - Self::request_with_row_offset(parent, request).await?; + preserve_order: bool, + ) -> Result { + validate_take_scan_in_order(request)?; + let (indices, by_row_id) = match (&request.take_offsets, &request.take_row_ids) { + (Some(indices), None) => (indices.clone(), false), + (None, Some(indices)) => (indices.clone(), true), + _ => { + return Err(Error::InvalidInput { + message: "take lookup requires exactly one of take_offsets or take_row_ids" + .to_string(), + }); + } + }; + // The explicit flag only applies to offset takes. Row-id takes retain + // their existing implicit ordering behavior: input order when no sort is + // requested, and the explicit sort otherwise. + let explicit_preserve_order = !by_row_id && (preserve_order || request.preserve_order); + if explicit_preserve_order + && request + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { + return Err(Error::InvalidInput { + message: "preserve_order cannot be combined with an explicit order_by".to_string(), + }); + } + let preserve_order = if by_row_id { + request.order_by.as_ref().is_none_or(Vec::is_empty) + } else { + explicit_preserve_order + }; + let (mut request, ordering_column, drop_ordering_column, output_projection) = if by_row_id { + let mut request = request.clone(); + let with_row_id = request.with_row_id; + let mut names = match &request.select { + Select::All => None, + Select::Columns(names) => Some(names.clone()), + Select::Dynamic(pairs) => { + Some(pairs.iter().map(|(name, _)| name.clone()).collect()) + } + Select::Expr(pairs) => Some(pairs.iter().map(|(name, _)| name.clone()).collect()), + }; + let selected_row_id = names + .as_ref() + .is_some_and(|names| names.iter().any(|name| name == ROW_ID)); + // with_row_id appends the metadata column, but Lance leaves an + // existing projection alias named _rowid untouched. Rename that + // alias during lookup so it cannot be mistaken for the real ID. + let alias = if selected_row_id + && matches!(request.select, Select::Dynamic(_) | Select::Expr(_)) + { + let mut alias = "__lancedb_take_row_id".to_string(); + while names.as_ref().is_some_and(|names| names.contains(&alias)) { + alias.push('_'); + } + Some(alias) + } else { + None + }; + match &mut request.select { + // Remote tables expose metadata through with_row_id, not + // through the ordinary selected-column list. + Select::Columns(columns) => columns.retain(|name| name != ROW_ID), + Select::Dynamic(pairs) => { + if let Some(alias) = &alias { + for (name, _) in pairs.iter_mut().filter(|(name, _)| name == ROW_ID) { + *name = alias.clone(); + } + } + } + Select::Expr(pairs) => { + if let Some(alias) = &alias { + for (name, _) in pairs.iter_mut().filter(|(name, _)| name == ROW_ID) { + *name = alias.clone(); + } + } + } + Select::All => {} + } + if with_row_id && let Some(names) = &mut names { + if let Some(position) = names.iter().position(|name| name == ROW_ID) { + names.remove(position); + } + names.push(ROW_ID.to_string()); + } + let output_projection = if selected_row_id { + names.map(|names| { + names + .into_iter() + .map(|name| { + let input_name = if name == ROW_ID { + alias.as_ref().unwrap_or(&name).clone() + } else { + name.clone() + }; + (input_name, name) + }) + .collect() + }) + } else { + None + }; + let drop_row_id = alias.is_some() || (!with_row_id && !selected_row_id); + request.with_row_id = true; + (request, ROW_ID.to_string(), drop_row_id, output_projection) + } else { + let (request, column, drop_column) = + Self::request_with_row_offset(parent, request).await?; + (request, column, drop_column, None) + }; + request.take_offsets = None; + request.take_row_ids = None; // The lookup operates on distinct physical rows. Pagination is a logical // operation over occurrences and must be applied only after restoration. let output_offset = request.offset.take().unwrap_or_default(); let output_limit = request.limit.take(); - Ok(( + Ok(TakeLookup { request, + indices, ordering_column, drop_ordering_column, output_offset, output_limit, - )) + preserve_order, + output_projection, + }) } - fn wrap_offsets_plan( + fn wrap_take_plan( lookup: Arc, - offsets: &[u64], + indices: &[u64], ordering_column: String, drop_ordering_column: bool, output_offset: usize, @@ -2142,7 +2428,7 @@ impl TakeQuery { }; let restored: Arc = Arc::new(TakeRestoreExec::try_new( lookup, - offsets.to_vec(), + indices.to_vec(), ordering_column, drop_ordering_column, preserve_order, @@ -2159,7 +2445,7 @@ impl TakeQuery { } } - fn wrap_offsets_explanation( + fn wrap_take_explanation( lookup: &str, occurrence_count: usize, output_offset: usize, @@ -2199,21 +2485,6 @@ impl TakeQuery { } } - async fn create_offsets_plan( - &self, - offsets: &[u64], - options: QueryExecutionOptions, - ) -> Result> { - create_take_offsets_plan( - self.parent.as_ref(), - &self.request, - offsets, - options, - self.preserve_order, - ) - .await - } - /// Convert the `TakeQuery` into a `QueryRequest`. pub fn into_request(self) -> QueryRequest { self.request @@ -2258,15 +2529,22 @@ impl TakeQuery { } } -pub(crate) async fn create_take_offsets_plan( +pub(crate) async fn create_take_plan( parent: &dyn BaseTable, request: &QueryRequest, - offsets: &[u64], options: QueryExecutionOptions, preserve_order: bool, ) -> Result> { - let (request, ordering_column, drop_ordering_column, output_offset, output_limit) = - TakeQuery::prepare_offsets_lookup(parent, request).await?; + let TakeLookup { + request, + indices, + ordering_column, + drop_ordering_column, + output_offset, + output_limit, + preserve_order, + output_projection, + } = TakeQuery::prepare_take_lookup(parent, request, preserve_order).await?; let lookup_options = if preserve_order { options.without_output_batch_length_limit() } else { @@ -2276,43 +2554,73 @@ pub(crate) async fn create_take_offsets_plan( .create_plan(&AnyQuery::Query(request), lookup_options) .await?; - TakeQuery::wrap_offsets_plan( + let plan = TakeQuery::wrap_take_plan( lookup, - offsets, + &indices, ordering_column, drop_ordering_column, output_offset, output_limit, preserve_order, - ) + )?; + if let Some(projection) = output_projection { + let schema = plan.schema(); + let expressions = projection + .into_iter() + .map(|(input, output)| Ok((physical_col(&input, &schema)?, output))) + .collect::>>()?; + Ok(Arc::new(ProjectionExec::try_new(expressions, plan)?)) + } else { + Ok(plan) + } } -pub(crate) async fn explain_take_offsets_plan( +pub(crate) async fn explain_take_plan( parent: &dyn BaseTable, request: &QueryRequest, - offsets: &[u64], verbose: bool, + preserve_order: bool, ) -> Result { - let (request, _, _, output_offset, output_limit) = - TakeQuery::prepare_offsets_lookup(parent, request).await?; + let TakeLookup { + request, + indices, + output_offset, + output_limit, + preserve_order, + output_projection, + .. + } = TakeQuery::prepare_take_lookup(parent, request, preserve_order).await?; let lookup = parent .explain_plan(&AnyQuery::Query(request), verbose) .await?; - Ok(TakeQuery::wrap_offsets_explanation( + let explanation = TakeQuery::wrap_take_explanation( &lookup, - offsets.len(), + indices.len(), output_offset, output_limit, - false, - )) + preserve_order, + ); + if output_projection.is_some() { + Ok(format!( + "ProjectionExec\n{}", + explanation + .lines() + .map(|line| format!(" {line}")) + .collect::>() + .join("\n") + )) + } else { + Ok(explanation) + } } -pub(crate) async fn prepare_take_offsets_request( +pub(crate) async fn prepare_take_request( parent: &dyn BaseTable, request: &QueryRequest, ) -> Result { - let (request, _, _, _, _) = TakeQuery::prepare_offsets_lookup(parent, request).await?; - Ok(request) + Ok(TakeQuery::prepare_take_lookup(parent, request, false) + .await? + .request) } impl HasQuery for TakeQuery { @@ -2323,8 +2631,14 @@ impl HasQuery for TakeQuery { impl ExecutableQuery for TakeQuery { async fn create_plan(&self, options: QueryExecutionOptions) -> Result> { - if let Some(offsets) = &self.offsets { - return self.create_offsets_plan(offsets, options).await; + if self.request.has_take() { + return create_take_plan( + self.parent.as_ref(), + &self.request, + options, + self.request.preserve_order, + ) + .await; } let req = AnyQuery::Query(self.request.clone()); @@ -2335,7 +2649,7 @@ impl ExecutableQuery for TakeQuery { &self, options: QueryExecutionOptions, ) -> Result { - if self.offsets.is_some() { + if self.request.has_take() { let plan = self.create_plan(options.clone()).await?; let inner = execute_plan(plan, Default::default())?; let inner = MaxBatchLengthStream::new_boxed(inner, options.max_batch_length as usize); @@ -2354,23 +2668,14 @@ impl ExecutableQuery for TakeQuery { } async fn explain_plan(&self, verbose: bool) -> Result { - if let Some(offsets) = &self.offsets { - let (request, _, _, output_offset, output_limit) = - Self::prepare_offsets_lookup(self.parent.as_ref(), &self.request).await?; - // Ask the backend to explain only the distinct-row lookup. This keeps - // remote explanation non-executing while still showing the client-side - // operators that create_plan and execution place above that lookup. - let lookup = self - .parent - .explain_plan(&AnyQuery::Query(request), verbose) - .await?; - return Ok(Self::wrap_offsets_explanation( - &lookup, - offsets.len(), - output_offset, - output_limit, - self.preserve_order, - )); + if self.request.has_take() { + return explain_take_plan( + self.parent.as_ref(), + &self.request, + verbose, + self.request.preserve_order, + ) + .await; } let query = AnyQuery::Query(self.request.clone()); @@ -2378,10 +2683,9 @@ impl ExecutableQuery for TakeQuery { } async fn analyze_plan_with_options(&self, options: QueryExecutionOptions) -> Result { - if self.offsets.is_some() { + if self.request.has_take() { if self.parent.analyze_plan_is_remote() { - let (request, _, _, _, _) = - Self::prepare_offsets_lookup(self.parent.as_ref(), &self.request).await?; + let request = prepare_take_request(self.parent.as_ref(), &self.request).await?; // Remote analysis is owned by the service. The current wire // request represents only the distinct-row lookup, so return // the service report unchanged instead of fabricating metrics @@ -4100,6 +4404,53 @@ mod tests { ); } + async fn make_preserve_order_test_table(tmp_dir: &tempfile::TempDir) -> Table { + let dataset_path = tmp_dir.path().join("preserve_order.lance"); + let conn = connect(dataset_path.to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table( + "my_table", + RecordBatch::try_from_iter([( + "idx", + Arc::new(Int32Array::from(vec![0, 1, 2, 3])) as Arc, + )]) + .unwrap(), + ) + .execute() + .await + .unwrap(); + table + .add( + RecordBatch::try_from_iter([( + "idx", + Arc::new(Int32Array::from(vec![4, 5, 6, 7])) as Arc, + )]) + .unwrap(), + ) + .execute() + .await + .unwrap(); + table.delete("idx IN (1, 6)").await.unwrap(); + table + } + + fn collect_ids(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("idx") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect() + } + #[tokio::test] async fn test_take_offsets_applies_pagination_after_restoration() { let tmp_dir = tempdir().unwrap(); @@ -4150,6 +4501,104 @@ mod tests { ); } + #[tokio::test] + async fn test_take_offsets_preserve_order_across_fragments_deletes_and_batches() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + let offsets = vec![5, 0, 5, 2, 99, 4, 0]; + let expected = vec![7, 0, 7, 3, 5, 0]; + + let batches = table + .take_offsets(offsets.clone()) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + assert_eq!(collect_ids(&batches), expected); + + let converted = table + .take_offsets(offsets) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .into_request(); + let batches = table + .base_table() + .query( + &AnyQuery::Query(converted), + QueryExecutionOptions::default(), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_ids(&batches), expected); + + let batches = table + .take_offsets(vec![]) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + } + + #[tokio::test] + async fn test_take_offsets_preserve_order_paginates_after_restoration() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + + let batches = table + .take_offsets(vec![5, 0, 5, 2, 4, 0]) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .offset(2) + .limit(4) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_ids(&batches), vec![7, 3, 5, 0]); + } + + #[tokio::test] + async fn test_take_offsets_preserve_order_rejects_order_by() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + + let error = table + .take_offsets(vec![0, 2]) + .preserve_order() + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "idx".to_string(), + )])) + .execute() + .await + .err() + .unwrap(); + assert!( + error + .to_string() + .contains("preserve_order cannot be combined with an explicit order_by"), + "{error}" + ); + } + #[tokio::test] async fn test_take_offsets_create_plan_restores_occurrences() { let tmp_dir = tempdir().unwrap(); @@ -4201,12 +4650,88 @@ mod tests { } #[tokio::test] - async fn test_take_row_ids() { + async fn test_take_scan_in_order_is_rejected_before_lookup() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + + let mut offsets = table + .take_offsets(vec![5, 1, 17]) + .select(Select::Columns(vec!["id".to_string()])) + .limit(2) + .offset(1); + offsets.mut_query().scan_in_order = Some(true); + + let plan_err = offsets + .create_plan(QueryExecutionOptions::default()) + .await + .expect_err("take planning must reject scan_in_order(true)"); + assert!( + matches!(&plan_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {plan_err}" + ); + + let execution_err = offsets + .execute() + .await + .err() + .expect("take execution must reject scan_in_order(true)"); + assert!( + matches!(&execution_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {execution_err}" + ); + + let explain_err = offsets + .explain_plan(false) + .await + .expect_err("take explain must reject scan_in_order(true)"); + assert!( + matches!(&explain_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {explain_err}" + ); + + let mut row_ids = table.take_row_ids(vec![5, 1]); + row_ids.mut_query().scan_in_order = Some(true); + let row_id_err = row_ids + .execute() + .await + .err() + .expect("take by row id must reject scan_in_order(true)"); + assert!( + matches!(&row_id_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {row_id_err}" + ); + + // Allowing unordered scans leaves an ordinary take unchanged. + let mut allowed = table.take_offsets(vec![5, 1]); + allowed.mut_query().scan_in_order = Some(false); + let batches = allowed + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + 2 + ); + } + + #[rstest::rstest] + #[case::unsorted(vec![5, 1, 17], vec![5, 1, 17])] + #[case::duplicate_and_missing(vec![17, 5, 17, u64::MAX, 1], vec![17, 5, 17, 1])] + #[case::empty(vec![], vec![])] + #[tokio::test] + async fn test_take_row_ids(#[case] requested: Vec, #[case] expected: Vec) { let tmp_dir = tempdir().unwrap(); let table = make_test_table(&tmp_dir).await; let results = table - .take_row_ids(vec![5, 1, 17]) + .take_row_ids(requested) .execute() .await .unwrap() @@ -4215,18 +4740,255 @@ mod tests { .unwrap(); assert_eq!(results.len(), 1); - assert_eq!(results[0].num_rows(), 3); + assert_eq!(results[0].num_rows(), expected.len()); assert_eq!(results[0].num_columns(), 2); - let mut ids = results[0] + let ids = results[0] .column_by_name("id") .unwrap() .as_primitive::() .values() .to_vec(); - ids.sort(); + assert_eq!(ids, expected); + } - assert_eq!(ids, vec![1, 5, 17]); + #[rstest::rstest] + #[case::stable(true)] + #[case::physical(false)] + #[tokio::test] + async fn test_take_row_ids_deleted_and_pagination(#[case] stable: bool) { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = arrow_array::record_batch!( + ("id", Int32, [0, 1, 2, 3]), + ("label", Utf8, ["a", "b", "c", "d"]) + ) + .unwrap(); + let table = conn + .create_table("rows", vec![batch]) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams { + max_rows_per_file: 2, + max_rows_per_group: 2, + enable_stable_row_ids: stable, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let batches = table + .query() + .select(Select::columns(&["id"])) + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batch = concat_batches(&batches[0].schema(), &batches).unwrap(); + let row_ids: HashMap<_, _> = batch["id"] + .as_primitive::() + .values() + .iter() + .copied() + .zip( + batch[ROW_ID] + .as_primitive::() + .values() + .iter() + .copied(), + ) + .collect(); + table.delete("id = 1").await.unwrap(); + let take = table + .take_row_ids(vec![ + row_ids[&3], + row_ids[&1], + row_ids[&3], + u64::MAX, + row_ids[&0], + ]) + .select(Select::columns(&["label"])) + .with_row_id() + .offset(1) + .limit(2); + let batches = take + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["label"] + .as_string::() + .iter() + .collect::>(), + vec![Some("d"), Some("a")] + ); + assert_eq!( + actual[ROW_ID] + .as_primitive::() + .values() + .as_ref(), + &[row_ids[&3], row_ids[&0]] + ); + let request = take.clone().into_request(); + let direct = table + .base_table() + .query(&AnyQuery::Query(request), QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + concat_batches(&direct[0].schema(), &direct).unwrap(), + actual + ); + let plan = take + .create_plan(QueryExecutionOptions::default()) + .await + .unwrap(); + let planned = execute_plan(plan, Default::default()) + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + concat_batches(&planned[0].schema(), &planned).unwrap(), + actual + ); + } + + #[rstest::rstest] + #[case::empty(Select::Columns(vec![]), vec![], vec![])] + #[case::explicit_row_id(Select::columns(&[ROW_ID, "id"]), vec![ROW_ID, "id"], vec![5, 1, 17])] + #[case::dynamic_alias(Select::dynamic(&[(ROW_ID, "20 - id"), ("__lancedb_take_row_id", "id")]), vec![ROW_ID, "__lancedb_take_row_id"], vec![15, 19, 3])] + #[case::expr_alias(Select::expr_projection(&[(ROW_ID, lit(20) - col("id"))]), vec![ROW_ID], vec![15, 19, 3])] + #[tokio::test] + async fn test_take_row_ids_projection( + #[case] selection: Select, + #[case] names: Vec<&str>, + #[case] values: Vec, + #[values(false, true)] with_row_id: bool, + #[values(false, true)] order_by: bool, + ) { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let mut take = table.take_row_ids(vec![5, 1, 17]).select(selection); + if with_row_id { + take = take.with_row_id(); + } + if order_by { + take = take.order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])); + } + let batches = take + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!(actual.num_rows(), 3); + let mut expected_names = names.clone(); + if with_row_id { + expected_names.retain(|name| *name != ROW_ID); + expected_names.push(ROW_ID); + } + assert_eq!( + actual + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(), + expected_names + ); + if !values.is_empty() { + let row_ids = actual.column_by_name(ROW_ID).unwrap(); + if row_ids.data_type() == &DataType::UInt64 { + assert_eq!( + row_ids.as_primitive::().values().as_ref(), + if order_by { &[1, 5, 17] } else { &[5, 1, 17] } + ); + } else { + let mut expected = values; + if order_by { + expected.swap(0, 1); + } + assert_eq!( + row_ids.as_primitive::().values().as_ref(), + expected.as_slice() + ); + } + } + } + + #[tokio::test] + async fn test_take_row_ids_ignores_offset_preserve_flag_with_explicit_sort() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let mut request = table + .take_row_ids(vec![17, 5, 1, 5]) + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])) + .offset(1) + .limit(2) + .into_request(); + request.preserve_order = true; + + let batches = table + .base_table() + .query(&AnyQuery::Query(request), QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"].as_primitive::().values().as_ref(), + &[5, 5] + ); + } + + #[tokio::test] + async fn test_take_row_ids_explicit_order_by() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let batches = table + .take_row_ids(vec![17, 5, 1, 5]) + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])) + .offset(1) + .limit(2) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"].as_primitive::().values().as_ref(), + &[5, 5] + ); } } diff --git a/rust/lancedb/src/remote/catalog.rs b/rust/lancedb/src/remote/catalog.rs index 95facd04b..c620cf272 100644 --- a/rust/lancedb/src/remote/catalog.rs +++ b/rust/lancedb/src/remote/catalog.rs @@ -30,6 +30,8 @@ pub struct RemoteCatalogOptions { pub api_key: Option, /// Shared transport and authentication settings. pub client_config: ClientConfig, + /// Storage options supported by remote database connections. + pub storage_options: HashMap, /// SQL service endpoint used by returned database connections. /// Required for SQL when the catalog endpoint uses HTTPS. pub sql_host_override: Option, @@ -391,6 +393,10 @@ mod tests { .await; let mut options = RemoteCatalogOptions { api_key: Some("test-key".into()), + storage_options: HashMap::from([( + "azure_storage_account_name".into(), + "catalog-account".into(), + )]), ..Default::default() }; options.client_config.extra_headers = HashMap::from([ @@ -460,6 +466,10 @@ mod tests { ); assert!(!request.headers.contains_key("x-lancedb-database-prefix")); assert_eq!(request.headers["authorization"], "Bearer refreshed"); + assert_eq!( + request.headers["x-azure-storage-account-name"], + "catalog-account" + ); } assert_eq!( requests[0].line, diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index e0722bfbc..c15f72904 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -17,6 +17,9 @@ use crate::utils::validate_database_name; const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-request-id"); const DEFAULT_BLOB_REQUEST_CONCURRENCY: usize = 8; +/// M1 prototype routing threshold for direct Blob reads. It stays internal +/// until the acceptance benchmark establishes the right default. +const DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES: u64 = 10 * 1024 * 1024; pub fn redact_sensitive_headers(headers: &mut HeaderMap) { const SENSITIVE_HEADERS: [&str; 5] = [ @@ -69,14 +72,9 @@ pub trait HeaderProvider: Send + Sync + std::fmt::Debug { async fn get_headers(&self) -> Result>; } -/// Default maximum bytes per insert request (8 GiB). -/// -/// Sized so a multipart part can hold at least one full Lance data file (the -/// default is 1M rows / 90 GB per file), which keeps fragments from being split -/// into undersized files across parts. The time-based cut -/// ([`DEFAULT_MAX_REQUEST_DURATION_DIVISOR`]) bounds request duration on slow -/// uploads, so a large byte budget does not risk the read timeout. -const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 8 * 1024 * 1024 * 1024; +/// Default target size for replayable multipart IPC payloads (64 MiB). +/// A single oversized row (including its schema) may exceed the target. +const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 64 * 1024 * 1024; /// The default max request duration is the read timeout divided by this, leaving /// headroom for the server to finalize and acknowledge a part before the read @@ -92,7 +90,9 @@ pub struct ClientConfig { /// Maximum concurrent blob HTTP requests for this connection, shared by all /// tables and blob handles. Defaults to 8. The environment variable /// `LANCE_CLIENT_BLOB_REQUEST_CONCURRENCY` can also set this limit. - /// The value must be greater than zero. + /// The value must be between 1 and [`Semaphore::MAX_PERMITS`], inclusive. + /// Values outside that range are rejected with [`Error::InvalidInput`] when + /// the connection is created. pub blob_request_concurrency: Option, /// User agent to use for requests. The default provides the library /// name and version. @@ -114,28 +114,22 @@ pub struct ClientConfig { /// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment /// variable that contains the user ID value. pub user_id: Option, - /// Maximum number of bytes to send in a single insert HTTP request. + /// Target compressed IPC bytes per multipart request. Defaults to 64 MiB. /// - /// During a multipart write, each partition's data is split into one or more - /// parts of at most this many (Arrow IPC, compressed) bytes, each uploaded as - /// a separate request under the shared upload id. This bounds how long any - /// one request stays open, so large bulk ingests do not exceed the client - /// read timeout while the server streams the part to object storage. - /// - /// The request body is still streamed (not buffered), so this does not - /// increase peak memory. Set to `Some(0)` to disable splitting (one request - /// per partition). You can also set the `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` - /// environment variable. Defaults to 8 GiB. + /// Parts are buffered for retries with the same upload and part IDs. Input + /// batches are sliced before encoding. A single row and its schema are + /// indivisible and may exceed the target. Peak additional memory is bounded + /// by the number of active writers times the part size (plus encoding buffers). + /// Set to `Some(0)` to disable byte-based cuts, or configure + /// `LANCE_CLIENT_MAX_BYTES_PER_REQUEST`. Disabling cuts can require buffering + /// an entire partition for replay. pub max_bytes_per_request: Option, - /// Maximum wall-clock time to spend uploading a single insert HTTP request. + /// Maximum time spent filling a replayable multipart payload. /// - /// Complements [`Self::max_bytes_per_request`]: during a multipart write a - /// part is cut when it reaches either the byte budget or this duration, - /// whichever comes first. The client read timeout also covers the - /// request-body upload, so a slow or throttled upload of a large part can - /// hit that timeout before the byte budget is reached; cutting by time keeps - /// each request short enough that it completes (and the server acknowledges - /// the part) within the read timeout. + /// A part is cut after encoding a batch slice when either its byte budget + /// or this duration is reached. This does not impose a network deadline; + /// `timeout_config` controls HTTP timeouts. Timed-out parts are retried using + /// their original payload and transaction ID. /// /// Set to `Some(Duration::ZERO)` to disable the time-based cut. You can also /// set the `LANCE_CLIENT_MAX_REQUEST_DURATION` environment variable (integer @@ -306,8 +300,9 @@ pub struct RetryConfig { /// You can also set the `LANCE_CLIENT_RETRY_STATUSES` environment variable /// to set this value. Use a comma-separated list of integer values. /// - /// Note that write operations will never be retried on 5xx errors as this may - /// result in duplicated writes. + /// Non-idempotent writes do not replay ambiguous 5xx responses. Multipart + /// parts can retry configured statuses because each replay replaces the same + /// staged transaction. Completion is never replayed. /// /// The default is 409, 429, 500, 502, 503, 504. pub statuses: Option>, @@ -320,9 +315,16 @@ pub struct RetryConfig { #[derive(Clone)] pub struct RestfulLanceDbClient { client: reqwest::Client, + /// A separate client for presigned object-store traffic. It deliberately + /// carries none of the Enterprise default headers, so service credentials + /// never reach object storage. + object_store_client: reqwest::Client, host: String, pub(crate) retry_config: ResolvedRetryConfig, pub(crate) blob_request_semaphore: Arc, + /// Logical blob/range size at which a handle prefers a presigned direct + /// read over the existing proxy byte-range route. + pub(crate) blob_presign_threshold_bytes: u64, pub(crate) sender: S, pub(crate) header_provider: Option>, /// Connection-level read consistency interval. Drives the @@ -607,7 +609,7 @@ impl RestfulLanceDbClient { let client = client_builder .default_headers(default_headers) - .user_agent(client_config.user_agent) + .user_agent(client_config.user_agent.clone()) .build() .map_err(|err| Error::Other { message: "Failed to build HTTP client".into(), @@ -628,11 +630,29 @@ impl RestfulLanceDbClient { Self::resolve_max_bytes_per_request(client_config.max_bytes_per_request)?; let max_request_duration = Self::resolve_max_request_duration(client_config.max_request_duration, read_timeout)?; + + let mut object_store_builder = reqwest::Client::builder() + .connect_timeout(connect_timeout) + .read_timeout(read_timeout) + .pool_idle_timeout(pool_idle_timeout); + if let Some(timeout) = timeout { + object_store_builder = object_store_builder.timeout(timeout); + } + let object_store_client = object_store_builder + .user_agent(client_config.user_agent) + .build() + .map_err(|err| Error::Other { + message: "Failed to build object-store HTTP client".into(), + source: Some(Box::new(err)), + })?; + Ok(Self { client, + object_store_client, host, retry_config, blob_request_semaphore: Arc::new(Semaphore::new(blob_request_concurrency)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: client_config.header_provider, read_consistency_interval, @@ -658,6 +678,14 @@ impl RestfulLanceDbClient { message: "blob request concurrency must be greater than zero".into(), }); } + if value > Semaphore::MAX_PERMITS { + return Err(Error::InvalidInput { + message: format!( + "blob request concurrency must be at most {}, got {value}", + Semaphore::MAX_PERMITS + ), + }); + } Ok(value) } @@ -824,6 +852,34 @@ impl RestfulLanceDbClient { self.client.post(full_uri) } + /// Start a presigned object-store request. This client has no Enterprise + /// default headers and no dynamic header provider. + pub(crate) fn object_store_get(&self, url: &str) -> RequestBuilder { + self.object_store_client.get(url) + } + + /// Send presigned object-store traffic without request logging, request + /// ids, service headers, or signed URLs in returned errors. + pub(crate) async fn send_object_store( + &self, + req: RequestBuilder, + ) -> Result<(String, Response)> { + let request_id = "blob-direct".to_string(); + let (client, request) = req.build_split(); + let request = request.map_err(|err| Error::Http { + source: Box::new(err.without_url()), + request_id: request_id.clone(), + status_code: None, + })?; + let response = self + .sender + .send(&client, request) + .await + .map_err(|err| err.without_url()) + .err_to_http(request_id.clone())?; + Ok((request_id, response)) + } + pub fn put(&self, uri: &str) -> RequestBuilder { let full_uri = format!("{}{}", self.host, uri); self.client.put(full_uri) @@ -888,6 +944,16 @@ impl RestfulLanceDbClient { Ok((request_id, response)) } + pub(crate) fn with_retries(&self, retries: Option) -> Self { + let mut client = self.clone(); + if let Some(retries) = retries { + client.retry_config.retries = retries; + client.retry_config.connect_retries = retries; + client.retry_config.read_retries = retries; + } + client + } + /// Send the request using retries configured in the RetryConfig. /// If retry_5xx is false, 5xx requests will not be retried regardless of the statuses configured /// in the RetryConfig. @@ -963,6 +1029,13 @@ impl RestfulLanceDbClient { return Err(source); } retry_counter.increment_request_failures(source)?; + if status.is_server_error() { + log::warn!( + "Retrying request {} after gateway status {}", + request_id, + status + ); + } } Err(err) if err.is_connect() => { retry_counter.increment_connect_failures(err)?; @@ -1173,9 +1246,11 @@ pub mod test_utils { RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "http://localhost".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: MockSender { f: Arc::new(wrapper), }, @@ -1200,6 +1275,7 @@ pub mod test_utils { RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "http://localhost".to_string(), retry_config: config.retry_config.try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new( @@ -1207,6 +1283,7 @@ pub mod test_utils { .blob_request_concurrency .unwrap_or(DEFAULT_BLOB_REQUEST_CONCURRENCY), )), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: MockSender { f: Arc::new(wrapper), }, @@ -1498,6 +1575,29 @@ mod tests { ); } + /// A semaphore cannot hold more than `MAX_PERMITS`, so a larger configured + /// value is refused where it was set instead of panicking when the + /// connection is created. + #[test] + fn test_blob_request_concurrency_must_fit_a_semaphore() { + let error = RestfulLanceDbClient::::resolve_blob_request_concurrency(Some( + super::Semaphore::MAX_PERMITS + 1, + )) + .expect_err("a concurrency above the semaphore limit must be refused"); + assert!(matches!(error, Error::InvalidInput { .. })); + assert!( + error.to_string().contains("blob request concurrency"), + "{error}" + ); + assert_eq!( + RestfulLanceDbClient::::resolve_blob_request_concurrency(Some( + super::Semaphore::MAX_PERMITS + )) + .unwrap(), + super::Semaphore::MAX_PERMITS + ); + } + use super::*; use serial_test::serial; use std::time::Duration; @@ -1828,9 +1928,11 @@ mod tests { // Create client with header provider let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, @@ -1867,9 +1969,11 @@ mod tests { // Create client with header provider let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, @@ -1932,9 +2036,11 @@ mod tests { let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index b9a3f8ae1..5036d36e6 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -22,7 +22,8 @@ use lance_namespace::models::{ use crate::Error; use crate::database::{ CloneTableRequest, CreateTableMode, CreateTableRequest, Database, DatabaseOptions, - ExecuteQueryRequest, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest, + ExecuteQueryRequest, JobInfo, JobListFilter, OpenTableRequest, ReadConsistency, + TableNamesRequest, }; use crate::error::Result; use crate::function::{FunctionRegistrationRequest, FunctionVersion, GpuClass}; @@ -31,7 +32,7 @@ use crate::job::Job; use crate::listing::{ListingOptions, ListingPage}; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::job::{PauseJobResponse, RemoteJob, ResumeJobResponse, job_state_to_client}; -use crate::remote::util::stream_as_body; +use crate::remote::util::create_body; use crate::secrets::SecretInfo; use crate::table::BaseTable; use crate::utils::{ @@ -44,14 +45,42 @@ use super::client::{ ClientConfig, HeaderProvider, HttpSend, ID_DELIMITER, RequestResultExt, RestfulLanceDbClient, Sender, }; -use super::sql::SqlClient; use super::sql::materialized_view::quote_identifier; +use super::sql::{SecretWriteOperation, SqlClient}; use super::storage_integration as integration_sql; use super::table::RemoteTable; use super::util::parse_server_version; use super::{ARROW_STREAM_CONTENT_TYPE, extract_job_id}; use futures::TryStreamExt; +#[cfg(feature = "remote")] +fn direct_catalog_resource_error(error: Error) -> Error { + let Error::JobFailed { failure, .. } = &error else { + return error; + }; + let Some(Error::Sql { + message, + request_id, + grpc_code, + metadata, + }) = failure.source.as_deref() + else { + return error; + }; + let named_catalog_resource = metadata.resource.as_ref().is_some_and(|resource| { + matches!(resource.kind.as_str(), "function" | "namespace" | "secret") + }); + if !named_catalog_resource { + return error; + } + Error::Sql { + message: message.clone(), + request_id: request_id.clone(), + grpc_code: *grpc_code, + metadata: metadata.clone(), + } +} + // Request structure for the remote clone table API #[derive(serde::Serialize)] struct RemoteCloneTableRequest { @@ -357,7 +386,7 @@ impl RemoteDatabase { sql: options.sql_host_override.clone(), }, config, - RemoteOptions::default(), + StorageOptions(options.storage_options.clone()).into(), options.read_consistency_interval, super::client::ParsedDbUrl { db_name: name.unwrap_or("").to_string(), @@ -382,14 +411,6 @@ impl RemoteDatabase { read_consistency_interval: Option, parsed: super::client::ParsedDbUrl, ) -> Result { - let sql_client = SqlClient::new( - parsed.db_name.clone(), - parsed.db_prefix.clone(), - api_key.to_string(), - host_overrides.rest.clone(), - host_overrides.sql, - client_config.clone(), - ); let header_map = RestfulLanceDbClient::::default_headers( api_key, region, @@ -400,6 +421,27 @@ impl RemoteDatabase { &client_config, )?; + // Preserve the resolved source-account hint when table operations use SQL. + let mut sql_config = client_config.clone(); + if let Some(account) = header_map.get("x-azure-storage-account-name") { + sql_config.extra_headers.insert( + "x-azure-storage-account-name".into(), + account + .to_str() + .map_err(|error| Error::InvalidInput { + message: error.to_string(), + })? + .into(), + ); + } + let sql_client = SqlClient::new( + parsed.db_name.clone(), + parsed.db_prefix.clone(), + api_key.to_string(), + host_overrides.rest.clone(), + host_overrides.sql, + sql_config, + ); let namespace_headers: HashMap = header_map .iter() .filter_map(|(k, v)| { @@ -700,6 +742,18 @@ struct RemoteListJobRow { #[serde(default)] created_at_millis: i64, #[serde(default)] + completed_at_millis: Option, + #[serde(default)] + duration_millis: Option, + #[serde(default)] + columns: Vec, + #[serde(default)] + function_name: Option, + #[serde(default)] + function_version: Option, + #[serde(default)] + failure: Option, + #[serde(default)] progress: Option, #[serde(default)] phase: Option, @@ -769,22 +823,57 @@ impl Database for RemoteDatabase { if let Some(seconds) = request.auto_refresh_interval_seconds { options.push(format!("auto_refresh_interval_seconds = {seconds}")); } + if request.total_cpu_millis == Some(0) || request.total_memory_bytes == Some(0) { + return Err(Error::InvalidInput { + message: "total_cpu_millis and total_memory_bytes must be positive integers".into(), + }); + } + for (key, value) in [ + ("total_cpu_millis", request.total_cpu_millis), + ("total_memory_bytes", request.total_memory_bytes), + ("total_gpu_count", request.total_gpu_count.map(u64::from)), + ] { + if let Some(value) = value { + options.push(format!("{key} = {value}")); + } + } + + if let Some(class) = &request.gpu_class { + crate::function::validate_gpu_class_name(class)?; + options.push(format!("gpu_class = '{class}'")); + } + if let Some(count) = request.gpu_count { + if count == 0 { + return Err(Error::InvalidInput { + message: "gpu_count must be positive".into(), + }); + } + options.push(format!("gpu_count = {count}")); + } let name = request.name.replace('"', "\"\""); let options = if options.is_empty() { String::new() } else { format!(" WITH ({})", options.join(", ")) }; + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let submission = client .submit_materialized_view_job( format!( - "CREATE MATERIALIZED VIEW \"{name}\"{options} AS {}", + "CREATE MATERIALIZED VIEW{if_not_exists} \"{name}\"{options} AS {}", request.query ), request.namespace_path, ) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Ok(Job::new_done()) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new(Box::new(RemoteJob::new( @@ -859,8 +948,22 @@ impl Database for RemoteDatabase { validate_function_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .describe_function(name, version, namespace_path) + .describe_function(name, Some(version), namespace_path) .await + .map_err(direct_catalog_resource_error) + } + + async fn get_function_latest( + &self, + name: &str, + namespace_path: &[String], + ) -> Result { + validate_function_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .describe_function(name, None, namespace_path) + .await + .map_err(direct_catalog_resource_error) } async fn list_functions( @@ -903,6 +1006,23 @@ impl Database for RemoteDatabase { .await } + #[doc(hidden)] + async fn drop_function_with_warnings( + &self, + name: &str, + version: &str, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + validate_function_name(name)?; + validate_namespace(namespace_path)?; + let (outcome, job) = self + .sql_client()? + .drop_function_outcome(name, version, namespace_path) + .await?; + job.wait().await?; + Ok((outcome.dropped, outcome.warnings)) + } + async fn create_storage_integration( &self, name: &str, @@ -915,6 +1035,7 @@ impl Database for RemoteDatabase { query: sql, default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) @@ -928,12 +1049,13 @@ impl Database for RemoteDatabase { let name = integration_sql::object_name(name, namespace_path)?; let result = self .execute_query_async(ExecuteQueryRequest { - query: format!("DESCRIBE STORAGE INTEGRATION {name}"), + query: format!("DESCRIBE STORAGE INTEGRATION {name} FORMAT JSON"), default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; - integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) + super::sql::description(result.reader().await?.try_collect::>().await?) } async fn list_storage_integrations( @@ -941,30 +1063,9 @@ impl Database for RemoteDatabase { namespace_path: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace_path)?; - let result = self - .execute_query_async(ExecuteQueryRequest { - query: "SHOW STORAGE INTEGRATIONS".into(), - default_namespace_path: namespace_path.to_vec(), - parameters: None, - }) - .await?; - let mut names = - integration_sql::decode_names(&result.reader().await?.try_collect::>().await?)?; - if let Some(token) = options.page_token { - names.retain(|name| name > &token); - } - let mut page_token = None; - if let Some(limit) = options.page_limit - && names.len() > limit as usize - { - names.truncate(limit as usize); - page_token = names.last().cloned(); - } - Ok(ListingPage { - items: names, - page_token, - }) + self.sql_client()? + .list_names("SHOW STORAGE INTEGRATIONS", namespace_path, options) + .await } async fn drop_storage_integration(&self, name: &str, namespace_path: &[String]) -> Result<()> { @@ -974,6 +1075,7 @@ impl Database for RemoteDatabase { query: format!("DROP STORAGE INTEGRATION {name}"), default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; result.reader().await?.try_collect::>().await?; @@ -985,19 +1087,27 @@ impl Database for RemoteDatabase { name: &str, value: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result<()> { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .write_secret(name, value, namespace_path, true) + .write_secret( + name, + value, + namespace_path, + SecretWriteOperation::Create { exist_ok }, + ) .await + .map_err(direct_catalog_resource_error) } async fn alter_secret(&self, name: &str, value: &str, namespace_path: &[String]) -> Result<()> { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .write_secret(name, value, namespace_path, false) + .write_secret(name, value, namespace_path, SecretWriteOperation::Alter) .await + .map_err(direct_catalog_resource_error) } async fn list_secrets( &self, @@ -1008,11 +1118,15 @@ impl Database for RemoteDatabase { self.sql_client()? .list_secrets(namespace_path, options) .await + .map_err(direct_catalog_resource_error) } async fn drop_secret(&self, name: &str, namespace_path: &[String]) -> Result<()> { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; - self.sql_client()?.drop_secret(name, namespace_path).await + self.sql_client()? + .drop_secret(name, namespace_path) + .await + .map_err(direct_catalog_resource_error) } async fn describe_secret(&self, name: &str, namespace_path: &[String]) -> Result { crate::utils::validate_secret_name(name)?; @@ -1020,6 +1134,7 @@ impl Database for RemoteDatabase { self.sql_client()? .describe_secret(name, namespace_path) .await + .map_err(direct_catalog_resource_error) } async fn create_view( @@ -1027,11 +1142,12 @@ impl Database for RemoteDatabase { name: &str, query: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .create_view(name, query, namespace_path) + .create_view(name, query, namespace_path, exist_ok) .await } async fn describe_view( @@ -1170,16 +1286,39 @@ impl Database for RemoteDatabase { let handle = super::job::RemoteJob::new(self.client.clone(), job_id.to_string()); match crate::job::JobHandle::describe(&handle).await { Ok(description) => Ok(Job::opened(Box::new(handle), description)), - Err(Error::Http { - status_code: Some(StatusCode::NOT_FOUND), - .. - }) => Err(Error::JobNotFound { + Err( + error @ Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }, + ) => Err(Error::JobNotFound { job_id: job_id.to_string(), + source: Box::new(error), }), Err(err) => Err(err), } } + async fn server_info(&self) -> Result { + let req = self.client.get("/v1/server/info"); + let (request_id, response) = self.client.send(req).await?; + let response = match self.client.check_response(&request_id, response).await { + Ok(response) => response, + Err(Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }) => { + return Err(Error::NotSupported { + message: "Server build discovery requires a newer LanceDB server; \ + GET /v1/server/info returned 404 Not Found" + .into(), + }); + } + Err(error) => return Err(error), + }; + response.json().await.err_to_http(request_id) + } + async fn list_gpu_classes(&self) -> Result> { #[derive(serde::Deserialize)] struct Response { @@ -1207,7 +1346,54 @@ impl Database for RemoteDatabase { } async fn list_jobs(&self, options: ListingOptions) -> Result> { - let mut body = serde_json::json!({}); + self.list_jobs_filtered(JobListFilter::default(), options) + .await + } + + async fn list_jobs_filtered( + &self, + filter: JobListFilter, + options: ListingOptions, + ) -> Result> { + if self.db_name.is_empty() { + return Err(Error::InvalidInput { + message: "list_jobs requires a connected database".into(), + }); + } + if filter.table.is_none() && !filter.namespace_path.is_empty() { + return Err(Error::InvalidInput { + message: "namespace_path requires a table filter".into(), + }); + } + if let (Some(start), Some(end)) = + (filter.created_at_gte_millis, filter.created_at_lt_millis) + && start >= end + { + return Err(Error::InvalidInput { + message: "created_at_gte_millis must be less than created_at_lt_millis".into(), + }); + } + let mut body = serde_json::json!({"database": self.db_name}); + if let Some(table) = filter.table { + validate_table_name(&table)?; + validate_namespace(&filter.namespace_path)?; + body["table_ref"] = serde_json::json!({ + "db_name": self.db_name, + "table_id": {"namespace_path": filter.namespace_path, "table_name": table}, + }); + } + if let Some(state) = filter.state { + body["state"] = serde_json::json!(state); + } + if !filter.job_types.is_empty() { + body["job_types"] = serde_json::json!(filter.job_types); + } + if let Some(start) = filter.created_at_gte_millis { + body["created_at_gte_millis"] = start.into(); + } + if let Some(end) = filter.created_at_lt_millis { + body["created_at_lt_millis"] = end.into(); + } if let Some(token) = options.page_token { body["page_token"] = token.into(); } @@ -1227,6 +1413,12 @@ impl Database for RemoteDatabase { job_type: row.job_type, state: job_state_to_client(&row.state), created_at_millis: row.created_at_millis, + completed_at_millis: row.completed_at_millis, + duration_millis: row.duration_millis, + columns: row.columns, + function_name: row.function_name, + function_version: row.function_version, + failure: row.failure, progress: row.progress, phase: row.phase, paused: row.paused, @@ -1408,6 +1600,30 @@ impl Database for RemoteDatabase { // The remote create endpoint does not transmit Lance write parameters. // Reject them before consuming data or issuing a request, especially // for overwrite: silently using the server's format can lose intent. + // + // Name the blob-base options specifically: they carry data placement + // and URI-resolution semantics the server cannot honor, and a generic + // "write_options" message would not tell the caller which input to drop. + if let Some(params) = request.write_options.lance_write_params.as_ref() { + let unsupported = if params + .initial_bases + .as_ref() + .is_some_and(|bases| !bases.is_empty()) + { + Some("initial_bases") + } else if params.allow_external_blob_outside_bases { + Some("allow_external_blob_outside_bases") + } else { + None + }; + if let Some(option) = unsupported { + return Err(Error::NotSupported { + message: format!( + "{option} is not supported for table creation in LanceDB Enterprise" + ), + }); + } + } for (option, provided) in [ ( "write_options (including storage_options)", @@ -1425,7 +1641,7 @@ impl Database for RemoteDatabase { } } let data_schema = request.data.schema(); - let body = stream_as_body(request.data.scan_as_stream())?; + let body = create_body(request.data.scan_as_stream()).await?; let identifier = build_table_identifier(&request.name, &request.namespace_path)?; let req = self @@ -1516,10 +1732,13 @@ impl Database for RemoteDatabase { is_shallow: Some(request.is_shallow), }; - let req = self + let mut req = self .client .post(&format!("/v1/table/{}/clone", table_identifier.clone())) .json(&remote_request); + if request.exist_ok { + req = req.query(&[("exist_ok", true)]); + } let (request_id, rsp) = self.client.send(req).await?; @@ -1583,9 +1802,9 @@ impl Database for RemoteDatabase { let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; let rsp = RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; - self.client.check_response(&request_id, rsp).await?; + let rsp = self.client.check_response(&request_id, rsp).await?; - Ok(Arc::new(RemoteTable::new_with_sql_client( + let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), self.db_name.clone(), request.name, @@ -1593,7 +1812,10 @@ impl Database for RemoteDatabase { identifier, version, self.sql_client.clone(), - ))) + )); + table.seed_blob_ranges_capability(rsp.headers()); + table.seed_blob_locations_capability(rsp.headers()); + Ok(table) } else { // Describe the table to confirm it exists before moving on. let req = self @@ -1604,6 +1826,7 @@ impl Database for RemoteDatabase { RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; let rsp = self.client.check_response(&request_id, rsp).await?; let version = parse_server_version(&request_id, &rsp)?; + let describe_headers = rsp.headers().clone(); let describe_body = rsp.text().await.ok(); let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), @@ -1614,6 +1837,8 @@ impl Database for RemoteDatabase { version.clone(), self.sql_client.clone(), )); + table.seed_blob_ranges_capability(&describe_headers); + table.seed_blob_locations_capability(&describe_headers); // This describe already carries the schema, so hand it to the table // instead of making the first schema read fetch it again. A version or // branch pin applied after this invalidates the cache. @@ -1909,7 +2134,8 @@ mod tests { use rstest::rstest; use crate::connection::ConnectBuilder; - use crate::database::Database; + use crate::database::{Database, JobListFilter, JobListState}; + use crate::error::{JobFailure, RemoteErrorMetadata, RemoteResourceIdentity}; use crate::graph::{EdgeTable, Endpoint, NodeTable, PropertyGraphDefinition}; use crate::materialized_view::CreateMaterializedViewRequest; use crate::{ @@ -1919,6 +2145,53 @@ mod tests { remote::{ARROW_STREAM_CONTENT_TYPE, ClientConfig, HeaderProvider, JSON_CONTENT_TYPE}, }; + #[test] + fn catalog_helpers_unwrap_only_a_named_resource_job_failure() { + let job_failed = |source: Error| Error::JobFailed { + job_id: Some("job-1".into()), + failure: Box::new(JobFailure { + sql_job_id: Some("job-1".into()), + source: Some(Arc::new(source)), + ..Default::default() + }), + }; + + for (kind, name) in [ + ("function", "missing"), + ("namespace", "missing_ns"), + ("secret", "missing_secret"), + ] { + let resource = RemoteResourceIdentity::new(kind, name, vec!["ns".into()]); + let sql = Error::Sql { + message: format!("{kind} '{name}' was not found"), + request_id: "worker-request".into(), + grpc_code: 5, + metadata: Box::new(RemoteErrorMetadata { + error_code: Some("not_found".into()), + job_id: Some("job-1".into()), + resource: Some(resource.clone()), + ..Default::default() + }), + }; + let Error::Sql { metadata, .. } = super::direct_catalog_resource_error(job_failed(sql)) + else { + panic!("catalog helper must surface the {kind} resource failure"); + }; + assert_eq!(metadata.resource, Some(resource)); + } + + let generic = Error::Sql { + message: "query failed".into(), + request_id: "worker-request".into(), + grpc_code: 3, + metadata: Box::new(RemoteErrorMetadata::default()), + }; + assert!(matches!( + super::direct_catalog_resource_error(job_failed(generic)), + Error::JobFailed { .. } + )); + } + #[tokio::test] async fn test_catalog_namespace_identifier_validates_all_namespace_components() { let mut db = super::RemoteDatabase::new_mock(|_| -> http::Response { @@ -2503,6 +2776,149 @@ mod tests { assert_eq!(table.name(), "table1"); } + #[tokio::test] + async fn test_create_table_over_budget_never_reaches_server() { + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + let mut bytes = vec![0u8; 8 * 1024 * 1024]; + SmallRng::seed_from_u64(42).fill_bytes(&mut bytes); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(arrow_array::LargeBinaryArray::from(vec![Some( + bytes.as_slice(), + )]))], + ) + .unwrap(); + for overwrite in [false, true] { + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |_| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + http::Response::builder().status(200).body("").unwrap() + }); + let input: Box = + Box::new(arrow_array::RecordBatchIterator::new( + (0..34).map(|_| Ok(batch.clone())).collect::>(), + batch.schema(), + )); + let mut create = conn.create_table("table1", input); + if overwrite { + create = create.mode(CreateTableMode::Overwrite); + } + let error = create.execute().await.unwrap_err(); + let message = error.to_string(); + assert!(message.contains("single-request budget"), "{message}"); + assert!( + message.contains("schema=") && message.contains("progress=True"), + "{message}" + ); + // The same assertion covers a new half-table and damage to an + // existing table under overwrite: neither mode sends a request. + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 0); + } + } + + #[tokio::test] + async fn test_create_table_slices_large_batches_in_one_atomic_request() { + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |request| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let bytes = request.body().unwrap().as_bytes().unwrap(); + let batches = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None) + .unwrap() + .collect::, _>>() + .unwrap(); + assert!(batches.len() > 1); + assert_eq!( + batches.iter().map(|b| b.num_rows()).sum::(), + 4_000_000 + ); + http::Response::builder().status(200).body("").unwrap() + }); + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from_iter_values(0..4_000_000))], + ) + .unwrap(); + conn.create_table("table1", input).execute().await.unwrap(); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_create_table_compacts_dictionary_slices_in_one_atomic_request() { + use arrow_array::{Array, DictionaryArray, StringArray, cast::AsArray, types::Int32Type}; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + + let mut bytes = vec![0; 128 * 72 * 1024]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .as_chunks::<{ 72 * 1024 }>() + .0 + .iter() + .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let mut batches = Vec::new(); + for values in [strings.clone(), strings.iter().rev().cloned().collect()] { + let dict = DictionaryArray::::new( + Int32Array::from_iter_values(0..128), + Arc::new(StringArray::from(values)), + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "category", + dict.data_type().clone(), + false, + )])); + batches.push(RecordBatch::try_new(schema, vec![Arc::new(dict)]).unwrap()); + } + let schema = batches[0].schema(); + let expected = strings + .iter() + .chain(strings.iter().rev()) + .cloned() + .collect::>(); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let wire_schema = schema.clone(); + let conn = Connection::new_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/table/table1/create/"); + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let body = request.body().unwrap().as_bytes().unwrap(); + let reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), wire_schema); + let batches = reader.collect::, _>>().unwrap(); + assert!( + (2..=8).contains(&batches.len()), + "dictionary produced {} encoding slices", + batches.len() + ); + let actual = batches + .iter() + .flat_map(|batch| { + let values = arrow_cast::cast(batch.column(0), &DataType::Utf8).unwrap(); + values + .as_string::() + .iter() + .map(|s| s.unwrap().to_owned()) + .collect::>() + }) + .collect::>(); + assert_eq!(actual, expected); + assert!(body.len() < 2 * bytes.len() + 64 * 1024); + http::Response::builder().status(200).body("").unwrap() + }); + let input: Box = Box::new( + arrow_array::RecordBatchIterator::new(batches.into_iter().map(Ok), schema), + ); + conn.create_table("table1", input).execute().await.unwrap(); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + } + #[tokio::test] async fn test_create_table_already_exists() { let conn = Connection::new_with_handler(|_| { @@ -2573,6 +2989,89 @@ mod tests { } } + #[tokio::test] + async fn test_create_rejects_blob_base_options_before_reading_input() { + let conn = Connection::new_with_handler(|_| -> http::Response<&'static str> { + panic!("must not send a create request") + }); + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let base = crate::BasePath::new(1, "s3://bucket/prefix".to_string(), None, false); + + let reads = Arc::new(AtomicUsize::new(0)); + let data: Box = Box::new(CountingReader { + schema: schema.clone(), + reads: reads.clone(), + }); + let err = conn + .create_table("table1", data) + .initial_bases(vec![base]) + .execute() + .await + .unwrap_err(); + assert!( + matches!(err, Error::NotSupported { ref message } if message.contains("initial_bases")), + "got {err:?}" + ); + assert_eq!(reads.load(Ordering::SeqCst), 0); + + let err = conn + .create_empty_table("table1", schema) + .allow_external_blob_outside_bases(true) + .execute() + .await + .unwrap_err(); + assert!( + matches!(err, Error::NotSupported { ref message } if message.contains("allow_external_blob_outside_bases")), + "got {err:?}" + ); + } + + #[tokio::test] + async fn test_create_accepts_empty_blob_base_options() { + // Empty bases and the explicit opt-out are not customization: the remote + // create must stay an ordinary request. + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.url().path(), "/v1/table/table1/create/"); + http::Response::builder().status(200).body("").unwrap() + }); + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let data = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .unwrap(); + for builder in [ + conn.create_table("table1", data) + .initial_bases(Vec::new()) + .allow_external_blob_outside_bases(false), + conn.create_empty_table("table1", schema) + .initial_bases(Vec::new()) + .allow_external_blob_outside_bases(false), + ] { + assert!(builder.execute().await.is_ok()); + } + } + + struct CountingReader { + schema: Arc, + reads: Arc, + } + + impl Iterator for CountingReader { + type Item = Result; + + fn next(&mut self) -> Option { + self.reads.fetch_add(1, Ordering::SeqCst); + None + } + } + + impl arrow_array::RecordBatchReader for CountingReader { + fn schema(&self) -> arrow_schema::SchemaRef { + self.schema.clone() + } + } + #[rstest] #[tokio::test] async fn test_open_rejects_local_options_even_when_cached(#[values(false, true)] cached: bool) { @@ -3362,9 +3861,10 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { - let conn = Connection::new_with_handler(|request| { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { + let conn = Connection::new_with_handler(move |request| { assert_eq!(request.method(), &reqwest::Method::POST); assert_eq!(request.url().path(), "/v1/table/cloned_table/clone"); assert_eq!( @@ -3376,12 +3876,18 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(body).unwrap(); assert_eq!(body["source_location"], "s3://bucket/source_table"); assert_eq!(body["is_shallow"], true); + if exist_ok { + assert_eq!(request.url().query(), Some("exist_ok=true")); + } else { + assert!(request.url().query().is_none()); + } http::Response::builder().status(200).body("").unwrap() }); let table = conn .clone_table("cloned_table", "s3://bucket/source_table") + .exist_ok(exist_ok) .execute() .await .unwrap(); @@ -3847,7 +4353,10 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) .unwrap(); - assert_eq!(body, serde_json::json!({"page_token": token, "limit": 2})); + assert_eq!( + body, + serde_json::json!({"database": "default", "page_token": token, "limit": 2}) + ); } else { let ns = "team"; assert_eq!( @@ -3890,6 +4399,106 @@ mod tests { } } + #[tokio::test] + async fn test_server_info_preserves_remote_provenance() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/server/info"); + http::Response::builder().status(200).body(serde_json::json!({ + "query_node": { "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" }, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_gpu_worker_image": "example.invalid/worker:configured", + "future_component": "ignored" + }).to_string()).unwrap() + }); + let info = conn.server_info().await.unwrap(); + let build = info.query_node.unwrap(); + assert_eq!(build.release, "1.2.3"); + assert_eq!(build.git_sha, "0123456789ab"); + assert_eq!(build.build_date.as_deref(), Some("2024-01-01T00:00:00Z")); + assert_eq!(info.function_worker_protocol_version, 25); + assert_eq!( + info.configured_gpu_worker_image.as_deref(), + Some("example.invalid/worker:configured") + ); + } + + #[tokio::test] + async fn test_server_info_error_provenance_survives_classification() { + for target in ["table", "job", "masked"] { + let conn = Connection::new_with_handler(move |_| { + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + if target == "masked" { + http::Response::builder() + .status(500) + .header("x-lancedb-server-build", server.to_string()) + .body("Internal server error".to_string()) + .unwrap() + } else { + http::Response::builder() + .status(404) + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let error = match target { + "table" => conn.open_table("missing").execute().await.unwrap_err(), + "job" => conn.open_job("missing").await.unwrap_err(), + _ => conn.server_info().await.unwrap_err(), + }; + match target { + "table" => assert!(matches!(&error, Error::TableNotFound { .. })), + "job" => assert!(matches!(&error, Error::JobNotFound { .. })), + _ => assert_eq!( + error.status_code(), + Some(http::StatusCode::INTERNAL_SERVER_ERROR) + ), + } + let server = error + .remote_error_metadata() + .unwrap() + .server + .as_ref() + .unwrap(); + assert_eq!(server.git_sha, "0123456789ab"); + assert_eq!(server.release, "1.2.3"); + let message = error.to_string(); + assert!(message.contains("0123456789ab"), "{message}"); + assert!(message.contains("2024-01-01T00:00:00Z"), "{message}"); + } + } + + #[tokio::test] + async fn test_server_info_distinguishes_unsupported_from_denied() { + for status in [404, 403] { + let conn = Connection::new_with_handler(move |_| { + http::Response::builder() + .status(status) + .body("unavailable") + .unwrap() + }); + let error = conn.server_info().await.unwrap_err(); + if status == 404 { + assert!( + matches!(error, Error::NotSupported { message } if message.contains("/v1/server/info")) + ); + } else { + assert!(matches!( + error, + Error::Http { + status_code: Some(http::StatusCode::FORBIDDEN), + .. + } + )); + } + } + } + #[tokio::test] async fn test_list_gpu_classes_reports_configured_hardware() { let conn = Connection::new_with_handler(|request| { @@ -3950,6 +4559,84 @@ mod tests { )); } + #[tokio::test] + async fn test_list_jobs_filters_every_page_without_eager_fetching() { + let count = Arc::new(AtomicUsize::new(0)); + let seen = count.clone(); + let conn = Connection::new_with_handler(move |request| { + let page = seen.fetch_add(1, Ordering::SeqCst); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + let mut expected = serde_json::json!({ + "database": "default", + "table_ref": { + "db_name": "default", + "table_id": {"namespace_path": ["team", "project"], "table_name": "events"}, + }, + "state": "in_progress", + "job_types": ["column_refresh", "materialized_view_refresh"], + "created_at_gte_millis": 100, + "created_at_lt_millis": 200, + "limit": 1, + }); + if page > 0 { + expected["page_token"] = "next".into(); + } + assert_eq!(body, expected); + http::Response::builder().status(200).body(serde_json::json!({ + "jobs": [{"job_id": format!("job-{page}"), "table": "events", "job_type": "column_refresh", "state": "in_progress", "created_at_millis": 100}], + "page_token": (page == 0).then_some("next"), + }).to_string()).unwrap() + }); + let filter = JobListFilter { + table: Some("events".into()), + namespace_path: vec!["team".into(), "project".into()], + state: Some(JobListState::InProgress), + job_types: vec!["column_refresh".into(), "materialized_view_refresh".into()], + created_at_gte_millis: Some(100), + created_at_lt_millis: Some(200), + }; + let mut jobs = + conn.list_jobs_filtered(filter.clone(), ListingOptions::default().page_limit(1)); + assert_eq!(count.load(Ordering::SeqCst), 0); + assert_eq!(jobs.try_next().await.unwrap().unwrap().job_id, "job-0"); + assert_eq!(count.load(Ordering::SeqCst), 1); + let resumed = conn.list_jobs_filtered( + filter, + ListingOptions::default() + .page_limit(1) + .page_token(jobs.page_token().unwrap()), + ); + let remaining = resumed.try_collect::>().await.unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].job_id, "job-1"); + assert_eq!(count.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_list_jobs_invalid_filters_never_reach_server() { + let conn = Connection::new_with_handler(|_| -> http::Response { + panic!("invalid filters must not reach the server") + }); + let namespace_only = JobListFilter { + namespace_path: vec!["team".into()], + ..Default::default() + }; + let invalid_time = JobListFilter { + created_at_gte_millis: Some(200), + created_at_lt_millis: Some(100), + ..Default::default() + }; + for filter in [namespace_only, invalid_time] { + let mut jobs = conn.list_jobs_filtered(filter, ListingOptions::default()); + assert!(matches!( + jobs.try_next().await, + Err(Error::InvalidInput { .. }) + )); + assert!(jobs.try_next().await.unwrap().is_none()); + } + } + #[tokio::test] async fn test_list_jobs_does_not_truncate_after_100_pages() { let conn = Connection::new_with_handler(|request| { @@ -3993,7 +4680,7 @@ mod tests { http::Response::builder() .status(200) .body( - r#"{"jobs": [{"job_id": "job-2", "table": "t2", "job_type": "create_index", "state": "succeeded", "created_at_millis": 2000}, {"job_id": "job-3", "table": "t3", "job_type": "create_index", "state": "timed_out", "created_at_millis": 3000}]}"#, + r#"{"jobs": [{"job_id": "job-2", "table": "t2", "job_type": "create_index", "state": "succeeded", "created_at_millis": 2000}, {"job_id": "job-3", "table": "t3", "job_type": "create_index", "state": "timed_out", "created_at_millis": 3000, "completed_at_millis": 3000, "duration_millis": 0, "columns": ["embedding"], "function_name": "features$embed", "function_version": "7", "failure": {"phase": "execute", "message": "worker failed", "retryable": false}}]}"#, ) .unwrap() } @@ -4011,11 +4698,26 @@ mod tests { assert_eq!(jobs[0].progress.as_ref().unwrap()["rows_computed"], 4); assert_eq!(jobs[0].phase.as_deref(), Some("running")); assert!(jobs[0].paused); + assert_eq!(jobs[0].completed_at_millis, None); + assert_eq!(jobs[0].duration_millis, None); + assert!(jobs[0].columns.is_empty()); + assert_eq!(jobs[0].function_name, None); + assert_eq!(jobs[0].function_version, None); + assert_eq!(jobs[0].failure, None); assert_eq!(jobs[1].job_id, "job-2"); assert_eq!(jobs[1].state, "finished"); assert_eq!(jobs[1].created_at_millis, 2000); assert_eq!(jobs[2].job_id, "job-3"); assert_eq!(jobs[2].state, "failed"); + assert_eq!(jobs[2].completed_at_millis, Some(3000)); + assert_eq!(jobs[2].duration_millis, Some(0)); + assert_eq!(jobs[2].columns, ["embedding"]); + assert_eq!(jobs[2].function_name.as_deref(), Some("features$embed")); + assert_eq!(jobs[2].function_version.as_deref(), Some("7")); + let failure = jobs[2].failure.as_ref().unwrap(); + assert_eq!(failure.message.as_deref(), Some("worker failed")); + assert_eq!(failure.retryable, Some(false)); + assert_eq!(failure.traceback, None); } #[tokio::test] @@ -4103,7 +4805,7 @@ mod tests { }); let err = conn.open_job("nope").await.unwrap_err(); assert!( - matches!(&err, Error::JobNotFound { job_id } if job_id == "nope"), + matches!(&err, Error::JobNotFound { job_id, .. } if job_id == "nope"), "{err:?}" ); } @@ -4147,6 +4849,49 @@ mod tests { ); } + #[tokio::test] + async fn test_job_timeline_fetches_recorded_trace_without_waiting() { + let conn = Connection::new_with_handler(|request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "job-1"); + let body = match request.url().path() { + "/v1/jobs/describe" => { + r#"{"job_id":"job-1","job_type":"function_refresh","job_state":"IN_PROGRESS","creation_ms":1}"# + } + "/v1/jobs/timeline" => { + r#"{"traceEvents":[{"ph":"X","pid":1,"tid":1,"ts":0,"dur":1000,"name":"Split 1"}],"metadata":{"partial":true}}"# + } + path => panic!("Unexpected request: {path}"), + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + let trace = job.timeline().await.unwrap(); + assert_eq!(trace["traceEvents"][0]["dur"], 1000); + assert_eq!(trace["metadata"]["partial"], true); + } + + #[tokio::test] + async fn test_job_timeline_rejects_an_unrelated_json_response() { + let conn = Connection::new_with_handler(|request| { + let body = if request.url().path() == "/v1/jobs/describe" { + r#"{"job_id":"job-1","job_type":"function_refresh","job_state":"SUCCEEDED","creation_ms":1}"# + } else { + r#"{"message":"not a trace"}"# + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + assert!( + job.timeline() + .await + .unwrap_err() + .to_string() + .contains("not Chrome Trace Event JSON") + ); + } + #[tokio::test] async fn test_job_events_scope_to_that_job() { let schema = Arc::new(Schema::new(vec![Field::new( @@ -4385,6 +5130,75 @@ mod tests { )); } + #[tokio::test] + async fn function_refresh_status_tracks_capacity_without_ending_wait() { + let polls = Arc::new(AtomicUsize::new(0)); + let count = polls.clone(); + let conn = Connection::new_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + // Open, status while waiting, status after admission, another wait + // observed inside wait(), and finally a successful completion. + let (state, phase) = match count.fetch_add(1, Ordering::SeqCst) { + 0 | 1 | 3 => ("IN_PROGRESS", "waiting_for_capacity"), + 2 => ("IN_PROGRESS", "running"), + _ => ("SUCCEEDED", "waiting_for_capacity"), + }; + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id": "job-1", "job_type": "function_refresh", + "job_state": state, "phase": phase, "creation_ms": 1 + }) + .to_string(), + ) + .unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + assert_eq!(job.status().await.unwrap(), "waiting_for_capacity"); + assert_eq!(job.state().as_deref(), Some("running")); + assert_eq!(job.status().await.unwrap(), "running"); + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert!(polls.load(Ordering::SeqCst) >= 6); + } + + #[tokio::test] + async fn capacity_status_requires_an_active_function_refresh() { + for (job_type, lifecycle, phase, paused_at) in [ + ( + "create_index", + "in_progress", + Some("waiting_for_capacity"), + None, + ), + ( + "function_refresh", + "in_progress", + Some("waiting_for_capacity"), + Some(42), + ), + ( + "function_refresh", + "queued", + Some("waiting_for_capacity"), + None, + ), + ("function_refresh", "in_progress", None, None), + ] { + let conn = Connection::new_with_handler(move |_| { + http::Response::builder().status(200).body( + serde_json::json!({ + "job_id": "job-1", "job_type": job_type, "job_state": "IN_PROGRESS", + "lifecycle_state": lifecycle, "phase": phase, "paused_at_millis": paused_at + }).to_string() + ).unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + assert_eq!(job.status().await.unwrap(), "running"); + } + } + #[tokio::test] async fn test_conn_job_waits_to_done() { let polls = Arc::new(AtomicUsize::new(0)); @@ -4423,6 +5237,13 @@ mod tests { for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { let result = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + + exist_ok: false, name: "adults".into(), namespace_path: vec![], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index a5baab7b0..7385a74d5 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -3,6 +3,8 @@ //! Tracking for server-side jobs through the `/v1/jobs` API. +mod profile; + use std::time::Duration; use arrow_array::RecordBatch; @@ -13,7 +15,10 @@ use serde::Deserialize; use crate::database::JobDescription; use crate::error::{Error, JobFailure, Result}; -use crate::job::{JobEventsRequest, JobHandle, JobProgressCallback, TerminalResult}; +use crate::job::{ + FunctionProfile, FunctionProfileOptions, JobEventsRequest, JobHandle, JobProgressCallback, + TerminalResult, +}; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; /// Delay before the second job-state poll; doubles up to [`MAX_POLL_INTERVAL`]. @@ -49,13 +54,15 @@ impl JobState { impl From<&str> for JobState { fn from(state: &str) -> Self { match state { - "IN_PROGRESS" | "in_progress" => Self::InProgress, - "CANCELLED" | "cancelled" | "canceled" => Self::Cancelled, + "IN_PROGRESS" | "in_progress" | "created" | "CREATED" | "queued" | "QUEUED" => { + Self::InProgress + } + "CANCELLED" | "cancelled" | "canceled" | "CANCELED" => Self::Cancelled, // The server reports a timed-out job as FAILED on describe; // accept the raw registry state too in case a future server // stops folding it. "FAILED" | "failed" | "TIMED_OUT" | "timed_out" => Self::Failed, - "DONE" | "done" | "succeeded" => Self::Done, + "DONE" | "done" | "succeeded" | "SUCCEEDED" => Self::Done, other => Self::Other(other.to_string()), } } @@ -74,6 +81,8 @@ pub(super) struct ReportedFailure { #[serde(default)] message: Option, #[serde(default)] + traceback: Option, + #[serde(default)] retryable: Option, #[serde(default)] sql_job_id: Option, @@ -107,6 +116,20 @@ pub(super) struct DescribeJobResponse { #[serde(default)] pub(super) job_id: String, #[serde(default)] + pub(super) attempt_job_id: Option, + #[serde(default)] + pub(super) operation_id: Option, + #[serde(default)] + pub(super) attempt: Option, + #[serde(default)] + pub(super) retry_of: Option, + #[serde(default)] + pub(super) lifecycle_state: Option, + #[serde(default)] + pub(super) source_table_version: Option, + #[serde(default)] + pub(super) execution_epoch: Option, + #[serde(default)] pub(super) job_type: String, pub(super) job_state: String, #[serde(default)] @@ -114,6 +137,8 @@ pub(super) struct DescribeJobResponse { #[serde(default)] pub(super) progress: Option, #[serde(default)] + pub(super) operation_progress: Option, + #[serde(default)] pub(super) phase: Option, #[serde(default)] pub(super) queue_reason: Option, @@ -134,6 +159,7 @@ impl ReportedFailure { JobFailure { phase: self.phase, message: self.message, + traceback: self.traceback, retryable: self.retryable, sql_job_id: self.sql_job_id, source: None, @@ -143,7 +169,7 @@ impl ReportedFailure { impl DescribeJobResponse { fn state(&self) -> JobState { - JobState::from(self.job_state.as_str()) + JobState::from(self.lifecycle_state.as_deref().unwrap_or(&self.job_state)) } fn into_terminal_result(self, request_id: String) -> TerminalResult { @@ -152,12 +178,23 @@ impl DescribeJobResponse { /// The public description this wire envelope stands for. pub(super) fn into_description(self) -> JobDescription { + let state = self.state().client_label(); JobDescription { job_id: self.job_id, + attempt_job_id: self.attempt_job_id, + operation_id: self.operation_id, + attempt: self.attempt, + retry_of: self.retry_of, + lifecycle_state: self + .lifecycle_state + .as_deref() + .map(crate::job::JobState::from), + source_table_version: self.source_table_version, + execution_epoch: self.execution_epoch, job_type: self.job_type, - state: JobState::from(self.job_state.as_str()).client_label(), + state, creation_ms: self.creation_ms, - progress: self.progress, + progress: self.operation_progress.or(self.progress), phase: self.phase, queue_reason: self.queue_reason, waiting_for_job_id: self.waiting_for_job_id, @@ -199,6 +236,32 @@ impl RemoteJob { Self { client, job_id } } + pub async fn retry_attempt(&self) -> Result { + let request = self + .client + .post("/v1/jobs/retry") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let response: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("invalid job retry response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + let job_id = response + .get("job_id") + .and_then(serde_json::Value::as_str) + .filter(|id| !id.is_empty()) + .ok_or_else(|| Error::Http { + source: "job retry response omitted the successor job_id".into(), + request_id, + status_code: None, + })?; + Ok(Self::new(self.client.clone(), job_id.to_string())) + } + /// One `/v1/jobs/describe` round trip. async fn fetch_description(&self) -> Result<(String, DescribeJobResponse)> { let request = self @@ -232,6 +295,117 @@ impl JobHandle for RemoteJob { Ok(self.fetch_description().await?.1.into_description()) } + async fn timeline(&self) -> Result { + let request = self + .client + .post("/v1/jobs/timeline") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let trace: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse job timeline: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if !trace + .get("traceEvents") + .is_some_and(serde_json::Value::is_array) + { + return Err(Error::Http { + source: "server response is not Chrome Trace Event JSON; job timeline export requires server support".into(), + request_id, status_code: None, + }); + } + Ok(trace) + } + + async fn stack(&self, worker_id: &str) -> Result { + let request = self + .client + .post("/v1/jobs/stack") + .json(&serde_json::json!({"job_id": self.job_id, "worker_id": worker_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let evidence: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse worker stack response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if evidence + .get("worker_id") + .and_then(serde_json::Value::as_str) + != Some(worker_id) + || !matches!( + evidence.get("status").and_then(serde_json::Value::as_str), + Some("captured" | "unavailable" | "unsupported") + ) + || !evidence + .get("stacks") + .is_some_and(serde_json::Value::is_array) + || !evidence + .get("execution_epoch") + .is_some_and(serde_json::Value::is_i64) + { + return Err(Error::Http { + source: + "server response is not worker stack evidence; capture requires server support" + .into(), + request_id, + status_code: None, + }); + } + Ok(evidence) + } + + async fn capture_profile( + &self, + worker_id: &str, + options: FunctionProfileOptions, + ) -> Result { + self.capture_profile_inner(worker_id, options).await + } + + async fn profile_status(&self, profile_id: &str) -> Result { + self.profile_status_inner(profile_id).await + } + + async fn profile_artifact(&self, profile_id: &str) -> Result { + self.profile_artifact_inner(profile_id).await + } + + async fn stats(&self) -> Result> { + let request = self + .client + .post("/v1/jobs/stats") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let response: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse job statistics: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if response.get("job_id").and_then(serde_json::Value::as_str) == Some(self.job_id.as_str()) + { + match response.get("report") { + Some(serde_json::Value::Null) => return Ok(None), + Some(serde_json::Value::String(report)) => return Ok(Some(report.clone())), + _ => {} + } + } + Err(Error::Http { + source: "server response is not a Function job run report; job statistics require server support".into(), + request_id, + status_code: None, + }) + } + async fn events(&self, request: JobEventsRequest) -> Result> { let mut body = serde_json::json!({ "job_id": self.job_id }); if let Some(limit) = request.limit { @@ -240,6 +414,9 @@ impl JobHandle for RemoteJob { if let Some(filter) = request.filter { body["filter"] = serde_json::Value::String(filter); } + if let Some(token) = request.page_token { + body["page_token"] = serde_json::Value::String(token); + } fetch_job_events(&self.client, body).await } @@ -264,12 +441,32 @@ impl JobHandle for RemoteJob { match description.state() { JobState::Done => return Ok(description.into_terminal_result(request_id)), JobState::Failed => { + let mut failure = description + .failure + .map(ReportedFailure::into_job_failure) + .unwrap_or_default(); + // The responding query node may have upgraded since this job + // failed. Only its persisted terminal writer identifies the failure. + if let Some(server) = description + .result + .as_ref() + .and_then(|result| result.get("terminal_server")) + .and_then(|server| { + serde_json::from_value::( + server.clone(), + ) + .ok() + }) + { + let provenance = format!("[server: {server}]"); + failure.message = Some(match failure.message { + Some(message) => format!("{message} {provenance}"), + None => provenance, + }); + } return Err(Error::JobFailed { job_id: Some(self.job_id.clone()), - failure: description - .failure - .map(ReportedFailure::into_job_failure) - .unwrap_or_default(), + failure: Box::new(failure), }); } JobState::Cancelled => { @@ -298,11 +495,15 @@ impl JobHandle for RemoteJob { .await .map(|_| ()) } + + async fn retry(&self) -> Result> { + Ok(Box::new(self.retry_attempt().await?)) + } } #[cfg(test)] mod tests { - use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -310,7 +511,7 @@ mod tests { use crate::Result; use crate::function::{FunctionVersion, RefreshColumnResult}; - use crate::job::{Job, JobHandle, JobProgressCallback, TerminalResult}; + use crate::job::{Job, JobHandle, JobProgressCallback, JobWaitOptions, TerminalResult}; use crate::remote::client::test_utils::client_with_handler; use super::{DescribeJobResponse, RemoteJob}; @@ -323,6 +524,425 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + #[tokio::test(start_paused = true)] + async fn timed_wait_stops_polling_and_can_resume_or_reopen_typed_maintenance_jobs() { + for job_type in ["compact", "prewarm_page_cache"] { + let done = Arc::new(AtomicBool::new(false)); + let describes = Arc::new(AtomicUsize::new(0)); + let complete = done.clone(); + let seen = describes.clone(); + let expected = if job_type == "compact" { + serde_json::json!({"partial_commit":false,"rows_succeeded":12,"rows_failed":0,"completion_percentage":100}) + } else { + serde_json::json!({"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}) + }; + let payload = expected.clone(); + let client = + client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + seen.fetch_add(1, Ordering::SeqCst); + let finished = complete.load(Ordering::SeqCst); + http::Response::builder().status(200).body(serde_json::json!({ + "job_id":"bounded-job", "job_type":job_type, + "job_state":if finished {"DONE"} else {"IN_PROGRESS"}, + "result":if finished {payload.clone()} else {serde_json::Value::Null}, + }).to_string()).unwrap() + }); + let handle = RemoteJob::new(client.clone(), "bounded-job".into()); + let description = handle.describe().await.unwrap(); + let job = Job::opened(Box::new(handle), description) + .into_typed::() + .unwrap(); + let observations = Arc::new(Mutex::new(Vec::new())); + let updates = observations.clone(); + let options = JobWaitOptions::new() + .timeout(Duration::from_millis(50)) + .progress(move |description| { + updates.lock().unwrap().push(description.state.clone()) + }); + // Bound a regression that accidentally ignores the wait deadline. + let eventual_completion = done.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(1)).await; + eventual_completion.store(true, Ordering::SeqCst); + }); + let error = job.wait_with_options(options.clone()).await.unwrap_err(); + assert!(matches!(error, crate::Error::Timeout { .. })); + assert!(error.to_string().contains("bounded-job")); + assert!(error.to_string().contains("Connection::open_job")); + assert_eq!(job.state().as_deref(), Some("running")); + assert_eq!(describes.load(Ordering::SeqCst), 2); + tokio::time::advance(Duration::from_secs(2)).await; + tokio::task::yield_now().await; + assert_eq!( + describes.load(Ordering::SeqCst), + 2, + "timed-out poller must stop" + ); + assert_eq!(*observations.lock().unwrap(), ["running"]); + done.store(true, Ordering::SeqCst); + let result = job + .wait_with_options(options.timeout(Duration::from_secs(1))) + .await + .unwrap(); + assert_eq!(result, expected); + assert_eq!(*observations.lock().unwrap(), ["running", "finished"]); + let handle = RemoteJob::new(client, "bounded-job".into()); + let description = handle.describe().await.unwrap(); + let reopened = Job::opened(Box::new(handle), description) + .into_typed::() + .unwrap(); + assert_eq!( + reopened + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await + .unwrap(), + result + ); + } + } + + #[tokio::test(start_paused = true)] + async fn one_wait_timeout_does_not_interrupt_another_waiter() { + let done = Arc::new(AtomicBool::new(false)); + let complete = done.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + http::Response::builder().status(200).body(serde_json::json!({ + "job_state":if complete.load(Ordering::SeqCst) {"DONE"} else {"IN_PROGRESS"}, + }).to_string()).unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "shared-job".into()))); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(100)).await; + done.store(true, Ordering::SeqCst); + }); + let (short, long) = tokio::join!( + job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(50))), + job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))), + ); + assert!(matches!(short, Err(crate::Error::Timeout { .. }))); + long.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + } + + #[tokio::test] + async fn stack_preserves_availability_and_uses_the_selected_worker() { + for status in ["captured", "unsupported", "unavailable"] { + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/stack"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!( + body, + serde_json::json!({"job_id":"job-1", "worker_id":"worker-1"}) + ); + http::Response::builder().status(200).body(serde_json::json!({ + "worker_id":"worker-1", "status":status, "execution_epoch":1, "stacks":[], "omitted_sessions":0 + }).to_string()).unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert_eq!(job.stack("worker-1").await.unwrap()["status"], status); + } + } + + #[tokio::test] + async fn stack_rejects_unrelated_responses_and_preserves_authorization_errors() { + for body in [ + "{}", + r#"{"worker_id":"other","status":"captured","execution_epoch":1,"stacks":[]}"#, + ] { + let client = client_with_handler(move |_| { + http::Response::builder().status(200).body(body).unwrap() + }); + assert!(matches!( + RemoteJob::new(client, "job-1".into()) + .stack("worker-1") + .await + .unwrap_err(), + crate::Error::Http { .. } + )); + } + let client = client_with_handler(|_| { + http::Response::builder() + .status(403) + .body("access denied") + .unwrap() + }); + assert!( + RemoteJob::new(client, "job-1".into()) + .stack("worker-1") + .await + .unwrap_err() + .to_string() + .contains("403") + ); + } + + #[tokio::test] + async fn wait_preserves_a_timed_out_attempt_without_an_extra_status_request() { + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let client = client_with_handler(move |_| { + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body(r#"{"job_state":"FAILED","lifecycle_state":"timed_out"}"#.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "attempt-1".to_string()))); + for _ in 0..2 { + assert!(matches!( + job.wait().await, + Err(crate::Error::JobFailed { .. }) + )); + assert_eq!(job.state().as_deref(), Some("failed")); + assert_eq!(job.lifecycle_state(), Some(crate::JobState::TimedOut)); + } + assert_eq!(requests.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn local_and_remote_jobs_share_terminal_state_contract() { + for remote in [false, true] { + for state in [ + crate::JobState::Succeeded, + crate::JobState::Failed, + crate::JobState::Canceled, + ] { + let job = if remote { + let response_state = state.as_str().to_string(); + let client = client_with_handler(move |request| { + let body = if request.url().path() == "/v1/jobs/cancel" { + "{}".to_string() + } else { + serde_json::json!({ + "job_id": "attempt-2", "operation_id": "attempt-1", "attempt": 2, + "retry_of": "attempt-1", "job_state": "IN_PROGRESS", + "lifecycle_state": response_state, "source_table_version": 7, "execution_epoch": 3, + }).to_string() + }; + http::Response::builder().status(200).body(body).unwrap() + }); + Job::new(Box::new(RemoteJob::new(client, "attempt-2".to_string()))) + } else { + match state { + crate::JobState::Succeeded => Job::spawned(tokio::spawn(async { Ok(()) })), + crate::JobState::Failed => Job::spawned(tokio::spawn(async { + Err::<(), _>(crate::Error::Runtime { + message: "failed".to_string(), + }) + })), + _ => Job::spawned(tokio::spawn(std::future::pending::>())), + } + }; + if state == crate::JobState::Canceled { + job.cancel().await.unwrap(); + } + for _ in 0..2 { + let result = job.wait().await; + match state { + crate::JobState::Succeeded => result.unwrap(), + crate::JobState::Failed => { + assert!(matches!(result, Err(crate::Error::JobFailed { .. }))) + } + _ => assert!(matches!(result, Err(crate::Error::JobCancelled { .. }))), + } + assert_eq!(job.lifecycle_state(), Some(state.clone())); + assert_eq!(job.status_typed().await.unwrap(), state); + } + let identity = job.job_id().unwrap(); + let operation = job.operation_id(); + let mapped = job.map(|()| 7); + assert_eq!(mapped.job_id().as_deref(), Some(identity.as_str())); + assert_eq!(mapped.operation_id(), operation); + if remote { + assert_eq!(mapped.retry_of().as_deref(), Some("attempt-1")); + assert_eq!(mapped.attempt(), Some(2)); + assert_eq!(mapped.source_table_version(), Some(7)); + } else { + uuid::Uuid::parse_str(&identity).unwrap(); + assert_eq!(mapped.attempt(), Some(1)); + } + } + } + } + + #[tokio::test] + async fn unknown_detailed_state_never_inherits_legacy_success() { + let client = client_with_handler(|_| { + http::Response::builder().status(200).body( + r#"{"job_id":"job-1","job_state":"DONE","lifecycle_state":"publishing_in_future","result":null}"# + ).unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".to_string()))); + assert_eq!(job.status().await.unwrap(), "publishing_in_future"); + let state = job.status_typed().await.unwrap(); + assert_eq!(state.as_str(), "publishing_in_future"); + assert!(!state.is_success()); + assert!(!state.is_terminal()); + assert!(matches!( + job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(1))) + .await, + Err(crate::Error::Timeout { .. }) + )); + assert_eq!(job.lifecycle_state(), Some(state)); + } + + #[tokio::test] + async fn operation_handles_report_the_selected_attempt_without_changing_id() { + let client = client_with_handler(|_| { + http::Response::builder() + .status(200) + .body( + serde_json::json!({"job_id":"operation-1", "attempt_job_id":"attempt-2", + "operation_id":"operation-1", "attempt":2, "retry_of":"operation-1", + "job_state":"IN_PROGRESS", "lifecycle_state":"queued"}) + .to_string(), + ) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "operation-1".into()))); + assert_eq!(job.status_typed().await.unwrap(), crate::JobState::Queued); + assert_eq!(job.id(), Some("operation-1")); + assert_eq!(job.job_id().as_deref(), Some("attempt-2")); + assert_eq!(job.operation_id().as_deref(), Some("operation-1")); + assert_eq!(job.attempt(), Some(2)); + } + + #[tokio::test] + async fn retry_preserves_the_typed_result_decoder_and_exact_predecessor() { + let client = client_with_handler(|request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + let response = if request.url().path() == "/v1/jobs/retry" { + assert_eq!(body["job_id"], "attempt-1"); + serde_json::json!({"job_id": "attempt-2"}) + } else { + assert_eq!(body["job_id"], "attempt-2"); + serde_json::json!({"job_id": "attempt-2", "operation_id": "attempt-1", "attempt": 2, + "retry_of": "attempt-1", "job_state": "DONE", "lifecycle_state": "succeeded", "result": 41}) + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let job = Job::::new_typed(Box::new(RemoteJob::new(client, "attempt-1".to_string()))) + .map(|value| value + 1); + let successor = job.retry().await.unwrap(); + assert_eq!(successor.id(), Some("attempt-2")); + assert_eq!(successor.wait().await.unwrap(), 42); + successor.refresh().await.unwrap(); + assert_eq!(successor.operation_id().as_deref(), Some("attempt-1")); + assert_eq!(successor.attempt(), Some(2)); + assert_eq!(successor.retry_of().as_deref(), Some("attempt-1")); + } + + #[tokio::test] + async fn local_and_remote_wait_timeouts_leave_jobs_waitable() { + let (sender, receiver) = tokio::sync::oneshot::channel(); + let local = Job::spawned(tokio::spawn(async move { + receiver.await.map_err(|error| crate::Error::Runtime { + message: error.to_string(), + }) + })); + assert!(matches!( + local + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(1))) + .await, + Err(crate::Error::Timeout { .. }) + )); + sender.send(7).unwrap(); + assert_eq!(local.wait().await.unwrap(), 7); + + let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let observed = done.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + http::Response::builder().status(200).body(serde_json::json!({ + "job_state": if observed.load(Ordering::SeqCst) { "DONE" } else { "IN_PROGRESS" }, "result": 7 + }).to_string()).unwrap() + }); + let remote = Job::::new_typed(Box::new(RemoteJob::new(client, "job-1".to_string()))); + assert!(matches!( + remote + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(1))) + .await, + Err(crate::Error::Timeout { .. }) + )); + done.store(true, Ordering::SeqCst); + assert_eq!(remote.wait().await.unwrap(), 7); + } + + #[tokio::test] + async fn stats_reads_report_verbatim_and_preserves_unavailable_without_waiting() { + let requests = Arc::new(AtomicUsize::new(0)); + let seen = requests.clone(); + let report = "Function job: finished\nWorker utilization: unavailable\n"; + let client = client_with_handler(move |request| { + assert_eq!(request.method(), reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/jobs/stats"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body, serde_json::json!({"job_id":"job-1"})); + let response = if seen.fetch_add(1, Ordering::SeqCst) == 0 { + serde_json::json!({"job_id":"job-1","profile":null,"report":null}) + } else { + serde_json::json!({"job_id":"job-1","profile":{"future_field":17},"report":report}) + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".to_string()))); + assert_eq!(job.stats().await.unwrap(), None); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert_eq!(job.stats().await.unwrap().as_deref(), Some(report)); + assert_eq!(requests.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn stats_rejects_malformed_or_unrelated_responses() { + for body in [ + "{", + r#"{"job_id":"job-1"}"#, + r#"{"job_id":"job-1","report":7}"#, + r#"{"job_id":"another-job","report":"a report"}"#, + ] { + let client = client_with_handler(move |_| { + http::Response::builder().status(200).body(body).unwrap() + }); + let error = RemoteJob::new(client, "job-1".to_string()) + .stats() + .await + .unwrap_err(); + assert!(matches!(error, crate::Error::Http { .. })); + assert!(error.to_string().contains("job statistics")); + } + } + + #[tokio::test] + async fn stats_preserves_not_found_errors() { + let client = client_with_handler(|_| { + http::Response::builder() + .status(404) + .body("job not found") + .unwrap() + }); + let error = RemoteJob::new(client, "missing".to_string()) + .stats() + .await + .unwrap_err(); + match error { + crate::Error::Http { status_code, .. } => { + assert_eq!(status_code, Some(reqwest::StatusCode::NOT_FOUND)); + } + other => panic!("expected HTTP 404, got {other:?}"), + } + } + struct FixtureRemoteJob(&'static str); #[async_trait] @@ -372,6 +992,29 @@ mod tests { ); } + #[tokio::test] + async fn reopened_job_preserves_its_description_and_decodes_the_terminal_result() { + let description: DescribeJobResponse = serde_json::from_str(REFRESH_JOB).unwrap(); + let job = Job::opened( + Box::new(FixtureRemoteJob(REFRESH_JOB)), + description.into_description(), + ); + let raw_result = job.result(); + let job = job.into_typed::().unwrap(); + + assert_eq!(job.job_type().as_deref(), Some("refresh_function_columns")); + assert_eq!(job.state().as_deref(), Some("finished")); + assert_eq!(job.creation_ms(), Some(1787270400001)); + assert_eq!(job.result(), raw_result); + assert_eq!(job.wait().await.unwrap().rows_assigned, 999_998_800); + assert_eq!(job.wait().await.unwrap().published_version, Some(919)); + + let missing = Job::new(Box::new(FixtureRemoteJob(MISSING_RESULT_JOB))) + .into_typed::() + .unwrap(); + assert!(missing.wait().await.is_err()); + } + /// Five in-progress polls then done: 0.2 + 0.4 + 0.8 + 1 + 1 s of waiting. /// Under the old 5 s cap the same job would have waited 10 s. #[tokio::test(start_paused = true)] @@ -511,4 +1154,72 @@ mod tests { assert_eq!(failure.retryable, Some(true)); assert_eq!(failure.sql_job_id.as_deref(), Some("job-1")); } + + #[tokio::test] + async fn wait_failure_uses_persisted_terminal_build() { + let server = serde_json::json!({ + "release": "1.13.0-beta.0", + "git_sha": "2a7874ecd589", + "build_date": "2026-11-12T22:45:43Z" + }); + for result in [ + serde_json::Value::Null, + serde_json::json!({"terminal_server": null}), + serde_json::json!({"terminal_server": {"release": "incomplete"}}), + serde_json::json!({"terminal_server": server}), + ] { + let known_build = result["terminal_server"] == server; + let response = serde_json::json!({ + "job_id": "job-1", + "job_state": "FAILED", + "failure": { + "phase": "function_refresh_attempt_failed", + "message": "ValueError: corrupt frame at frame_index=207", + "traceback": "Traceback: original user code", + "retryable": false + }, + "result": result + }); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + http::Response::builder() + .status(200) + .header( + "x-lancedb-server-build", + r#"{"release":"2.0.0","git_sha":"new-query-node"}"#, + ) + .body(response.to_string()) + .unwrap() + }); + let job = RemoteJob::new(client, "job-1".to_string()); + let description = job.describe().await.unwrap(); + assert_eq!( + description.result.as_ref(), + (!result.is_null()).then_some(&result) + ); + assert_eq!( + description.failure.unwrap().message.as_deref(), + Some("ValueError: corrupt frame at frame_index=207") + ); + let error = job.wait().await.err().expect("failed job"); + let mut expected = + "Job job-1 failed: ValueError: corrupt frame at frame_index=207".to_string(); + if known_build { + expected.push_str( + " [server: 1.13.0-beta.0 (git 2a7874ecd589, built 2026-11-12T22:45:43Z)]", + ); + } + expected.push_str(" (in function_refresh_attempt_failed)"); + assert_eq!(error.to_string(), expected); + let crate::error::Error::JobFailed { job_id, failure } = error else { + panic!("expected JobFailed"); + }; + assert_eq!(job_id.as_deref(), Some("job-1")); + assert_eq!( + failure.traceback.as_deref(), + Some("Traceback: original user code") + ); + assert_eq!(failure.retryable, Some(false)); + } + } } diff --git a/rust/lancedb/src/remote/job/profile.rs b/rust/lancedb/src/remote/job/profile.rs new file mode 100644 index 000000000..3142d3e34 --- /dev/null +++ b/rust/lancedb/src/remote/job/profile.rs @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +use super::RemoteJob; +use crate::error::{Error, Result}; +use crate::job::{ + FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, +}; +use crate::remote::client::{HttpSend, RequestResultExt}; + +impl RemoteJob { + async fn profile_request( + &self, + action: &str, + body: Value, + ) -> Result<(String, T)> { + let request = self + .client + .post(&format!("/v1/jobs/profile/{action}")) + .json(&body); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value = serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("invalid Function profile {action} response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + Ok((request_id, value)) + } + + pub(super) async fn capture_profile_inner( + &self, + worker_id: &str, + options: FunctionProfileOptions, + ) -> Result { + let duration = options.duration_seconds(); + let (request_id, profile): (_, FunctionProfile) = self + .profile_request( + "capture", + json!({ + "job_id": self.job_id, + "worker_id": worker_id, + "session_slot": options.session_slot, + "kind": options.kind, + "duration_seconds": duration, + }), + ) + .await?; + if !profile.valid_for(&self.job_id, None) + || profile.worker_id != worker_id + || profile.session_slot != options.session_slot + || profile.kind != options.kind + || profile.duration_seconds != duration + { + return Err(Error::Http { + source: "Function profile response does not match the requested capture".into(), + request_id, + status_code: None, + }); + } + Ok(profile) + } + + pub(super) async fn profile_status_inner(&self, profile_id: &str) -> Result { + let (request_id, profile): (_, FunctionProfile) = self + .profile_request( + "status", + json!({"job_id": self.job_id, "profile_id": profile_id}), + ) + .await?; + if !profile.valid_for(&self.job_id, Some(profile_id)) { + return Err(Error::Http { + source: "Function profile response does not match the requested identity".into(), + request_id, + status_code: None, + }); + } + Ok(profile) + } + + pub(super) async fn profile_artifact_inner(&self, profile_id: &str) -> Result { + let profile = self.profile_status_inner(profile_id).await?; + if profile.status != FunctionProfileStatus::Complete { + return Err(Error::Runtime { + message: format!( + "Function worker profile {profile_id} is not complete ({:?}): {}", + profile.status, + profile + .error + .as_deref() + .unwrap_or("artifact is not available") + ), + }); + } + let (request_id, artifact): (_, Value) = self + .profile_request( + "artifact", + json!({"job_id": self.job_id, "profile_id": profile_id}), + ) + .await?; + let valid = match profile.kind { + FunctionProfileKind::Cpu => { + artifact.get("$schema").and_then(Value::as_str) + == Some("https://www.speedscope.app/file-format-schema.json") + && artifact + .pointer("/shared/frames") + .is_some_and(Value::is_array) + && artifact.get("profiles").is_some_and(Value::is_array) + } + FunctionProfileKind::Memory => { + artifact.get("format").and_then(Value::as_str) == Some("lancedb.tracemalloc.v1") + && artifact.get("allocations").is_some_and(Value::is_array) + } + FunctionProfileKind::Gpu => { + artifact.get("format").and_then(Value::as_str) == Some("lancedb.cuda.v1") + && artifact.get("traceEvents").is_some_and(Value::is_array) + && artifact.get("truncated").is_some_and(Value::is_boolean) + } + }; + if !valid { + return Err(Error::Http { + source: "Function profile artifact does not match its declared format".into(), + request_id, + status_code: None, + }); + } + Ok(artifact) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::time::Duration; + + use serde_json::{Value, json}; + + use crate::error::Error; + use crate::job::{ + FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, + FunctionProfileWaitOptions, Job, + }; + use crate::remote::client::test_utils::client_with_handler; + use crate::remote::job::RemoteJob; + + fn metadata(kind: &str, status: &str) -> Value { + json!({ + "profile_id": "profile-1", "job_id": "job-1", "worker_id": "worker-1", + "execution_epoch": 3, "session_slot": 0, "kind": kind, + "duration_seconds": 2.0, "status": status, + "requested_at_millis": 1000, "deadline_at_millis": 46000, + "expires_at_millis": 3601000, "completed_at_millis": null, + "error": if status == "failed" { Some("gpu_unavailable") } else { None }, + "artifact_id": if status == "complete" { Some("profile-1") } else { None }, + }) + } + + #[tokio::test] + async fn capture_sends_selected_identity_and_kind_specific_defaults() { + for (kind, name, duration) in [ + (FunctionProfileKind::Cpu, "cpu", 10.0), + (FunctionProfileKind::Memory, "memory", 10.0), + (FunctionProfileKind::Gpu, "gpu", 5.0), + ] { + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/profile/capture"); + let body: Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!( + body, + json!({ + "job_id":"job-1", "worker_id":"worker-1", "kind":name, + "session_slot":2, "duration_seconds":duration, + }) + ); + let mut value = metadata(name, "pending"); + value["session_slot"] = json!(2); + value["duration_seconds"] = json!(duration); + http::Response::builder() + .status(202) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let profile = job + .capture_profile( + "worker-1", + FunctionProfileOptions::new(kind).session_slot(2), + ) + .await + .unwrap(); + assert_eq!(profile.kind, kind); + assert_eq!(profile.execution_epoch, 3); + assert_eq!(profile.status, FunctionProfileStatus::Pending); + assert_eq!(job.state(), None); + } + } + + #[tokio::test] + async fn invalid_capture_options_never_send_a_request() { + let client = + client_with_handler::(|_| panic!("invalid capture sent an HTTP request")); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + for (kind, duration) in [ + (FunctionProfileKind::Cpu, Duration::from_millis(999)), + (FunctionProfileKind::Memory, Duration::from_secs(31)), + (FunctionProfileKind::Gpu, Duration::from_millis(5001)), + ] { + assert!(matches!( + job.capture_profile( + "worker-1", + FunctionProfileOptions::new(kind).duration(duration) + ) + .await, + Err(Error::InvalidInput { .. }) + )); + } + assert!( + job.capture_profile("", FunctionProfileOptions::default()) + .await + .is_err() + ); + assert!( + job.capture_profile("é".repeat(129), FunctionProfileOptions::default()) + .await + .is_err() + ); + assert!(job.profile_status("").await.is_err()); + assert!(job.profile_artifact("p".repeat(257)).await.is_err()); + } + + #[tokio::test] + async fn response_identity_and_unsupported_servers_are_not_accepted_as_captures() { + for mutation in [ + "profile_id", + "job_id", + "worker_id", + "kind", + "session_slot", + "duration_seconds", + ] { + let client = client_with_handler(move |_| { + let mut value = metadata("gpu", "pending"); + value[mutation] = match mutation { + "profile_id" => json!(""), + "session_slot" => json!(1), + "duration_seconds" => json!(3), + "kind" => json!("cpu"), + _ => json!("other"), + }; + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert!(matches!( + job.capture_profile( + "worker-1", + FunctionProfileOptions::new(FunctionProfileKind::Gpu) + .duration(Duration::from_secs(2)) + ) + .await, + Err(Error::Http { .. }) + )); + } + let client = + client_with_handler(|_| http::Response::builder().status(200).body("{}").unwrap()); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert!(matches!( + job.profile_status("profile-1").await, + Err(Error::Http { .. }) + )); + } + + #[tokio::test(start_paused = true)] + async fn wait_timeout_is_resumable_and_does_not_cancel_or_refresh_the_job() { + let complete = Arc::new(AtomicBool::new(false)); + let status = complete.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/profile/status"); + let value = metadata( + "gpu", + if status.load(Ordering::SeqCst) { + "complete" + } else { + "pending" + }, + ); + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let error = job + .wait_for_profile( + "profile-1", + FunctionProfileWaitOptions::new().timeout(Duration::from_millis(50)), + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { .. })); + assert_eq!(job.state(), None); + complete.store(true, Ordering::SeqCst); + assert_eq!( + job.wait_for_profile("profile-1", FunctionProfileWaitOptions::new()) + .await + .unwrap() + .status, + FunctionProfileStatus::Complete + ); + } + + #[tokio::test(start_paused = true)] + async fn waiting_honors_poll_interval_and_rejects_execution_changes() { + let calls = Arc::new(AtomicUsize::new(0)); + let count = calls.clone(); + let client = client_with_handler(move |_| { + let next = count.fetch_add(1, Ordering::SeqCst); + let mut value = metadata("gpu", if next == 0 { "pending" } else { "complete" }); + if next > 0 { + value["execution_epoch"] = json!(4); + } + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let started = tokio::time::Instant::now(); + let error = job + .wait_for_profile( + "profile-1", + FunctionProfileWaitOptions::new().poll_interval(Duration::from_secs(5)), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("execution identity")); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert!(started.elapsed() >= Duration::from_secs(5)); + } + + #[tokio::test] + async fn failed_capture_keeps_its_reason_and_is_not_a_failed_refresh() { + let client = client_with_handler(|request| { + assert_eq!(request.url().path(), "/v1/jobs/profile/status"); + http::Response::builder() + .status(200) + .body(metadata("gpu", "failed").to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let profile = job.profile_status("profile-1").await.unwrap(); + assert_eq!(profile.status, FunctionProfileStatus::Failed); + assert_eq!(profile.error.as_deref(), Some("gpu_unavailable")); + let error = job + .wait_for_profile("profile-1", FunctionProfileWaitOptions::new()) + .await + .unwrap_err(); + assert!(matches!(error, Error::Runtime { .. })); + assert!(error.to_string().contains("gpu_unavailable")); + assert_eq!(job.state(), None); + } + + #[tokio::test] + async fn artifacts_preserve_all_supported_formats_and_truncation_after_refresh() { + for (kind, artifact) in [ + ( + "cpu", + json!({"$schema":"https://www.speedscope.app/file-format-schema.json","shared":{"frames":[{"name":"work"}]},"profiles":[],"future_field":7}), + ), + ( + "memory", + json!({"format":"lancedb.tracemalloc.v1","allocations":[{"size_bytes":4096,"frames":[]}],"truncated":false}), + ), + ( + "gpu", + json!({"format":"lancedb.cuda.v1","traceEvents":[{"cat":"kernel","name":"compute","ph":"X","ts":10,"dur":2}],"truncated":true}), + ), + ] { + let output = artifact.clone(); + let client = client_with_handler(move |request| { + let body: Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body, json!({"job_id":"job-1","profile_id":"profile-1"})); + let response = match request.url().path() { + "/v1/jobs/profile/status" => metadata(kind, "complete"), + "/v1/jobs/profile/artifact" => output.clone(), + other => panic!("retrieval must not describe or restart refresh: {other}"), + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert_eq!(job.profile_artifact("profile-1").await.unwrap(), artifact); + } + } + + #[tokio::test] + async fn permission_missing_and_expired_errors_are_preserved_without_retry() { + for code in [403, 404, 500] { + for operation in ["capture", "status", "artifact"] { + let calls = Arc::new(AtomicUsize::new(0)); + let seen = calls.clone(); + let client = client_with_handler(move |request| { + let path = request.url().path(); + if operation == "artifact" && path.ends_with("/status") { + return http::Response::builder() + .status(200) + .body(metadata("gpu", "complete").to_string()) + .unwrap(); + } + assert_eq!(path, format!("/v1/jobs/profile/{operation}")); + seen.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(code) + .body("profile is unavailable".to_owned()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + let error = match operation { + "capture" => job + .capture_profile("worker-1", FunctionProfileOptions::default()) + .await + .unwrap_err(), + "status" => job.profile_status("profile-1").await.unwrap_err(), + _ => job.profile_artifact("profile-1").await.unwrap_err(), + }; + assert!( + matches!(error, Error::Http { status_code: Some(status), .. } if status.as_u16() == code) + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + } + } + + #[tokio::test] + async fn unrelated_or_incomplete_artifacts_are_not_exported_as_profiles() { + let client = client_with_handler(|request| { + let value = if request.url().path().ends_with("/status") { + metadata("gpu", "complete") + } else { + json!({"traceEvents":[]}) + }; + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert!(matches!( + job.profile_artifact("profile-1").await, + Err(Error::Http { .. }) + )); + let client = client_with_handler(|request| { + assert!(request.url().path().ends_with("/status")); + http::Response::builder() + .status(200) + .body(metadata("gpu", "capturing").to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert!(matches!( + job.profile_artifact("profile-1").await, + Err(Error::Runtime { .. }) + )); + } +} diff --git a/rust/lancedb/src/remote/retry.rs b/rust/lancedb/src/remote/retry.rs index 51c9b2126..c0ef2bd11 100644 --- a/rust/lancedb/src/remote/retry.rs +++ b/rust/lancedb/src/remote/retry.rs @@ -63,7 +63,7 @@ impl<'a> RetryCounter<'a> { /// Increment the appropriate failure counter based on the error type. /// /// For `Error::Http` whose source is a connect error, increments - /// `connect_failures`. For read errors (`is_body` or `is_decode`), + /// `connect_failures`. For read errors (`is_timeout`, `is_body` or `is_decode`), /// increments `read_failures`. For all other errors, increments /// `request_failures`. Calls `check_out_of_retries` to enforce global limits. pub fn increment_from_error(&mut self, source: crate::Error) -> crate::Result<()> { @@ -74,7 +74,7 @@ impl<'a> RetryCounter<'a> { if reqwest_err.is_some_and(|e| e.is_connect()) { self.connect_failures += 1; - } else if reqwest_err.is_some_and(|e| e.is_body() || e.is_decode()) { + } else if reqwest_err.is_some_and(|e| e.is_timeout() || e.is_body() || e.is_decode()) { self.read_failures += 1; } else { self.request_failures += 1; @@ -187,6 +187,37 @@ mod tests { )); } + #[tokio::test] + async fn test_increment_from_error_read_timeout() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let _ = tokio::io::copy(&mut socket, &mut tokio::io::sink()).await; + }); + let err = reqwest::Client::builder() + .read_timeout(Duration::from_millis(100)) + .build() + .unwrap() + .get(format!("http://{address}/")) + .send() + .await + .unwrap_err(); + assert!(err.is_timeout() && !err.is_connect()); + let config = test_config(); + let mut counter = RetryCounter::new(&config, "part-1".into()); + counter + .increment_from_error(Error::Http { + request_id: "part-1".into(), + status_code: None, + source: Box::new(err), + }) + .unwrap(); + assert_eq!(counter.read_failures, 1); + assert_eq!(counter.request_failures, 0); + server.abort(); + } + #[test] fn test_increment_from_error_request() { let config = test_config(); diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 94d8bf063..fda450e2c 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -12,18 +12,18 @@ use arrow_array::RecordBatch; use arrow_flight::decode::FlightRecordBatchStream; use arrow_flight::error::FlightError; use arrow_flight::flight_service_client::FlightServiceClient; -#[cfg(test)] use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt}; use arrow_flight::{ Action, CancelFlightInfoRequest, CancelFlightInfoResult, CancelStatus, FlightClient, FlightDescriptor, FlightEndpoint, FlightInfo, PollInfo, }; use arrow_schema::{Schema, SchemaRef}; -use futures::TryStreamExt; +use futures::{StreamExt, TryStreamExt}; use http::header::{HeaderMap, HeaderName, HeaderValue}; use prost::Message; use serde::{Serialize, de::DeserializeOwned}; use tokio::sync::{Mutex, Notify, OnceCell, mpsc}; +use tonic::Request; use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity}; use uuid::Uuid; @@ -38,18 +38,25 @@ use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; mod function; pub(super) mod materialized_view; mod objects; +pub(super) use objects::description; +pub(super) mod receipt; mod secret; +pub(super) use secret::SecretWriteOperation; mod stream; mod view; +const PREWARM_AZURE_HINT_CAPABILITY: &str = "lancedb.prewarm.azure_storage_account_name"; + use stream::{StreamingQuery, StreamingQueryHandle, Submission}; const DEFAULT_SQL_PORT: u16 = 10025; const DEFAULT_SQL_TLS_PORT: u16 = 10026; const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(120); const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(300); +const AUTOMATIC_CANCELLATION_TIMEOUT: Duration = Duration::from_secs(5); const STATUS_POLL_TIMEOUT: Duration = Duration::from_secs(1); const MIN_POLL_INTERVAL: Duration = Duration::from_millis(50); +const MAX_SQL_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 60 * 60); const MAX_SQL_MESSAGE_SIZE: usize = 1024 * 1024 * 1024; const SQL_JOB_ID_METADATA_KEY: &str = "x-lancedb-sql-job-id"; const TERMINAL_QUERY_RETENTION: Duration = Duration::from_secs(300); @@ -66,6 +73,7 @@ pub(super) struct SubmittedQuery { pub(super) materialized_view_job_handle_supported: bool, } +#[derive(Clone)] struct SqlClientInner { database: String, database_prefix: Option, @@ -74,6 +82,8 @@ struct SqlClientInner { sql_host_override: Option, client_config: ClientConfig, client: Arc>, + deadline: Option, + cancel_on_drop: bool, } struct SqlConnection { @@ -87,6 +97,12 @@ struct ResultEndpointStream { stream: FlightRecordBatchStream, request_id: String, read_timeout: Duration, + job_id: Option, +} + +struct PollResult { + info: PollInfo, + job_id: Option, } struct PreparedSqlResult { @@ -204,11 +220,62 @@ impl SqlClient { sql_host_override, client_config, client: Arc::new(OnceCell::new()), + deadline: None, + cancel_on_drop: false, }), queries: Arc::new(QueryRegistry::new()), } } + /// Unknown headers are otherwise silently ignored by older SQL servers. + /// Probe only when a source-account hint is present, before submitting work. + pub(super) async fn execute_prewarm(&self, request: ExecuteQueryRequest) -> Result { + with_overall_timeout( + self.inner.overall_timeout()?, + "prewarm submission", + async { + validate_namespace_path(&request.default_namespace_path)?; + let request_id = Uuid::new_v4().to_string(); + let headers = self + .inner + .headers(&request.default_namespace_path, &request_id) + .await?; + if headers.contains_key("x-azure-storage-account-name") { + let connection = self.inner.connection(&request_id).await?; + let mut client = client_with_headers(connection.client.clone(), &headers)?; + let command = CommandStatementQuery { + query: request.query.clone(), + transaction_id: None, + }; + let descriptor = FlightDescriptor::new_cmd(command.as_any().encode_to_vec()); + let read_timeout = resolve_timeout( + self.inner.client_config.timeout_config.read_timeout, + "LANCE_CLIENT_READ_TIMEOUT", Some(DEFAULT_READ_TIMEOUT), + )?.unwrap(); + let info = tokio::time::timeout(read_timeout, client.get_flight_info(descriptor)) + .await.map_err(|_| Error::Runtime { message: format!("SQL PREWARM capability check timed out (request_id={request_id})") })? + .map_err(|error| sql_flight_error(&request_id, &error))?; + let supported = info.try_decode_schema().ok().is_some_and(|schema| { + schema + .metadata() + .get(PREWARM_AZURE_HINT_CAPABILITY) + .map(String::as_str) + == Some("true") + }); + if !supported { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM server cannot acknowledge the Azure storage-account hint (request_id={request_id}); upgrade the server. No execution request was sent." + ), + }); + } + } + self.execute(request).await + }, + ) + .await + } + pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result { Ok(self .execute_with_materialized_view_job_handle(request, false) @@ -221,42 +288,75 @@ impl SqlClient { request: ExecuteQueryRequest, materialized_view_job_handle: bool, ) -> Result { - let timeout = self.inner.overall_timeout()?; + let mut client = self.inner.as_ref().clone(); + client.deadline = request + .options + .timeout + .map(|timeout| { + if timeout > MAX_SQL_TIMEOUT { + return Err(Error::InvalidInput { + message: "SQL query timeout exceeds the gRPC limit".to_string(), + }); + } + tokio::time::Instant::now() + .checked_add(timeout) + .ok_or_else(|| Error::InvalidInput { + message: "SQL query timeout is too large".to_string(), + }) + }) + .transpose()?; + client.cancel_on_drop = request.options.cancel_on_drop; + if let Some(read_timeout) = request.options.read_timeout { + client.client_config.timeout_config.read_timeout = Some(read_timeout); + } + let client = Arc::new(client); + let timeout = client.execution_timeout()?; with_overall_timeout(timeout, "SQL query submission", async { validate_namespace_path(&request.default_namespace_path)?; let query_id = Uuid::now_v7(); let opened = StreamingQuery::open( - self.inner.clone(), + client.clone(), &request.query, request.parameters, &request.default_namespace_path, materialized_view_job_handle, ) .await?; - let query = match opened.submission { + let stream::OpenedSubmission { + submission, + materialized_view_job_handle_supported, + job_id, + } = opened; + let query = match submission { Submission::Stream(response) => { - let query = - Arc::new(StreamingQuery::new(query_id, self.inner.clone(), response)); + let query = Arc::new(StreamingQuery::new( + query_id, + client.clone(), + response, + job_id.clone(), + )); self.queries .insert(query_id, RegisteredQuery::Streamed(query.clone())); + query.start_deadline(); Query::new(Arc::new(StreamingQueryHandle::new(query))) } Submission::Deferred(poll_info) => { let query = Arc::new(RemoteQuery::new( query_id, - self.inner.clone(), + client.clone(), request.default_namespace_path, poll_info, + job_id, )?); self.queries .insert(query_id, RegisteredQuery::Polled(query.clone())); + query.start_deadline(); Query::new(Arc::new(RemoteQueryHandle::new(query))) } }; Ok(SubmittedQuery { query, - materialized_view_job_handle_supported: opened - .materialized_view_job_handle_supported, + materialized_view_job_handle_supported, }) }) .await @@ -283,6 +383,7 @@ impl SqlClient { self.inner.clone(), default_namespace_path.to_vec(), poll_info, + None, )?); self.queries .insert(query_id, RegisteredQuery::Polled(query.clone())); @@ -307,6 +408,7 @@ impl SqlClient { query: statement, default_namespace_path: namespace, parameters: None, + options: Default::default(), }) .await?, ); @@ -349,6 +451,21 @@ impl SqlClient { } impl SqlClientInner { + fn execution_timeout(&self) -> Result> { + match self.deadline { + Some(deadline) => Ok(Some( + deadline.saturating_duration_since(tokio::time::Instant::now()), + )), + None => self.overall_timeout(), + } + } + + fn set_execution_timeout(&self, request: &mut Request) { + if let Some(deadline) = self.deadline { + request.set_timeout(deadline.saturating_duration_since(tokio::time::Instant::now())); + } + } + fn overall_timeout(&self) -> Result> { resolve_timeout( self.client_config.timeout_config.timeout, @@ -383,16 +500,29 @@ impl SqlClientInner { &self, descriptor: FlightDescriptor, default_namespace_path: &[String], - ) -> Result> { + ) -> Result> { let request_id = uuid::Uuid::new_v4().to_string(); - let mut client = self - .client_with_headers(default_namespace_path, &request_id) - .await - .map_err(|err| sql_error(&request_id, err))?; - match tokio::time::timeout(STATUS_POLL_TIMEOUT, client.poll_flight_info(descriptor)).await { - Ok(result) => result - .map(Some) - .map_err(|err| sql_flight_error(&request_id, &err)), + let connection = self.connection(&request_id).await?; + let headers = self.headers(default_namespace_path, &request_id).await?; + let metadata = client_with_headers(connection.client.clone(), &headers)? + .metadata() + .clone(); + let mut request = Request::new(descriptor); + *request.metadata_mut() = metadata; + match tokio::time::timeout( + STATUS_POLL_TIMEOUT, + connection.client.clone().poll_flight_info(request), + ) + .await + { + Ok(Ok(response)) => { + let job_id = sql_job_id_from_metadata(response.metadata()); + Ok(Some(PollResult { + info: response.into_inner(), + job_id, + })) + } + Ok(Err(status)) => Err(sql_status_error(&request_id, &status)), Err(_) => Ok(None), } } @@ -401,7 +531,7 @@ impl SqlClientInner { &self, descriptor: FlightDescriptor, default_namespace_path: &[String], - ) -> Result { + ) -> Result { let read_timeout = resolve_timeout( self.client_config.timeout_config.read_timeout, "LANCE_CLIENT_READ_TIMEOUT", @@ -413,12 +543,18 @@ impl SqlClientInner { loop { let started = Instant::now(); let request_id = uuid::Uuid::new_v4().to_string(); - let mut client = self - .client_with_headers(default_namespace_path, &request_id) - .await?; - let result = - tokio::time::timeout(read_timeout, client.poll_flight_info(descriptor.clone())) - .await; + let connection = self.connection(&request_id).await?; + let headers = self.headers(default_namespace_path, &request_id).await?; + let metadata = client_with_headers(connection.client.clone(), &headers)? + .metadata() + .clone(); + let mut request = Request::new(descriptor.clone()); + *request.metadata_mut() = metadata; + let result = tokio::time::timeout( + read_timeout, + connection.client.clone().poll_flight_info(request), + ) + .await; let poll_info = match result { Err(_) if retry_count < retry_config.read_retries => { retry_count += 1; @@ -426,7 +562,7 @@ impl SqlClientInner { continue; } Err(_) => return Err(sql_error(&request_id, "SQL query poll timed out")), - Ok(Err(FlightError::Tonic(status))) + Ok(Err(status)) if matches!( status.code(), tonic::Code::DeadlineExceeded | tonic::Code::Unavailable @@ -436,8 +572,14 @@ impl SqlClientInner { tokio::time::sleep(poll_retry_delay(&retry_config, retry_count)).await; continue; } - Ok(Err(error)) => return Err(sql_flight_error(&request_id, &error)), - Ok(Ok(poll_info)) => poll_info, + Ok(Err(status)) => return Err(sql_status_error(&request_id, &status)), + Ok(Ok(response)) => { + let job_id = sql_job_id_from_metadata(response.metadata()); + PollResult { + info: response.into_inner(), + job_id, + } + } }; if let Some(delay) = MIN_POLL_INTERVAL.checked_sub(started.elapsed()) { tokio::time::sleep(delay).await; @@ -461,17 +603,28 @@ impl SqlClientInner { let ticket = endpoint.ticket.ok_or_else(|| { sql_error(&request_id, "SQL result endpoint did not include a ticket") })?; - let mut endpoint_client = self - .client_with_headers(default_namespace_path, &request_id) - .await?; - let stream = tokio::time::timeout(read_timeout, endpoint_client.do_get(ticket)) - .await - .map_err(|_| sql_error(&request_id, "SQL result fetch timed out"))? - .map_err(|err| sql_flight_error(&request_id, &err))?; + let connection = self.connection(&request_id).await?; + let headers = self.headers(default_namespace_path, &request_id).await?; + let metadata = client_with_headers(connection.client.clone(), &headers)? + .metadata() + .clone(); + let mut request = Request::new(ticket); + *request.metadata_mut() = metadata; + self.set_execution_timeout(&mut request); + let response = + tokio::time::timeout(read_timeout, connection.client.clone().do_get(request)) + .await + .map_err(|_| sql_error(&request_id, "SQL result fetch timed out"))? + .map_err(|status| sql_status_error(&request_id, &status))?; + let job_id = sql_job_id_from_metadata(response.metadata()); + let stream = response + .into_inner() + .map_err(|status| FlightError::Tonic(Box::new(status))); Ok(ResultEndpointStream { - stream, + stream: FlightRecordBatchStream::new_from_flight_data(stream), request_id, read_timeout, + job_id, }) } @@ -547,6 +700,7 @@ impl SqlClientInner { Ok(CancelOutcome::Status(status)) } + #[cfg(test)] async fn client_with_headers( &self, default_namespace_path: &[String], @@ -684,6 +838,7 @@ impl QueryRegistry { struct RemoteQuery { id: Uuid, + job_id: StdMutex>, client: Arc, default_namespace_path: Vec, state: Mutex, @@ -696,6 +851,10 @@ struct RemoteQuery { last_accessed: StdMutex, lifecycle: StdMutex, cancel_request_uncertain: Arc, + failure: StdMutex>, + cleanup_started: AtomicBool, + runtime: tokio::runtime::Handle, + deadline_task: StdMutex>, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -713,6 +872,7 @@ impl RemoteQuery { client: Arc, default_namespace_path: Vec, poll_info: PollInfo, + job_id: Option, ) -> Result { let expires_at = query_expiration(&poll_info)?; let terminal_at = OnceLock::new(); @@ -724,6 +884,7 @@ impl RemoteQuery { }; Ok(Self { id, + job_id: StdMutex::new(job_id.filter(|job_id| !job_id.is_empty())), client, default_namespace_path, state: Mutex::new(poll_info), @@ -736,9 +897,75 @@ impl RemoteQuery { last_accessed: StdMutex::new(Instant::now()), lifecycle: StdMutex::new(lifecycle), cancel_request_uncertain: Arc::new(AtomicBool::new(false)), + failure: StdMutex::new(None), + cleanup_started: AtomicBool::new(false), + runtime: tokio::runtime::Handle::current(), + deadline_task: StdMutex::new(None), }) } + fn start_deadline(self: &Arc) { + let Some(deadline) = self.client.deadline else { + return; + }; + let query = Arc::downgrade(self); + let task = self.runtime.spawn(async move { + tokio::time::sleep_until(deadline).await; + if let Some(query) = query.upgrade() + && !matches!( + query.lifecycle(), + QueryLifecycle::Completed | QueryLifecycle::Cancelled + ) + { + query.fail(&sql_result_timeout()); + } + }); + *self.deadline_task.lock().unwrap() = Some(task.abort_handle()); + } + + fn stop_deadline(&self) { + if let Some(task) = self.deadline_task.lock().unwrap().take() { + task.abort(); + } + } + + fn fail(self: &Arc, error: &Error) { + let lifecycle = self.lifecycle.lock().unwrap(); + if matches!( + *lifecycle, + QueryLifecycle::Completed | QueryLifecycle::Cancelled | QueryLifecycle::Cancelling + ) { + return; + } + self.failure + .lock() + .unwrap() + .get_or_insert_with(|| match error { + Error::Runtime { message } => message.clone(), + other => other.to_string(), + }); + drop(lifecycle); + self.stop_deadline(); + self.mark_terminal(); + self.cancelled.notify_waiters(); + self.cancel_in_background(); + } + + fn cancel_in_background(self: &Arc) { + if matches!( + self.lifecycle(), + QueryLifecycle::Completed | QueryLifecycle::Cancelled + ) || self.cleanup_started.swap(true, Ordering::SeqCst) + { + return; + } + let query = self.clone(); + self.runtime.spawn(async move { + let _ = + tokio::time::timeout(AUTOMATIC_CANCELLATION_TIMEOUT, query.cancel_inner()).await; + }); + } + fn registry_expired(&self, abandoned: bool) -> bool { if let Some(finished) = self.terminal_at.get() { return finished.elapsed() >= TERMINAL_QUERY_RETENTION; @@ -775,6 +1002,7 @@ impl RemoteQuery { } *lifecycle = QueryLifecycle::Cancelled; drop(lifecycle); + self.stop_deadline(); self.mark_terminal(); self.cancelled.notify_waiters(); self.state_changed.notify_waiters(); @@ -809,13 +1037,17 @@ impl RemoteQuery { fn mark_result_completed(&self) -> Result<()> { let mut lifecycle = self.lifecycle.lock().unwrap(); - if matches!( - *lifecycle, - QueryLifecycle::Cancelling | QueryLifecycle::Cancelled - ) { + if self.failure.lock().unwrap().is_some() + || matches!( + *lifecycle, + QueryLifecycle::Cancelling | QueryLifecycle::Cancelled + ) + { return Err(self.cancelled_error()); } *lifecycle = QueryLifecycle::Completed; + drop(lifecycle); + self.stop_deadline(); Ok(()) } @@ -824,13 +1056,20 @@ impl RemoteQuery { } fn is_cancellation_requested(&self) -> bool { - matches!( - self.lifecycle(), - QueryLifecycle::Cancelling | QueryLifecycle::Cancelled - ) + let failed = self.failure.lock().unwrap().is_some(); + failed + || matches!( + self.lifecycle(), + QueryLifecycle::Cancelling | QueryLifecycle::Cancelled + ) } fn cancelled_error(&self) -> Error { + if let Some(message) = self.failure.lock().unwrap().as_ref() { + return Error::Runtime { + message: message.clone(), + }; + } Error::JobCancelled { job_id: Some(self.id.to_string()), } @@ -850,6 +1089,44 @@ impl RemoteQuery { *self.last_accessed.lock().unwrap() = Instant::now(); } + fn job_id(&self) -> Option { + self.job_id.lock().unwrap().clone() + } + + fn observe_job_id(&self, job_id: Option<&str>) -> Result<()> { + let Some(job_id) = job_id.filter(|job_id| !job_id.is_empty()) else { + return Ok(()); + }; + let mut current = self.job_id.lock().unwrap(); + match current.as_deref() { + None => *current = Some(job_id.to_string()), + Some(existing) if existing == job_id => {} + Some(existing) => { + return Err(Error::Runtime { + message: format!( + "SQL query changed durable job identity from {existing} to {job_id}" + ), + }); + } + } + Ok(()) + } + + fn observe_error_job_id(&self, error: &Error) -> Result<()> { + self.observe_job_id( + error + .remote_error_metadata() + .and_then(|metadata| metadata.job_id.as_deref()), + ) + } + + fn record_error_job_id(&self, result: Result) -> Result { + if let Err(error) = &result { + self.observe_error_job_id(error)?; + } + result + } + async fn poll_next_state(&self, descriptor: FlightDescriptor) -> Result { self.touch(); if self.is_cancellation_requested() { @@ -874,10 +1151,11 @@ impl RemoteQuery { Err(_) if self.is_cancellation_requested() => { return Err(self.cancelled_error()); } - result => result?, + result => self.record_error_job_id(result)?, }, }; - self.update_state(&descriptor, updated).await + self.observe_job_id(updated.job_id.as_deref())?; + self.update_state(&descriptor, updated.info).await } async fn prepare_result(self: &Arc) -> Result { @@ -894,8 +1172,9 @@ impl RemoteQuery { result = self.client.open_result_endpoint( endpoint, &self.default_namespace_path, - ) => result?, + ) => self.record_error_job_id(result)?, }; + self.observe_job_id(endpoint_stream.job_id.as_deref())?; let buffered_batch = tokio::select! { biased; _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), @@ -908,6 +1187,7 @@ impl RemoteQuery { .ok_or_else(|| Error::Runtime { message: "SQL result endpoint did not include a schema".to_string(), })?; + self.observe_job_id(sql_job_id_from_schema(&schema).as_deref())?; return Ok(PreparedSqlResult { schema, next_endpoint: 1, @@ -925,6 +1205,7 @@ impl RemoteQuery { .map_err(|err| sql_error(&request_id, err))?, ) }; + self.observe_job_id(sql_job_id_from_schema(&schema).as_deref())?; return Ok(PreparedSqlResult { schema, next_endpoint: 0, @@ -1001,7 +1282,7 @@ impl RemoteQuery { result = self.client.open_result_endpoint( endpoint, &self.default_namespace_path, - ) => result?, + ) => self.record_error_job_id(result)?, }); continue; } @@ -1065,26 +1346,27 @@ impl RemoteQuery { async fn describe_inner(&self) -> Result { self.touch(); + if self.failure.lock().unwrap().is_some() { + return Err(self.cancelled_error()); + } if self.is_cancellation_requested() { let state = self.state.lock().await.clone(); - return query_description(self.id, &state, self.lifecycle()); + return query_description(self.id, self.job_id(), &state, self.lifecycle()); } let state = self.state.lock().await.clone(); let state = if let Some(descriptor) = state.flight_descriptor.clone() { let poll_guard = tokio::select! { biased; - _ = self.wait_for_cancellation() => return query_description( - self.id, - &state, - self.lifecycle(), - ), + _ = self.wait_for_cancellation() => { + return query_description(self.id, self.job_id(), &state, self.lifecycle()) + } poll_guard = tokio::time::timeout( STATUS_POLL_TIMEOUT, self.poll_gate.lock(), ) => poll_guard, }; let Ok(_poll_guard) = poll_guard else { - return query_description(self.id, &state, self.lifecycle()); + return query_description(self.id, self.job_id(), &state, self.lifecycle()); }; let latest = self.state.lock().await.clone(); if latest.flight_descriptor.as_ref() != Some(&descriptor) { @@ -1092,25 +1374,28 @@ impl RemoteQuery { } else { let updated = tokio::select! { biased; - _ = self.wait_for_cancellation() => return query_description( - self.id, - &latest, - self.lifecycle(), - ), + _ = self.wait_for_cancellation() => { + return query_description(self.id, self.job_id(), &latest, self.lifecycle()) + } result = self.client.poll_status( descriptor.clone(), &self.default_namespace_path, ) => match result { - Err(_) if self.is_cancellation_requested() => return query_description( - self.id, - &latest, - self.lifecycle(), - ), - result => result?, + Err(error) if self.is_cancellation_requested() => { + self.observe_error_job_id(&error)?; + return query_description( + self.id, + self.job_id(), + &latest, + self.lifecycle(), + ); + } + result => self.record_error_job_id(result)?, }, }; if let Some(updated) = updated { - self.update_state(&descriptor, updated).await? + self.observe_job_id(updated.job_id.as_deref())?; + self.update_state(&descriptor, updated.info).await? } else { latest } @@ -1118,7 +1403,7 @@ impl RemoteQuery { } else { state }; - query_description(self.id, &state, self.lifecycle()) + query_description(self.id, self.job_id(), &state, self.lifecycle()) } async fn cancel(&self) -> Result<()> { @@ -1214,11 +1499,15 @@ impl RemoteQuery { if self.state.lock().await.flight_descriptor.as_ref() != Some(&descriptor) { continue; } - let updated = self.client.poll_continuation( + let updated = self.record_error_job_id( + self.client.poll_continuation( descriptor.clone(), &self.default_namespace_path, - ).await?; - self.update_state(&descriptor, updated).await?; + ) + .await, + )?; + self.observe_job_id(updated.job_id.as_deref())?; + self.update_state(&descriptor, updated.info).await?; } _ = notified => {} } @@ -1226,6 +1515,14 @@ impl RemoteQuery { } } +struct CancelQueryOnDrop(Arc); + +impl Drop for CancelQueryOnDrop { + fn drop(&mut self) { + self.0.cancel_in_background(); + } +} + struct RemoteQueryHandle { query: Arc, result_started: AtomicBool, @@ -1240,6 +1537,14 @@ impl RemoteQueryHandle { } } +impl Drop for RemoteQueryHandle { + fn drop(&mut self) { + if self.query.client.cancel_on_drop && !self.result_started.load(Ordering::SeqCst) { + self.query.cancel_in_background(); + } + } +} + #[async_trait::async_trait] impl QueryHandle for RemoteQueryHandle { fn id(&self) -> Uuid { @@ -1247,12 +1552,19 @@ impl QueryHandle for RemoteQueryHandle { self.query.id } + fn job_id(&self) -> Option { + self.query.job_id() + } + async fn describe(&self) -> Result { self.query.describe().await } async fn reader(&self) -> Result { - let timeout = self.query.client.overall_timeout()?; + let timeout = self.query.client.execution_timeout()?; + if self.query.failure.lock().unwrap().is_some() { + return Err(self.query.cancelled_error()); + } if self .result_started .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) @@ -1263,9 +1575,22 @@ impl QueryHandle for RemoteQueryHandle { }); } let result_start = ResultStartGuard::new(&self.result_started); + let cancel_on_drop = self + .query + .client + .cancel_on_drop + .then(|| CancelQueryOnDrop(self.query.clone())); let started = Instant::now(); let prepared = - with_overall_timeout(timeout, "SQL query result", self.query.prepare_result()).await?; + match with_overall_timeout(timeout, "SQL query result", self.query.prepare_result()) + .await + { + Ok(prepared) => prepared, + Err(error) => { + self.query.fail(&error); + return Err(error); + } + }; let remaining_timeout = timeout.map(|timeout| timeout.saturating_sub(started.elapsed())); let schema = prepared.schema.clone(); let (sender, receiver) = mpsc::channel(2); @@ -1275,18 +1600,21 @@ impl QueryHandle for RemoteQueryHandle { let result = with_overall_timeout( remaining_timeout, "SQL query result", - query.run_result_stream(prepared, sender), + query.clone().run_result_stream(prepared, sender), ) .await; if let Err(error) = result { + query.fail(&error); let _ = error_sender.send(Err(error)).await; } }); - let stream = futures::stream::unfold(receiver, |mut receiver| async move { - receiver.recv().await.map(|item| (item, receiver)) - }); result_start.commit(); - Ok(Box::pin(SimpleRecordBatchStream::new(stream, schema))) + let stream = + sql_result_stream(receiver, schema, self.query.client.deadline, cancel_on_drop); + Ok(match self.job_id() { + Some(job_id) => attach_sql_job_id(stream, &job_id), + None => stream, + }) } async fn cancel(&self) -> Result<()> { @@ -1294,14 +1622,43 @@ impl QueryHandle for RemoteQueryHandle { } } +fn sql_result_timeout() -> Error { + Error::Runtime { + message: "SQL query result timed out".to_string(), + } +} + +fn sql_result_stream( + receiver: mpsc::Receiver>, + schema: SchemaRef, + deadline: Option, + guard: G, +) -> SendableRecordBatchStream { + let stream = futures::stream::unfold(Some((receiver, guard)), move |state| async move { + let (mut receiver, guard) = state?; + let item = match deadline { + Some(deadline) => tokio::select! { + biased; + _ = tokio::time::sleep_until(deadline) => return Some((Err(sql_result_timeout()), None)), + item = receiver.recv() => item, + }, + None => receiver.recv().await, + }; + item.map(|item| (item, Some((receiver, guard)))) + }); + Box::pin(SimpleRecordBatchStream::new(stream, schema)) +} + fn query_description( id: Uuid, + job_id: Option, poll_info: &PollInfo, lifecycle: QueryLifecycle, ) -> Result { let expires_at = query_expiration(poll_info)?; Ok(QueryDescription { id, + job_id, status: match lifecycle { QueryLifecycle::Cancelling => QueryStatus::Cancelling, QueryLifecycle::Cancelled => QueryStatus::Cancelled, @@ -1317,6 +1674,36 @@ fn query_description( }) } +fn sql_job_id_from_metadata(metadata: &tonic::metadata::MetadataMap) -> Option { + metadata + .get(SQL_JOB_ID_METADATA_KEY) + .and_then(|value| value.to_str().ok()) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +fn sql_job_id_from_schema(schema: &Schema) -> Option { + schema + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .filter(|value| !value.is_empty()) + .cloned() +} + +pub(super) fn attach_sql_job_id( + stream: SendableRecordBatchStream, + job_id: &str, +) -> SendableRecordBatchStream { + let mut metadata = stream.schema().metadata().clone(); + metadata.insert(SQL_JOB_ID_METADATA_KEY.to_string(), job_id.to_string()); + let schema = Arc::new(stream.schema().as_ref().clone().with_metadata(metadata)); + let batch_schema = schema.clone(); + let stream = stream.map(move |batch| { + batch.and_then(|batch| batch.with_schema(batch_schema.clone()).map_err(Error::from)) + }); + Box::pin(SimpleRecordBatchStream::new(stream, schema)) +} + fn query_expiration(poll_info: &PollInfo) -> Result>> { poll_info .expiration_time @@ -1652,13 +2039,25 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .map(str::to_owned) }; let metadata = crate::error::RemoteErrorMetadata { + server: status + .metadata() + .get_bin("x-lancedb-server-build-bin") + .and_then(|value| value.to_bytes().ok()) + .and_then(|value| serde_json::from_slice(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header(SQL_JOB_ID_METADATA_KEY), job_request_id: header("x-job-request-id"), + resource: header("x-lancedb-resource") + .as_deref() + .and_then(crate::error::parse_flight_resource_identity), }; let sql_job_id = metadata.job_id.clone(); + let mut message = status.message().to_owned(); + if let Some(server) = &metadata.server { + message.push_str(&format!(" [server: {server}]")); + } let error = Error::Sql { - message: status.message().into(), + message: message.clone(), request_id: request_id.into(), grpc_code: status.code() as i32, metadata: Box::new(metadata), @@ -1666,13 +2065,14 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro if let Some(sql_job_id) = sql_job_id { return Error::JobFailed { job_id: Some(sql_job_id.clone()), - failure: JobFailure { + failure: Box::new(JobFailure { phase: None, - message: Some(status.message().into()), + message: Some(message), + traceback: None, retryable: None, sql_job_id: Some(sql_job_id), source: Some(Arc::new(error)), - }, + }), }; } error diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index 7682b11c1..d147fb374 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -4,7 +4,7 @@ use super::{ SqlClient, materialized_view::quote_identifier, - objects::{definition, literal, strings}, + objects::{definition, description, literal, string_lists, strings}, }; use crate::{ database::ExecuteQueryRequest, @@ -14,7 +14,14 @@ use crate::{ listing::{ListingOptions, ListingPage}, utils::{validate_function_name, validate_namespace}, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + +/// The SQL result of one Function drop, before the public boolean wrapper +/// discards the advisory details. +#[derive(Clone, serde::Deserialize, serde::Serialize)] +pub(in crate::remote) struct DropFunctionOutcome { + pub(in crate::remote) dropped: bool, + pub(in crate::remote) warnings: Vec, +} impl SqlClient { pub(in crate::remote) async fn register_function( @@ -26,15 +33,25 @@ impl SqlClient { validate_function_name(&request.name)?; validate_namespace(namespace)?; let name = quote_identifier(&request.name); + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let mut body = serde_json::to_value(request).map_err(|error| Error::Runtime { message: error.to_string(), })?; body.as_object_mut().unwrap().remove("name"); + body.as_object_mut().unwrap().remove("exist_ok"); self.object_job( ExecuteQueryRequest { - query: format!("CREATE FUNCTION {name} FROM {}", literal(&body.to_string())), + query: format!( + "CREATE FUNCTION{if_not_exists} {name} FROM {}", + literal(&body.to_string()) + ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, definition, ) @@ -43,22 +60,26 @@ impl SqlClient { pub(in crate::remote) async fn describe_function( &self, name: &str, - version: &str, + version: Option<&str>, namespace: &[String], ) -> Result { validate_function_name(name)?; validate_namespace(namespace)?; + let version_clause = match version { + Some(version) => format!(" WITH (version = {})", literal(version)), + None => String::new(), + }; self.object_job( ExecuteQueryRequest { query: format!( - "DESCRIBE FUNCTION {} WITH (version = {})", - quote_identifier(name), - literal(version) + "DESCRIBE FUNCTION {}{version_clause} FORMAT JSON", + quote_identifier(name) ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, - definition, + description, ) .await? .wait() @@ -69,89 +90,25 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid = || Error::InvalidInput { - message: "invalid function page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let bytes = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid())?; - let (database, prefix, path, name, version): ( - String, - Option, - Vec, - String, - String, - ) = serde_json::from_slice(&bytes).map_err(|_| invalid())?; - if database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid()); - } - Some((name, version)) - } else { - None - }; - let mut sql_options = vec![ - format!("limit = {}", u64::from(limit) + 1), - "include_definition = true".to_owned(), - ]; - if let Some((name, version)) = &after { - sql_options.push(format!("after_name = {}", literal(name))); - sql_options.push(format!("after_version = {}", literal(version))); - } - let mut items: Vec = self - .object_job( - ExecuteQueryRequest { - query: format!("SHOW FUNCTIONS HISTORY WITH ({})", sql_options.join(", ")), - default_namespace_path: namespace.to_vec(), - parameters: None, - }, - |batches| { - strings(&batches, "definition")? - .into_iter() - .map(|value| { - serde_json::from_str(&value).map_err(|error| Error::Runtime { - message: error.to_string(), - }) - }) - .collect::>>() - }, - ) - .await? - .wait() + let (batches, page_token) = self + .listing_page("SHOW FUNCTIONS HISTORY", namespace, options) .await?; - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let last = items.last().unwrap(); - let bytes = serde_json::to_vec(&( - &self.inner.database, - &self.inner.database_prefix, - namespace, - last.name(), - last.version(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(bytes)) - } else { - None - }; + let items = strings(&batches, "definition")? + .into_iter() + .map(|value| { + serde_json::from_str(&value).map_err(|error| Error::Runtime { + message: error.to_string(), + }) + }) + .collect::>>()?; Ok(ListingPage { items, page_token }) } - pub(in crate::remote) async fn drop_function( + pub(in crate::remote) async fn drop_function_outcome( &self, name: &str, version: &str, namespace: &[String], - ) -> Result<(bool, Job)> { + ) -> Result<(DropFunctionOutcome, Job)> { validate_function_name(name)?; validate_namespace(namespace)?; let job = self @@ -164,26 +121,41 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, |batches| { let rows = strings(&batches, "status")?; - match rows.as_slice() { - [status] if status == "dropped" => Ok(true), - [status] if status == "not_found" => Ok(false), - _ => Err(Error::Runtime { - message: "invalid DROP FUNCTION result".into(), - }), - } + let dropped = match rows.as_slice() { + [status] if status == "dropped" => true, + [status] if status == "not_found" => false, + _ => { + return Err(Error::Runtime { + message: "invalid DROP FUNCTION result".into(), + }); + } + }; + Ok(DropFunctionOutcome { + dropped, + warnings: string_lists(&batches, "warnings")?, + }) }, ) .await?; let id = job.id().unwrap().parse().map_err(|_| Error::Runtime { message: "invalid SQL query job id".into(), })?; - let dropped = job.wait().await?; - Ok(( - dropped, - Job::from_query_task(id, tokio::spawn(async { Ok(()) }), || async { Ok(()) }), - )) + let outcome = job.wait().await?; + let job = Job::from_query_task(id, tokio::spawn(async { Ok(()) }), || async { Ok(()) }); + Ok((outcome, job)) + } + + pub(in crate::remote) async fn drop_function( + &self, + name: &str, + version: &str, + namespace: &[String], + ) -> Result<(bool, Job)> { + let (outcome, job) = self.drop_function_outcome(name, version, namespace).await?; + Ok((outcome.dropped, job)) } } diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index 4eaad5156..b8b9fc2f7 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -3,12 +3,11 @@ use std::sync::Arc; -use arrow_array::{Array, RecordBatch, StringArray}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use arrow_array::{Array, StringArray}; use futures::TryStreamExt; -use super::SqlClient; -use crate::arrow::SendableRecordBatchStream; +use super::receipt::ReceiptRow; +use super::{SqlClient, objects::description}; use crate::database::ExecuteQueryRequest; use crate::error::{Error, Result}; use crate::listing::{ListingOptions, ListingPage}; @@ -20,25 +19,13 @@ pub(in crate::remote) fn quote_identifier(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) } -fn strings(batch: &RecordBatch, name: &str) -> Result> { - let values = batch - .column_by_name(name) - .and_then(|column| column.as_any().downcast_ref::()) - .ok_or_else(|| Error::Runtime { - message: format!("materialized-view SQL result is missing UTF-8 column '{name}'"), - })?; - if values.null_count() != 0 { - return Err(Error::Runtime { - message: format!("materialized-view SQL result contains null '{name}'"), - }); - } - Ok(values - .iter() - .map(|value| value.unwrap().to_owned()) - .collect()) +#[derive(serde::Deserialize)] +struct MaterializedViewMetadata { + query: String, } pub(in crate::remote) enum MaterializedViewJobSubmission { + AlreadyExists, Registry { job_id: String }, Query(Arc), } @@ -55,56 +42,43 @@ impl SqlClient { query: statement, default_namespace_path: namespace, parameters: None, + options: Default::default(), }, true, ) .await?; - let query = Arc::new(submitted.query); if !submitted.materialized_view_job_handle_supported { - return Ok(MaterializedViewJobSubmission::Query(query)); + return Ok(MaterializedViewJobSubmission::Query(Arc::new( + submitted.query, + ))); } - let mut reader: SendableRecordBatchStream = query.reader().await?; - let mut rows = 0; - let mut registry_job_id = None; - while let Some(batch) = reader.try_next().await? { - rows += batch.num_rows(); - if rows > 1 { - return Err(Error::Runtime { - message: "materialized-view submission must return exactly one status row" - .into(), - }); - } - if let Some(column) = batch.column_by_name("job_id") { - let values = column - .as_any() - .downcast_ref::() - .ok_or_else(|| Error::Runtime { - message: "materialized-view submission job_id is not UTF-8".into(), - })?; - if values.null_count() != 0 { - return Err(Error::Runtime { - message: "materialized-view submission contains a null job_id".into(), - }); - } - if values.is_empty() { - continue; - } - let value = values.value(0); - if !value.is_empty() { - registry_job_id = Some(value.to_string()); - } - } - } - if rows != 1 { - return Err(Error::Runtime { + let row = ReceiptRow::read(&submitted.query) + .await? + .ok_or_else(|| Error::Runtime { message: "materialized-view submission must return exactly one status row".into(), - }); + })?; + let already_exists = if let Some(column) = row.column("status") { + let status = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "materialized-view submission status is not UTF-8".into(), + })?; + !status.is_null(0) && status.value(0) == "already_exists" + } else { + false + }; + match row.job_id()? { + Some(id) => Ok(MaterializedViewJobSubmission::Registry { + job_id: id.to_owned(), + }), + None if already_exists => Ok(MaterializedViewJobSubmission::AlreadyExists), + None => Err(Error::Runtime { + message: + "server acknowledged an early materialized-view handle but returned no job_id" + .into(), + }), } - let job_id = registry_job_id.ok_or_else(|| Error::Runtime { - message: "server acknowledged an early materialized-view handle but returned no job_id" - .into(), - })?; - Ok(MaterializedViewJobSubmission::Registry { job_id }) } pub(in crate::remote) async fn describe_materialized_view( @@ -116,20 +90,19 @@ impl SqlClient { validate_namespace(namespace)?; let query = self .execute(ExecuteQueryRequest { - query: format!("DESCRIBE MATERIALIZED VIEW {}", quote_identifier(name)), + query: format!( + "DESCRIBE MATERIALIZED VIEW {} FORMAT JSON", + quote_identifier(name) + ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }) .await?; - let mut reader = query.reader().await?; - let mut definitions = Vec::new(); - while let Some(batch) = reader.try_next().await? { - definitions.extend(strings(&batch, "query")?); - } - let [definition_sql] = - <[String; 1]>::try_from(definitions).map_err(|_| Error::Runtime { - message: "DESCRIBE MATERIALIZED VIEW must return exactly one definition".into(), - })?; + let reader = query.reader().await?; + let metadata: MaterializedViewMetadata = + description(reader.try_collect::>().await?)?; + let definition_sql = metadata.query; let parsed_definition = MaterializedViewDefinition::from_sql(&definition_sql).ok(); Ok(MaterializedViewInfo { definition_sql, @@ -142,60 +115,7 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid materialized-view page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (database, prefix, path, last): (String, Option, Vec, String) = - serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!( - "SHOW MATERIALIZED VIEWS{after} LIMIT {}", - u64::from(limit) + 1 - ), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&batch, "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW MATERIALIZED VIEWS", namespace, options) + .await } } diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index 2c4d33614..cbf40f576 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -1,43 +1,196 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use super::SqlClient; +use super::{SqlClient, materialized_view::quote_identifier}; use crate::{ database::ExecuteQueryRequest, error::{Error, Result}, job::Job, + listing::{ListingOptions, ListingPage}, + utils::validate_namespace, }; -use arrow_array::{Array, RecordBatch, StringArray}; +use arrow_array::{Array, LargeStringArray, ListArray, RecordBatch, StringArray, StringViewArray}; use futures::TryStreamExt; use serde::{Serialize, de::DeserializeOwned}; use std::sync::Arc; +const DEFAULT_SQL_LISTING_LIMIT: u32 = 1_000; +const MAX_SQL_LISTING_LIMIT: u32 = 10_000; +const NEXT_PAGE_TOKEN_METADATA_KEY: &str = "lancedb.next_page_token"; + +impl SqlClient { + pub(in crate::remote) async fn listing_page( + &self, + statement: &str, + namespace: &[String], + options: ListingOptions, + ) -> Result<(Vec, Option)> { + validate_namespace(namespace)?; + let limit = options.page_limit.unwrap_or(DEFAULT_SQL_LISTING_LIMIT); + if limit > MAX_SQL_LISTING_LIMIT { + return Err(Error::InvalidInput { + message: format!("page limit must be between 0 and {MAX_SQL_LISTING_LIMIT}"), + }); + } + if options.page_token.as_ref().is_some_and(String::is_empty) { + return Err(Error::InvalidInput { + message: "page token must not be empty".into(), + }); + } + if limit == 0 { + return Ok((Vec::new(), None)); + } + let schema = if namespace.is_empty() { + "public".to_owned() + } else { + namespace.join("$") + }; + let mut statement = format!("{statement} IN {} LIMIT {limit}", quote_identifier(&schema)); + if let Some(token) = options.page_token { + statement.push_str(&format!(" FROM {}", literal(&token))); + } + let query = self + .execute(ExecuteQueryRequest { + query: statement, + default_namespace_path: namespace.to_vec(), + parameters: None, + options: Default::default(), + }) + .await?; + let reader = query.reader().await?; + let token = reader + .schema() + .metadata() + .get(NEXT_PAGE_TOKEN_METADATA_KEY) + .cloned() + .filter(|token| !token.is_empty()); + let batches = reader.try_collect::>().await?; + if batches.iter().map(RecordBatch::num_rows).sum::() > limit as usize { + return Err(Error::Runtime { + message: "SQL listing exceeded its requested page size".into(), + }); + } + Ok((batches, token)) + } + + pub(in crate::remote) async fn list_names( + &self, + statement: &str, + namespace: &[String], + options: ListingOptions, + ) -> Result> { + let (batches, page_token) = self.listing_page(statement, namespace, options).await?; + Ok(ListingPage { + items: strings(&batches, "name")?, + page_token, + }) + } +} + pub(super) fn literal(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } pub(super) fn strings(batches: &[RecordBatch], name: &str) -> Result> { - batches - .iter() - .map(|batch| { - let values = batch - .column_by_name(name) - .and_then(|column| column.as_any().downcast_ref::()) - .ok_or_else(|| Error::Runtime { - message: format!("SQL result is missing UTF-8 column '{name}'"), - })?; - if values.null_count() != 0 { + let mut result = Vec::new(); + for batch in batches { + let column = batch.column_by_name(name).ok_or_else(|| Error::Runtime { + message: format!("SQL result is missing string column '{name}'"), + })?; + if column.null_count() != 0 { + return Err(Error::Runtime { + message: format!("SQL result contains null '{name}'"), + }); + } + if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else { + return Err(Error::Runtime { + message: format!("SQL result column '{name}' is not a string"), + }); + } + } + Ok(result) +} + +/// Read an optional `List` column. Older servers do not return the +/// column, so a missing column means no warnings rather than a bad result. +pub(super) fn string_lists(batches: &[RecordBatch], name: &str) -> Result> { + let mut values = Vec::new(); + for batch in batches { + let Some(column) = batch.column_by_name(name) else { + continue; + }; + let lists = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: format!("SQL result column '{name}' is not a string list"), + })?; + for index in 0..lists.len() { + if lists.is_null(index) { return Err(Error::Runtime { message: format!("SQL result contains null '{name}'"), }); } - Ok(values - .iter() - .map(|value| value.unwrap().to_owned()) - .collect::>()) - }) - .collect::>>() - .map(|rows| rows.into_iter().flatten().collect()) + let list = lists.value(index); + let strings = + list.as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: format!("SQL result column '{name}' contains a non-string value"), + })?; + if strings.null_count() != 0 { + return Err(Error::Runtime { + message: format!("SQL result column '{name}' contains null values"), + }); + } + values.extend(strings.iter().map(|value| value.unwrap().to_owned())); + } + } + Ok(values) } + +pub(in crate::remote) fn description(batches: Vec) -> Result { + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(Error::Runtime { + message: "DESCRIBE FORMAT JSON must return exactly one document".into(), + }); + } + for batch in &batches { + if batch.num_columns() != 1 + || batch + .schema() + .metadata() + .get("lancedb.describe.format") + .map(String::as_str) + != Some("json") + || batch + .column_by_name("description") + .and_then(|column| column.as_any().downcast_ref::()) + .is_none() + { + return Err(Error::Runtime { message: "DESCRIBE FORMAT JSON requires one UTF8 description column with JSON format metadata".into() }); + } + } + let mut documents = strings(&batches, "description")?; + let document: serde_json::Value = + serde_json::from_str(&documents.remove(0)).map_err(|error| Error::Runtime { + message: format!("Invalid DESCRIBE JSON document: {error}"), + })?; + if !document.is_object() { + return Err(Error::Runtime { + message: "DESCRIBE FORMAT JSON requires an object document".into(), + }); + } + serde_json::from_value(document).map_err(|error| Error::Runtime { + message: format!("Invalid DESCRIBE metadata: {error}"), + }) +} + pub(super) fn definition(batches: Vec) -> Result { let values = strings(&batches, "definition")?; let [value]: [String; 1] = values.try_into().map_err(|_| Error::Runtime { @@ -70,3 +223,161 @@ impl SqlClient { })) } } + +#[cfg(test)] +mod tests { + use super::{string_lists, strings}; + use arrow_array::builder::{ListBuilder, StringBuilder}; + use arrow_array::{ArrayRef, LargeStringArray, RecordBatch, StringArray, StringViewArray}; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + fn warning_schema() -> Arc { + Arc::new(Schema::new(vec![Field::new( + "warnings", + DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))), + true, + )])) + } + + #[test] + fn listing_strings_accept_all_arrow_string_representations() { + for values in [ + Arc::new(StringArray::from(vec!["a", "z"])) as ArrayRef, + Arc::new(LargeStringArray::from(vec!["a", "z"])) as ArrayRef, + Arc::new(StringViewArray::from(vec!["a", "z"])) as ArrayRef, + ] { + let batch = RecordBatch::try_from_iter(vec![("name", values)]).unwrap(); + assert_eq!(strings(&[batch], "name").unwrap(), ["a", "z"]); + } + let batch = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringViewArray::from(vec![Some("a"), None])) as ArrayRef, + )]) + .unwrap(); + assert!(strings(&[batch], "name").is_err()); + } + + #[test] + fn reads_warnings_after_an_empty_first_batch() { + let schema = warning_schema(); + let empty = RecordBatch::new_empty(schema.clone()); + let mut builder = ListBuilder::new(StringBuilder::new()); + builder.values().append_value( + "materialized view \"pinned\" references Function \"embed\" version \"1\"", + ); + builder.append(true); + let non_empty = + RecordBatch::try_new(schema.clone(), vec![Arc::new(builder.finish()) as ArrayRef]) + .unwrap(); + + assert_eq!( + string_lists(&[empty, non_empty], "warnings").unwrap(), + ["materialized view \"pinned\" references Function \"embed\" version \"1\""] + ); + } + + #[test] + fn missing_warning_column_remains_an_empty_result() { + let schema = Arc::new(Schema::new(vec![Field::new( + "status", + DataType::Utf8, + false, + )])); + let batch = RecordBatch::new_empty(schema); + + assert_eq!( + string_lists(&[batch], "warnings").unwrap(), + Vec::::new() + ); + } + + #[test] + fn null_or_non_list_warning_values_are_rejected() { + let mut builder = ListBuilder::new(StringBuilder::new()); + builder.append(false); + let null_list = RecordBatch::try_new( + warning_schema(), + vec![Arc::new(builder.finish()) as ArrayRef], + ) + .unwrap(); + assert!(string_lists(&[null_list], "warnings").is_err()); + + let non_list_schema = Arc::new(Schema::new(vec![Field::new( + "warnings", + DataType::Utf8, + false, + )])); + let non_list = RecordBatch::new_empty(non_list_schema); + assert!(string_lists(&[non_list], "warnings").is_err()); + } +} + +#[cfg(test)] +mod description_tests { + use super::*; + + #[test] + fn descriptions_require_one_explicit_json_document() { + let document = serde_json::json!({"name":"saved", "schema":{"fields":[]}, "nullable":null}); + let batch = RecordBatch::try_new( + Arc::new( + arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "description", + arrow_schema::DataType::Utf8, + false, + )]) + .with_metadata(std::collections::HashMap::from([( + "lancedb.describe.format".into(), + "json".into(), + )])), + ), + vec![Arc::new(StringArray::from(vec![document.to_string()]))], + ) + .unwrap(); + assert_eq!( + description::(vec![batch.clone()]).unwrap(), + document + ); + assert!(description::(vec![]).is_err()); + assert!(description::(vec![batch.clone(), batch.clone()]).is_err()); + let invalid = RecordBatch::try_new( + batch.schema(), + vec![Arc::new(StringArray::from(vec!["View\nname: saved"]))], + ) + .unwrap(); + assert!(description::(vec![invalid]).is_err()); + let text = RecordBatch::try_new( + Arc::new(batch.schema().as_ref().clone().with_metadata( + std::collections::HashMap::from([( + "lancedb.describe.format".into(), + "text".into(), + )]), + )), + batch.columns().to_vec(), + ) + .unwrap(); + assert!(description::(vec![text]).is_err()); + for value in ["[]", "null", "1", "\"text\""] { + let scalar = RecordBatch::try_new( + batch.schema(), + vec![Arc::new(StringArray::from(vec![value]))], + ) + .unwrap(); + assert!(description::(vec![scalar]).is_err()); + } + let null = RecordBatch::try_new( + Arc::new( + arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "description", + arrow_schema::DataType::Utf8, + true, + )]) + .with_metadata(batch.schema().metadata().clone()), + ), + vec![Arc::new(StringArray::from(vec![None::<&str>]))], + ) + .unwrap(); + assert!(description::(vec![null]).is_err()); + } +} diff --git a/rust/lancedb/src/remote/sql/receipt.rs b/rust/lancedb/src/remote/sql/receipt.rs new file mode 100644 index 000000000..4f45292d5 --- /dev/null +++ b/rust/lancedb/src/remote/sql/receipt.rs @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{Array, ArrayRef, RecordBatch, StringArray}; +use futures::TryStreamExt; + +use crate::sql::Query; +use crate::{Error, Result}; + +/// The single row returned by a SQL job submission, after its stream completed successfully. +pub(in crate::remote) struct ReceiptRow(RecordBatch); + +impl ReceiptRow { + /// Empty batches carry no receipt data. Zero or multiple rows yield `None`. + pub(in crate::remote) async fn read(query: &Query) -> Result> { + let mut reader = query.reader().await?; + let mut receipt = None; + let mut rows = 0usize; + while let Some(batch) = reader.try_next().await? { + rows = rows.saturating_add(batch.num_rows()); + if rows == 1 && batch.num_rows() == 1 { + receipt = Some(Self(batch)); + } + } + Ok(receipt.filter(|_| rows == 1)) + } + + pub(in crate::remote) fn column(&self, name: &str) -> Option<&ArrayRef> { + self.0.column_by_name(name) + } + + /// An absent column or an empty string can represent a completed no-op. + /// Each command decides whether its receipt permits that outcome. + pub(in crate::remote) fn job_id(&self) -> Result> { + let Some(column) = self.column("job_id") else { + return Ok(None); + }; + let ids = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "SQL job receipt job_id is not UTF-8".into(), + })?; + if ids.is_null(0) { + return Err(Error::Runtime { + message: "SQL job receipt contains a null job_id".into(), + }); + } + let id = ids.value(0); + if id.is_empty() { + Ok(None) + } else if id.trim().is_empty() { + Err(Error::Runtime { + message: "SQL job receipt contains a blank job_id".into(), + }) + } else { + Ok(Some(id)) + } + } +} diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index bdb70ef6f..ded060e93 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use super::{SqlClient, materialized_view::quote_identifier, objects::strings}; +use super::{SqlClient, materialized_view::quote_identifier, objects::description}; use crate::{ database::ExecuteQueryRequest, error::{Error, Result}, @@ -9,36 +9,16 @@ use crate::{ secrets::SecretInfo, utils::{validate_namespace, validate_secret_name}, }; -use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use futures::TryStreamExt; +use arrow_array::{RecordBatch, StringArray}; use std::sync::Arc; + +pub(in crate::remote) enum SecretWriteOperation { + Create { exist_ok: bool }, + Alter, +} + fn secret_info(batches: Vec) -> Result { - if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { - return Err(Error::Runtime { - message: "DESCRIBE SECRET must return exactly one row".into(), - }); - } - let batch = batches.iter().find(|batch| batch.num_rows() == 1).unwrap(); - let timestamp = |name: &str| -> Result { - let values = batch - .column_by_name(name) - .and_then(|column| column.as_any().downcast_ref::()) - .ok_or_else(|| Error::Runtime { - message: format!("DESCRIBE SECRET is missing INT64 column '{name}'"), - })?; - if values.is_null(0) { - return Err(Error::Runtime { - message: format!("DESCRIBE SECRET contains null '{name}'"), - }); - } - Ok(values.value(0)) - }; - Ok(SecretInfo { - name: strings(&batches, "name")?.remove(0), - created_at_millis: timestamp("created_at_millis")?, - updated_at_millis: timestamp("updated_at_millis")?, - }) + description(batches) } impl SqlClient { @@ -47,10 +27,21 @@ impl SqlClient { name: &str, value: &str, namespace: &[String], - create: bool, + operation: SecretWriteOperation, ) -> Result<()> { validate_secret_name(name)?; validate_namespace(namespace)?; + let (prefix, assignment) = match operation { + SecretWriteOperation::Create { exist_ok } => ( + if exist_ok { + "CREATE SECRET IF NOT EXISTS" + } else { + "CREATE SECRET" + }, + "TYPE = GENERIC_STRING ", + ), + SecretWriteOperation::Alter => ("ALTER SECRET", "SET "), + }; let parameters = RecordBatch::try_from_iter(vec![( "", Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, @@ -61,17 +52,14 @@ impl SqlClient { self.object_job( ExecuteQueryRequest { query: format!( - "{} SECRET {} {}SECRET_STRING = $1", - if create { "CREATE" } else { "ALTER" }, + "{} {} {}SECRET_STRING = $1", + prefix, quote_identifier(name), - if create { - "TYPE = GENERIC_STRING " - } else { - "SET " - } + assignment ), default_namespace_path: namespace.to_vec(), parameters: Some(parameters), + options: Default::default(), }, |_| Ok(()), ) @@ -88,9 +76,10 @@ impl SqlClient { validate_namespace(namespace)?; self.object_job( ExecuteQueryRequest { - query: format!("DESCRIBE SECRET {}", quote_identifier(name)), + query: format!("DESCRIBE SECRET {} FORMAT JSON", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, secret_info, ) @@ -110,6 +99,7 @@ impl SqlClient { query: format!("DROP SECRET IF EXISTS {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, |_| Ok(()), ) @@ -122,101 +112,47 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid secret page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (kind, database, prefix, path, last): ( - String, - String, - Option, - Vec, - String, - ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if kind != "secret" - || database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!("SHOW SECRETS{after} LIMIT {}", u64::from(limit) + 1), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&[batch], "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - "secret", - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW SECRETS", namespace, options).await } } #[cfg(test)] mod tests { use super::*; - use arrow_array::ArrayRef; #[test] - fn decodes_native_secret_metadata() { - let batch = RecordBatch::try_from_iter(vec![ - ( - "name", - Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, - ), - ( - "created_at_millis", - Arc::new(Int64Array::from(vec![10])) as ArrayRef, - ), - ( - "updated_at_millis", - Arc::new(Int64Array::from(vec![20])) as ArrayRef, - ), - ]) + fn decodes_secret_json_metadata() { + let document = serde_json::json!({"name":"api-key", "created_at_millis":10, "updated_at_millis":20, "history":[{"generation":1,"at_millis":10}]}); + let schema = arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "description", + arrow_schema::DataType::Utf8, + false, + )]) + .with_metadata(std::collections::HashMap::from([( + "lancedb.describe.format".into(), + "json".into(), + )])); + let batch = RecordBatch::try_new( + Arc::new(schema), + vec![Arc::new(StringArray::from(vec![document.to_string()]))], + ) .unwrap(); let info = secret_info(vec![batch.clone()]).unwrap(); assert_eq!(info.name, "api-key"); assert_eq!(info.created_at_millis, 10); assert_eq!(info.updated_at_millis, 20); assert!(secret_info(vec![]).is_err()); - assert!(secret_info(vec![batch.clone(), batch]).is_err()); - let missing = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, - )]) - .unwrap(); - assert!(secret_info(vec![missing]).is_err()); + assert!(secret_info(vec![batch.clone(), batch.clone()]).is_err()); + for invalid in [ + serde_json::json!({"name":"api-key"}), + serde_json::json!({"name":"api-key","created_at_millis":"10","updated_at_millis":20}), + ] { + let batch = RecordBatch::try_new( + batch.schema(), + vec![Arc::new(StringArray::from(vec![invalid.to_string()]))], + ) + .unwrap(); + assert!(secret_info(vec![batch]).is_err()); + } } } diff --git a/rust/lancedb/src/remote/sql/stream.rs b/rust/lancedb/src/remote/sql/stream.rs index 420eecd15..b5315353f 100644 --- a/rust/lancedb/src/remote/sql/stream.rs +++ b/rust/lancedb/src/remote/sql/stream.rs @@ -21,9 +21,9 @@ use uuid::Uuid; use super::{ ABANDONED_QUERY_RETENTION, DEFAULT_READ_TIMEOUT, ResultEndpointStream, ResultStartGuard, SqlClientInner, TERMINAL_QUERY_RETENTION, resolve_timeout, sql_error, sql_flight_error, - sql_status_error, with_overall_timeout, + sql_result_stream, sql_status_error, with_overall_timeout, }; -use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}; +use crate::arrow::SendableRecordBatchStream; use crate::error::{Error, Result}; use crate::sql::{QueryDescription, QueryHandle, QueryStatus}; @@ -55,6 +55,8 @@ pub(super) struct StreamingQuery { cancelled: Notify, terminal_at: OnceLock, last_accessed: StdMutex, + job_id: StdMutex>, + deadline_task: StdMutex>, } struct PreparedStream { @@ -125,6 +127,7 @@ pub(super) enum Submission { pub(super) struct OpenedSubmission { pub(super) submission: Submission, pub(super) materialized_view_job_handle_supported: bool, + pub(super) job_id: Option, } impl StreamingQuery { @@ -181,15 +184,18 @@ impl StreamingQuery { .map_err(|error| sql_flight_error(&request_id, &error))?; let mut request = tonic::Request::new(futures::stream::iter(messages)); *request.metadata_mut() = metadata; + client.set_execution_timeout(&mut request); tokio::time::timeout(read_timeout, flight.do_exchange(request)).await } else { let mut request = tonic::Request::new(Ticket::new(CommandTicket { command }.encode_to_vec())); *request.metadata_mut() = metadata; + client.set_execution_timeout(&mut request); tokio::time::timeout(read_timeout, flight.do_get(request)).await } .map_err(|_| sql_error(&request_id, "SQL query submission timed out"))? .map_err(|error| sql_status_error(&request_id, &error))?; + let response_job_id = super::sql_job_id_from_metadata(response.metadata()); let negotiated = response .metadata() .get(PROTOCOL_HEADER) @@ -233,6 +239,7 @@ impl StreamingQuery { return Ok(OpenedSubmission { submission: Submission::Deferred(info), materialized_view_job_handle_supported, + job_id: response_job_id, }); } } @@ -245,8 +252,10 @@ impl StreamingQuery { stream, request_id, read_timeout, + job_id: None, }), materialized_view_job_handle_supported: false, + job_id: response_job_id, }) } @@ -254,6 +263,7 @@ impl StreamingQuery { id: Uuid, client: Arc, response: ResultEndpointStream, + job_id: Option, ) -> Self { Self { id, @@ -263,9 +273,31 @@ impl StreamingQuery { cancelled: Notify::new(), terminal_at: OnceLock::new(), last_accessed: StdMutex::new(Instant::now()), + job_id: StdMutex::new(job_id.filter(|job_id| !job_id.is_empty())), + deadline_task: StdMutex::new(None), } } + pub(super) fn start_deadline(self: &Arc) { + let Some(deadline) = self.client.deadline else { + return; + }; + let query = Arc::downgrade(self); + let task = tokio::spawn(async move { + tokio::time::sleep_until(deadline).await; + if let Some(query) = query.upgrade() { + query.settle(Lifecycle::Failed("SQL query result timed out".to_string())); + query.response.lock().unwrap().take(); + } + }); + *self.deadline_task.lock().unwrap() = Some(task.abort_handle()); + } + + #[cfg(test)] + pub(super) fn deadline_stopped(&self) -> bool { + self.deadline_task.lock().unwrap().is_none() + } + pub(super) fn touch(&self) { *self.last_accessed.lock().unwrap() = Instant::now(); } @@ -291,6 +323,7 @@ impl StreamingQuery { }; Ok(QueryDescription { id: self.id, + job_id: self.job_id(), status, progress: (status == QueryStatus::Finished).then_some(1.0), expires_at: None, @@ -319,14 +352,49 @@ impl StreamingQuery { *lifecycle = state; drop(lifecycle); let _ = self.terminal_at.set(Instant::now()); + if let Some(task) = self.deadline_task.lock().unwrap().take() { + task.abort(); + } + self.cancelled.notify_waiters(); true } fn is_cancelled(&self) -> bool { - *self.lifecycle.lock().unwrap() == Lifecycle::Cancelled + matches!( + *self.lifecycle.lock().unwrap(), + Lifecycle::Cancelled | Lifecycle::Failed(_) + ) + } + + fn job_id(&self) -> Option { + self.job_id.lock().unwrap().clone() + } + + fn observe_job_id(&self, job_id: Option<&str>) -> Result<()> { + let Some(job_id) = job_id.filter(|job_id| !job_id.is_empty()) else { + return Ok(()); + }; + let mut current = self.job_id.lock().unwrap(); + match current.as_deref() { + None => *current = Some(job_id.to_string()), + Some(existing) if existing == job_id => {} + Some(existing) => { + return Err(Error::Runtime { + message: format!( + "SQL query changed durable job identity from {existing} to {job_id}" + ), + }); + } + } + Ok(()) } fn cancelled_error(&self) -> Error { + if let Lifecycle::Failed(message) = &*self.lifecycle.lock().unwrap() { + return Error::Runtime { + message: message.clone(), + }; + } Error::JobCancelled { job_id: Some(self.id.to_string()), } @@ -345,13 +413,7 @@ impl StreamingQuery { /// Take the rows and wait for the first batch, which carries the schema. async fn prepare(&self) -> Result { let Some(rows) = self.response.lock().unwrap().take() else { - // Taken by an earlier attempt that failed, or dropped by a cancel. - return Err(match &*self.lifecycle.lock().unwrap() { - Lifecycle::Failed(message) => Error::Runtime { - message: message.clone(), - }, - _ => self.cancelled_error(), - }); + return Err(self.cancelled_error()); }; let mut rows = Borrowed { query: self, @@ -373,6 +435,7 @@ impl StreamingQuery { .ok_or_else(|| Error::Runtime { message: "SQL result stream did not include a schema".to_string(), })?; + self.observe_job_id(super::sql_job_id_from_schema(&schema).as_deref())?; if first.is_none() { self.settle(Lifecycle::Finished); } @@ -476,12 +539,16 @@ impl QueryHandle for StreamingQueryHandle { self.query.id } + fn job_id(&self) -> Option { + self.query.job_id() + } + async fn describe(&self) -> Result { self.query.describe() } async fn reader(&self) -> Result { - let timeout = self.query.client.overall_timeout()?; + let timeout = self.query.client.execution_timeout()?; if self .result_started .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) @@ -522,11 +589,12 @@ impl QueryHandle for StreamingQueryHandle { let _ = error_sender.send(Err(error)).await; } }); - let stream = futures::stream::unfold(receiver, |mut receiver| async move { - receiver.recv().await.map(|item| (item, receiver)) - }); result_start.commit(); - Ok(Box::pin(SimpleRecordBatchStream::new(stream, schema))) + let stream = sql_result_stream(receiver, schema, self.query.client.deadline, ()); + Ok(match self.job_id() { + Some(job_id) => super::attach_sql_job_id(stream, &job_id), + None => stream, + }) } async fn cancel(&self) -> Result<()> { diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index 0c2229684..32a43b421 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -1,7 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use super::{SqlClient, materialized_view::quote_identifier, objects::strings}; +use super::{ + SqlClient, + materialized_view::quote_identifier, + objects::{description, strings}, +}; use crate::{ database::ExecuteQueryRequest, error::{Error, Result}, @@ -9,8 +13,6 @@ use crate::{ utils::{validate_namespace, validate_view_name}, view::ViewDescription, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use futures::TryStreamExt; use lance_namespace::models::JsonArrowSchema; use std::sync::Arc; #[derive(Clone, serde::Serialize, serde::Deserialize)] @@ -42,7 +44,7 @@ impl ViewDefinition { } } -fn view_description( +fn created_view_definition( batches: Vec, namespace: Vec, ) -> Result { @@ -55,11 +57,29 @@ fn view_description( } Ok(values.remove(0)) }; - let name = one("name")?; - let json: JsonArrowSchema = - serde_json::from_str(&one("schema")?).map_err(|error| Error::Runtime { - message: format!("View '{name}' has invalid schema JSON: {error}"), - })?; + let metadata = ViewMetadata { + name: one("name")?, + query: one("query")?, + schema: serde_json::from_str(&one("schema")?).map_err(|error| Error::Runtime { + message: format!("View metadata has invalid schema JSON: {error}"), + })?, + }; + view_definition(metadata, namespace) +} + +#[derive(serde::Deserialize)] +struct ViewMetadata { + name: String, + query: String, + schema: JsonArrowSchema, +} + +fn view_definition(metadata: ViewMetadata, namespace: Vec) -> Result { + let ViewMetadata { + name, + query, + schema: json, + } = metadata; let schema = lance_namespace::schema::convert_json_arrow_schema(&json).map_err(|error| { Error::Runtime { message: format!("View '{name}' has an undecodable schema: {error}"), @@ -86,7 +106,7 @@ fn view_description( Ok(ViewDefinition { name, namespace, - query: one("query")?, + query, default_database, default_namespace: default_namespace_path, schema: json, @@ -99,17 +119,23 @@ impl SqlClient { name: &str, query: &str, namespace: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace)?; let namespace_path = namespace.to_vec(); + let if_not_exists = if exist_ok { " IF NOT EXISTS" } else { "" }; self.object_job( ExecuteQueryRequest { - query: format!("CREATE VIEW {} AS {query}", quote_identifier(name)), + query: format!( + "CREATE VIEW{if_not_exists} {} AS {query}", + quote_identifier(name) + ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, - move |batches| view_description(batches, namespace_path), + move |batches| created_view_definition(batches, namespace_path), ) .await? .wait() @@ -126,11 +152,12 @@ impl SqlClient { let namespace_path = namespace.to_vec(); self.object_job( ExecuteQueryRequest { - query: format!("DESCRIBE VIEW {}", quote_identifier(name)), + query: format!("DESCRIBE VIEW {} FORMAT JSON", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, - move |batches| view_description(batches, namespace_path), + move |batches| view_definition(description(batches)?, namespace_path), ) .await? .wait() @@ -142,64 +169,6 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid view page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (kind, database, prefix, path, last): ( - String, - String, - Option, - Vec, - String, - ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if kind != "view" - || database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!("SHOW VIEWS{after} LIMIT {}", u64::from(limit) + 1), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&[batch], "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - "view", - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW VIEWS", namespace, options).await } } diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index b25ab4ddb..f14eb3cc9 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3,7 +3,7 @@ use std::sync::atomic::AtomicUsize; -use arrow_array::builder::StringDictionaryBuilder; +use arrow_array::builder::{ListBuilder, StringBuilder, StringDictionaryBuilder}; use arrow_array::types::{Float32Type, Int32Type}; use arrow_array::{Array, ArrayRef, FixedSizeListArray, Float32Array, Int64Array, StringArray}; use arrow_flight::encode::FlightDataEncoderBuilder; @@ -14,7 +14,6 @@ use arrow_flight::{ FlightInfo, HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket, }; use arrow_schema::{DataType, Field, Schema}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::stream::BoxStream; use futures::{StreamExt, TryStreamExt}; use tonic::metadata::MetadataMap; @@ -24,6 +23,7 @@ use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; use crate::Connection; use crate::database::Database; +use crate::embeddings::MemoryRegistry; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::RemoteCatalogOptions; use crate::remote::client::HeaderProvider; @@ -33,6 +33,53 @@ use crate::remote::table::RemoteTable; use crate::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; use crate::table::BaseTable; +#[test] +fn server_info_survives_flight_error_and_job_wrapping() { + for with_job in [false, true] { + let mut status = tonic::Status::invalid_argument("invalid query"); + status + .metadata_mut() + .insert("x-lancedb-error-code", "invalid_query".parse().unwrap()); + let build = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" + }) + .to_string(); + status.metadata_mut().insert_bin( + "x-lancedb-server-build-bin", + tonic::metadata::MetadataValue::from_bytes(build.as_bytes()), + ); + if with_job { + status + .metadata_mut() + .insert(SQL_JOB_ID_METADATA_KEY, "job-original".parse().unwrap()); + } + let error = sql_status_error("request-original", &status); + let text = error.to_string(); + assert!(text.contains("invalid query"), "{text}"); + assert!(text.contains("1.2.3"), "{text}"); + assert!(text.contains("0123456789ab"), "{text}"); + assert!(text.contains("2024-01-01T00:00:00Z"), "{text}"); + assert_eq!( + error.remote_error_metadata().unwrap().error_code.as_deref(), + Some("invalid_query") + ); + match error { + Error::JobFailed { job_id, .. } if with_job => { + assert_eq!(job_id.as_deref(), Some("job-original")) + } + Error::Sql { + grpc_code, + request_id, + .. + } if !with_job => { + assert_eq!(grpc_code, tonic::Code::InvalidArgument as i32); + assert_eq!(request_id, "request-original"); + } + other => panic!("unexpected error classification: {other}"), + } + } +} + #[derive(Debug, Default)] struct DelayedHeaderProvider { delay_next: AtomicBool, @@ -69,6 +116,7 @@ struct CapturedHeaders { api_key: String, database_prefix: String, materialized_view_job_handle: Option, + grpc_timeout: Option, } /// Every exchange's statement and the parameter row it arrived with. @@ -91,13 +139,19 @@ struct TestSqlService { first_continuation_count: Arc, transient_poll_failures: Arc, headers: Arc>>, + result_deadlines: Arc>>>, gate_refresh_release: Arc, exchanges: ReceivedExchanges, result_overrides: Arc>>, materialized_view_job_handle_supported: bool, + optimize_error: Option, + prewarm_error: Option, + prewarm_azure_supported: bool, /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, + result_tail: Vec>, + result_frames: Option>, large_result: RecordBatch, dictionary_result: RecordBatch, } @@ -122,6 +176,9 @@ impl TestSqlService { .to_string() }; self.headers.lock().unwrap().push(CapturedHeaders { + grpc_timeout: metadata + .get("grpc-timeout") + .map(|value| value.to_str().unwrap().to_owned()), database: header("database"), namespace_path: header("namespace-path"), request_id: header("x-request-id"), @@ -160,8 +217,17 @@ impl TestSqlService { return Response::new(rows); } let poll_info = self.defer.then(|| { - let mut info = FlightInfo::new() - .with_endpoint(FlightEndpoint::new().with_ticket(Ticket::new(query.to_string()))); + let mut info = FlightInfo::new(); + if !query.starts_with("SELECT durable job") { + info = info.with_endpoint( + FlightEndpoint::new().with_ticket(Ticket::new(query.to_string())), + ); + } + if query.starts_with("SELECT durable job") { + info = info + .try_with_schema(&self.result_for_query(query).schema()) + .unwrap(); + } if self.materialized_view_job_handle_supported { info.app_metadata = b"early-v1".to_vec().into(); } @@ -198,6 +264,13 @@ impl TestSqlService { response .metadata_mut() .insert(PROTOCOL_HEADER, PROTOCOL_VERSION.parse().unwrap()); + if query.starts_with("SELECT direct durable job") { + let job_id = query.rsplit(' ').next().unwrap(); + response.metadata_mut().insert( + SQL_JOB_ID_METADATA_KEY, + format!("job-{job_id}").parse().unwrap(), + ); + } response } } @@ -249,12 +322,18 @@ impl Default for TestSqlService { first_continuation_count: Arc::new(AtomicUsize::new(0)), transient_poll_failures: Arc::new(AtomicUsize::new(0)), headers: Arc::new(std::sync::Mutex::new(Vec::new())), + result_deadlines: Arc::new(std::sync::Mutex::new(Vec::new())), gate_refresh_release: Arc::new(Notify::new()), exchanges: Arc::new(std::sync::Mutex::new(Vec::new())), result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())), materialized_view_job_handle_supported: false, + optimize_error: None, + prewarm_error: None, + prewarm_azure_supported: false, exchange_drops: Arc::new(AtomicUsize::new(0)), result, + result_tail: vec![], + result_frames: None, large_result, dictionary_result, } @@ -287,9 +366,30 @@ impl FlightService for TestSqlService { async fn get_flight_info( &self, - _request: Request, + request: Request, ) -> std::result::Result, Status> { - Err(Status::unimplemented("get_flight_info")) + self.capture_headers(request.metadata()); + assert!( + request + .metadata() + .get("x-azure-storage-account-name") + .is_some() + ); + let schema = if self.prewarm_azure_supported { + self.result + .schema() + .as_ref() + .clone() + .with_metadata(HashMap::from([( + "lancedb.prewarm.azure_storage_account_name".into(), + "true".into(), + )])) + } else { + self.result.schema().as_ref().clone() + }; + Ok(Response::new( + FlightInfo::new().try_with_schema(&schema).unwrap(), + )) } async fn poll_flight_info( @@ -351,7 +451,14 @@ impl FlightService for TestSqlService { .insert("x-lancedb-sql-job-id", "job-1".parse().unwrap()); return Err(status); } - let complete = if query == "SELECT no info" { + if query == "SELECT durable job failure" && stage == 1 { + let mut status = Status::internal("durable SQL job failed"); + status + .metadata_mut() + .insert("x-lancedb-sql-job-id", "job-1".parse().unwrap()); + return Err(status); + } + let complete = if query == "SELECT no info" || query.starts_with("SELECT durable job") { stage >= 2 } else { stage >= 1 @@ -362,11 +469,14 @@ impl FlightService for TestSqlService { } else { query.clone() }; - let mut info = FlightInfo::new().with_endpoint( - FlightEndpoint::new() - .with_ticket(Ticket::new(first_ticket)) - .with_location("grpc://127.0.0.1:1"), - ); + let mut info = FlightInfo::new(); + if !(query.starts_with("SELECT durable job") && !complete) { + info = info.with_endpoint( + FlightEndpoint::new() + .with_ticket(Ticket::new(first_ticket)) + .with_location("grpc://127.0.0.1:1"), + ); + } if query == "SELECT incremental" && stage > 0 { info = info.with_endpoint( FlightEndpoint::new() @@ -378,13 +488,21 @@ impl FlightService for TestSqlService { let schema = self.result_for_query(&query).schema(); info = info.try_with_schema(&schema).unwrap(); } - Ok(Response::new(PollInfo { + let mut response = Response::new(PollInfo { info: (query != "SELECT no info" || stage > 0).then_some(info), flight_descriptor: (!complete) .then(|| FlightDescriptor::new_cmd(format!("poll:{}:{query}", stage + 1))), progress: Some(if complete { 1.0 } else { 0.25 }), expiration_time: None, - })) + }); + if query.starts_with("SELECT durable job") && stage > 0 { + let job_id = query.rsplit(' ').next().unwrap(); + response.metadata_mut().insert( + SQL_JOB_ID_METADATA_KEY, + format!("job-{job_id}").parse().unwrap(), + ); + } + Ok(response) } async fn get_schema( @@ -405,6 +523,17 @@ impl FlightService for TestSqlService { .and_then(|command| command.unpack::().ok().flatten()); if let Some(command) = &initial { self.statements.lock().unwrap().push(command.query.clone()); + if command.query.starts_with("OPTIMIZE ") + && let Some(error) = &self.optimize_error + { + return Err(error.clone()); + } + if (command.query.starts_with("PREWARM") + || command.query.starts_with("EXPLAIN (FORMAT JSON) PREWARM")) + && let Some(error) = &self.prewarm_error + { + return Err(error.clone()); + } if command.query == "SELECT rejected" { return Err(Status::invalid_argument("invalid statement")); } @@ -414,6 +543,14 @@ impl FlightService for TestSqlService { PROTOCOL_VERSION ); } + if initial.is_none() { + self.result_deadlines.lock().unwrap().push( + request + .metadata() + .get("grpc-timeout") + .map(|value| value.to_str().unwrap().to_owned()), + ); + } let query = initial .as_ref() .map(|command| command.query.as_bytes()) @@ -436,16 +573,28 @@ impl FlightService for TestSqlService { } (!empty).then_some(Ok(result)) }) - .filter_map(futures::future::ready); + .filter_map(futures::future::ready) + .chain( + futures::stream::iter(self.result_tail.clone()).then(|item| async { + // Let tonic flush the preceding batch before sending an error trailer. + if item.is_err() { + tokio::task::yield_now().await; + } + item.map_err(|status| FlightError::Tonic(Box::new(status))) + }), + ); let mut encoder = FlightDataEncoderBuilder::new().with_schema(schema); if large { encoder = encoder.with_max_flight_data_size(8 * 1024 * 1024); } - let stream = encoder.build(input).map_err(Status::from); + let stream = match &self.result_frames { + Some(frames) => futures::stream::iter(frames.clone()).map(Ok).boxed(), + None => encoder.build(input).map_err(Status::from).boxed(), + }; if let Some(initial) = initial { - Ok(self.adaptive_response(&initial.query, stream.boxed())) + Ok(self.adaptive_response(&initial.query, stream)) } else { - Ok(Response::new(stream.boxed())) + Ok(Response::new(stream)) } } @@ -566,10 +715,25 @@ impl FlightService for TestSqlService { )); } if query == "SELECT exchange stall" { - return Ok(Response::new(futures::stream::pending().boxed())); + let dropped = DropSignal(self.exchange_drops.clone()); + return Ok(Response::new( + futures::stream::pending() + .map(move |message| { + let _dropped = &dropped; + message + }) + .boxed(), + )); } let rows = parameters.ok_or_else(|| Status::invalid_argument("exchange without parameters"))?; + let rows = self + .result_overrides + .lock() + .unwrap() + .get(&query) + .cloned() + .unwrap_or(rows); let schema = rows.schema(); let rest: BoxStream<'static, arrow_flight::error::Result> = if query == "SELECT exchange slow" { @@ -601,6 +765,17 @@ impl FlightService for TestSqlService { } } +fn description_batch(document: serde_json::Value) -> RecordBatch { + let schema = Schema::new(vec![Field::new("description", DataType::Utf8, false)]).with_metadata( + HashMap::from([("lancedb.describe.format".into(), "json".into())]), + ); + RecordBatch::try_new( + Arc::new(schema), + vec![Arc::new(StringArray::from(vec![document.to_string()]))], + ) + .unwrap() +} + fn parameter_row() -> RecordBatch { let vector = FixedSizeListArray::from_iter_primitive::( [Some([0.1_f32, 1e-45, -0.0].map(Some))], @@ -730,6 +905,106 @@ async fn parameters_travel_on_one_exchange() { assert_eq!(headers[0].api_key, "test-key"); } +#[tokio::test] +async fn running_job_backed_queries_expose_their_own_durable_job_id() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + + let first = client + .execute(ExecuteQueryRequest::new("SELECT durable job first")) + .await + .unwrap(); + let second = client + .execute(ExecuteQueryRequest::new("SELECT durable job second")) + .await + .unwrap(); + assert_eq!(first.job_id(), None); + assert_eq!(second.job_id(), None); + + let first_description = first.describe().await.unwrap(); + let second_description = second.describe().await.unwrap(); + assert_eq!(first_description.status, QueryStatus::Running); + assert_eq!(first_description.job_id.as_deref(), Some("job-first")); + assert_eq!(second_description.status, QueryStatus::Running); + assert_eq!(second_description.job_id.as_deref(), Some("job-second")); + assert_ne!(first.id(), second.id()); + assert_ne!(first_description.job_id, second_description.job_id); + + let reader = first.reader().await.unwrap(); + assert_eq!( + reader + .schema() + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .map(String::as_str), + Some("job-first") + ); + assert_eq!(first.job_id().as_deref(), Some("job-first")); + assert_eq!(second.job_id().as_deref(), Some("job-second")); + + let reader_only = client + .execute(ExecuteQueryRequest::new("SELECT durable job reader-only")) + .await + .unwrap(); + let reader_only_result = reader_only.reader().await.unwrap(); + assert_eq!( + reader_only_result + .schema() + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .map(String::as_str), + Some("job-reader-only") + ); + + let ordinary = client + .execute(ExecuteQueryRequest::new("SELECT ordinary")) + .await + .unwrap(); + assert_eq!(ordinary.describe().await.unwrap().job_id, None); +} + +#[tokio::test] +async fn direct_job_backed_queries_expose_the_initial_response_job_id() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let query = client + .execute(ExecuteQueryRequest::new("SELECT direct durable job direct")) + .await + .unwrap(); + + assert_eq!(query.job_id().as_deref(), Some("job-direct")); + assert_eq!( + query.describe().await.unwrap().job_id.as_deref(), + Some("job-direct") + ); + let reader = query.reader().await.unwrap(); + assert_eq!( + reader + .schema() + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .map(String::as_str), + Some("job-direct") + ); + let batches = reader.try_collect::>().await.unwrap(); + assert_eq!(batches.len(), 1); + assert_eq!( + batches[0] + .schema() + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .map(String::as_str), + Some("job-direct") + ); +} + /// The server plans before it answers, so a refusal is the submission's. #[tokio::test] async fn a_refused_statement_fails_its_submission() { @@ -849,13 +1124,26 @@ async fn an_abandoned_reader_leaves_the_rows_for_the_next_one() { async fn a_reader_that_times_out_reports_the_failure() { let mut client_config = ClientConfig::default(); client_config.timeout_config.timeout = Some(Duration::from_millis(200)); - let (client, _shutdown) = start_sql_service(TestSqlService::default(), client_config).await; + let service = TestSqlService::default(); + let drops = service.exchange_drops.clone(); + let (client, _shutdown) = start_sql_service(service, client_config).await; - let stalled = client - .execute(parameterized("SELECT exchange stall", parameter_row())) - .await - .unwrap(); + // Real loopback I/O must finish before the clock can advance to the timeout. + // A blocking task inhibits Tokio's automatic clock advance during submission. + tokio::time::pause(); + let submission_client = client.clone(); + let stalled = tokio::task::spawn_blocking(move || { + tokio::runtime::Handle::current().block_on( + submission_client.execute(parameterized("SELECT exchange stall", parameter_row())), + ) + }) + .await + .unwrap() + .unwrap(); + assert_eq!(drops.load(Ordering::SeqCst), 0); assert_overall_timeout(stalled.reader().await, "result"); + tokio::time::resume(); + wait_for(&drops, 1, "a timed-out reader must end the call").await; let Err(retried) = stalled.reader().await else { panic!("the rows are gone, so a second reader cannot succeed"); }; @@ -928,6 +1216,61 @@ async fn catalog_connections_use_explicit_sql_endpoint_and_database_scope() { server.await.unwrap().unwrap(); } +#[tokio::test] +async fn remote_query_builder_sends_the_complete_query() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let incoming = futures::stream::try_unfold(listener, |listener| async { + let (socket, _) = listener.accept().await?; + Ok::<_, std::io::Error>(Some((socket, listener))) + }); + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(FlightServiceServer::new(service)) + .serve_with_incoming_shutdown(incoming, async { + let _ = shutdown_rx.await; + }), + ); + let connection = crate::connect("db://analytics") + .region("us-east-1") + .api_key("test-key") + .host_override("http://127.0.0.1:1") + .sql_host_override(&format!("grpc://{address}")) + .execute() + .await + .unwrap(); + for query in [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ] { + connection + .create_materialized_view_from_query("result", query) + .auto_refresh_enabled(false) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + statements.lock().unwrap().last().unwrap(), + &format!( + "CREATE MATERIALIZED VIEW \"result\" WITH (auto_refresh_enabled = false) AS {query}" + ) + ); + } + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + #[tokio::test] async fn remote_create_uses_sql_and_preserves_options_and_namespace() { for defer in [false, true] { @@ -944,17 +1287,39 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { panic!("CREATE must use SQL, not REST: {}", request.url().path()); }) .with_sql_client(sql_client.clone()); - for (enabled, interval, expected) in [ - (None, None, ""), - (Some(true), None, " WITH (auto_refresh_enabled = true)"), + for (enabled, interval, cpu, gpu, expected) in [ + (None, None, None, None, ""), + ( + Some(true), + None, + None, + None, + " WITH (auto_refresh_enabled = true)", + ), ( Some(false), Some(0.5), + None, + None, " WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 0.5)", ), + ( + None, + None, + Some(8000), + Some(0), + " WITH (total_cpu_millis = 8000, total_gpu_count = 0)", + ), ] { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: cpu, + total_memory_bytes: None, + total_gpu_count: gpu, + + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -982,7 +1347,7 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { ); } assert_eq!(count.load(Ordering::SeqCst), 0); - assert_eq!(statements.lock().unwrap().len(), 3); + assert_eq!(statements.lock().unwrap().len(), 4); assert!( headers .lock() @@ -1037,6 +1402,13 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1064,6 +1436,159 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry_job() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + materialized_view_job_handle_supported: true, + ..Default::default() + }; + let statement = "CREATE MATERIALIZED VIEW IF NOT EXISTS \"adults\" AS SELECT * FROM people"; + service.result_overrides.lock().unwrap().insert( + statement.into(), + RecordBatch::try_from_iter([ + ( + "status", + Arc::new(StringArray::from(vec!["already_exists"])) as arrow_array::ArrayRef, + ), + ( + "job_id", + Arc::new(StringArray::from(vec![""])) as arrow_array::ArrayRef, + ), + ]) + .unwrap(), + ); + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!( + "a skipped creation must not poll a registry job: {}", + request.url() + ); + }) + .with_sql_client(client); + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + + exist_ok: true, + name: "adults".into(), + namespace_path: vec!["team".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + }) + .await + .unwrap(); + if defer { + assert!(job.id().is_none()); + } else { + assert_eq!(job.job_type().as_deref(), Some("query")); + } + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert_eq!(*statements.lock().unwrap(), [statement]); + shutdown.send(()).unwrap(); + } +} + +#[rstest::rstest] +#[case::submitted("submitted", " job-1 ", Ok(Some(" job-1 ")), Ok(Some(" job-1 ")))] +#[case::blank_id("submitted", " \t ", Err("blank job_id"), Err("blank job_id"))] +#[case::missing_id("submitted", "", Err("returned no job_id"), Err("returned no job_id"))] +#[case::already_exists("already_exists", "", Ok(None), Err("create-only already_exists"))] +#[case::malformed_noop("already_exists", " \t ", Err("blank job_id"), Err("blank job_id"))] +#[tokio::test] +async fn remote_materialized_view_receipt_with_empty_batches( + #[case] status: &str, + #[case] job_id: &str, + #[case] expected_create: std::result::Result, &str>, + #[case] expected_refresh: std::result::Result, &str>, +) { + let row = RecordBatch::try_from_iter([ + ( + "status", + Arc::new(StringArray::from(vec![status])) as ArrayRef, + ), + ( + "job_id", + Arc::new(StringArray::from(vec![job_id])) as ArrayRef, + ), + ]) + .unwrap(); + let empty = row.slice(0, 0); + // FlightDataEncoderBuilder skips zero-row batches. Encode them explicitly on the wire. + let frames = + arrow_flight::utils::batches_to_flight_data(&row.schema(), vec![empty.clone(), row, empty]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + materialized_view_job_handle_supported: true, + result_frames: Some(frames), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|r| -> http::Response { + panic!("unexpected HTTP request during create: {}", r.url()) + }) + .with_sql_client(sql.clone()); + let table = receipt_test_table(sql); + let create = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "events".into(), + namespace_path: vec!["team".into()], + query: "SELECT * FROM people".into(), + exist_ok: true, + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + gpu_class: None, + gpu_count: None, + }) + .await; + let refresh = table.refresh_materialized_view_async(None, false).await; + for (operation, actual, expected) in [ + ( + "CREATE", + create.as_ref().map(|job| job.id()), + expected_create, + ), + ( + "REFRESH", + refresh.as_ref().map(|job| job.id()), + expected_refresh, + ), + ] { + match expected { + Ok(id) => assert_eq!(actual.unwrap(), id, "{operation}"), + Err(message) => { + let err = actual.unwrap_err().to_string(); + assert!(err.contains(message), "{operation}: {err}"); + } + } + } + assert_eq!( + *statements.lock().unwrap(), + [ + r#"CREATE MATERIALIZED VIEW IF NOT EXISTS "events" AS SELECT * FROM people"#, + r#"REFRESH MATERIALIZED VIEW "events""#, + ] + ); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn remote_create_registry_handle_reopens_describes_and_cancels() { let service = TestSqlService { @@ -1129,6 +1654,13 @@ async fn remote_create_registry_handle_reopens_describes_and_cancels() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + gpu_class: Default::default(), + gpu_count: Default::default(), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1213,6 +1745,36 @@ async fn function_failure_preserves_the_isolated_sql_job_id() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn fast_durable_job_failure_exposes_the_same_job_id_on_the_query_handle() { + let (client, shutdown) = start_sql_service( + TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }, + ClientConfig::default(), + ) + .await; + let query = client + .execute(ExecuteQueryRequest { + query: "SELECT durable job failure".into(), + default_namespace_path: vec![], + parameters: None, + options: Default::default(), + }) + .await + .unwrap(); + assert_eq!(query.job_id(), None); + + let Err(Error::JobFailed { job_id, .. }) = collect_result(&query).await else { + panic!("a failed durable query must remain a structured JobFailed error"); + }; + assert_eq!(job_id.as_deref(), Some("job-1")); + assert_eq!(query.job_id().as_deref(), Some("job-1")); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn rejected_job_cancellation_does_not_abort_sql_completion() { let service = TestSqlService { @@ -1250,17 +1812,8 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { let (socket, _) = listener.accept().await?; Ok::<_, std::io::Error>(Some((socket, listener))) }); - let result = RecordBatch::try_from_iter(vec![ - ( - "name", - Arc::new(StringArray::from(vec!["view"])) as ArrayRef, - ), - ( - "query", - Arc::new(StringArray::from(vec!["SELECT * FROM source"])) as ArrayRef, - ), - ]) - .unwrap(); + let result = + description_batch(serde_json::json!({"name":"view", "query":"SELECT * FROM source"})); let service = TestSqlService { result, ..Default::default() @@ -1329,7 +1882,30 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { .await .unwrap(); - for result in [first, second] { + let third = view + .refresh() + .full(true) + .total_cpu_millis(8000) + .total_memory_bytes(16 << 30) + .total_gpu_count(2) + .gpu_class("h100") + .gpu_count(2) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + for invalid in [ + view.refresh().gpu_class("H200:8"), + view.refresh().total_gpu_count(0).gpu_class("h100"), + ] { + assert!(matches!( + invalid.execute_async().await, + Err(Error::InvalidInput { .. }) + )); + } + for result in [first, second, third] { assert_eq!(result.mode, None); assert_eq!(result.rows_written, None); assert_eq!(result.source_version, None); @@ -1347,9 +1923,10 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { assert_eq!( *statements.lock().unwrap(), [ - "DESCRIBE MATERIALIZED VIEW \"view\"", + "DESCRIBE MATERIALIZED VIEW \"view\" FORMAT JSON", "REFRESH MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true)", + "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true, total_cpu_millis = 8000, total_memory_bytes = 17179869184, total_gpu_count = 2, gpu_class = 'h100', gpu_count = 2)", ] ); assert!( @@ -1529,10 +2106,12 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { .delay_next .store(true, Ordering::SeqCst); assert_overall_timeout(collect_result(&timeout_query).await, "result"); - timeout_header_provider - .delay_next - .store(true, Ordering::SeqCst); - assert_overall_timeout(timeout_query.cancel().await, "cancellation"); + wait_for( + &cancel_count, + 1, + "the overall timeout must cancel execution", + ) + .await; timeout_query.cancel().await.unwrap(); let pre_dispatch_timeout = timeout_client @@ -1819,6 +2398,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { flight_descriptor: Some(FlightDescriptor::new_cmd("restored")), ..Default::default() }, + None, ) .unwrap(), ); @@ -1937,7 +2517,14 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { .submit("SELECT fail", &["public".to_string()]) .await .unwrap(); + let before_failure = cancel_count.load(Ordering::SeqCst); assert!(collect_result(&failed).await.is_err()); + wait_for( + &cancel_count, + before_failure + 1, + "failed result reads must cancel execution", + ) + .await; let registry = QueryRegistry::new(); for descriptor in ["active-one", "active-two"] { @@ -1951,6 +2538,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { flight_descriptor: Some(FlightDescriptor::new_cmd(descriptor)), ..Default::default() }, + None, ) .unwrap(), ); @@ -1972,6 +2560,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { expiration_time: Some(Default::default()), ..Default::default() }, + None, ) .unwrap(), ); @@ -1988,6 +2577,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { flight_descriptor: Some(FlightDescriptor::new_cmd("stale")), ..Default::default() }, + None, ) .unwrap(), ); @@ -1999,7 +2589,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { assert_eq!(client.initialized_client_count().await, 1); assert_eq!(query_count.load(Ordering::SeqCst), 21); assert_eq!(do_get_count.load(Ordering::SeqCst), 17); - assert_eq!(cancel_count.load(Ordering::SeqCst), 15); + assert_eq!(cancel_count.load(Ordering::SeqCst), 16); assert_eq!(first_result, vec![expected.clone()]); assert!(empty_result.is_empty()); assert!(client.describe(Uuid::nil()).await.is_err()); @@ -2318,7 +2908,7 @@ async fn remote_optimize_submits_a_compaction_job_over_sql() { assert!(stats.prune.is_none()); assert_eq!( *statements.lock().unwrap(), - ["OPTIMIZE TABLE \"events\" REWRITE DATA"] + ["OPTIMIZE \"events\" REWRITE DATA"] ); assert!( headers @@ -2362,7 +2952,7 @@ async fn remote_optimize_on_a_branch_submits_a_with_clause_over_sql() { assert_eq!( *statements.lock().unwrap(), - ["OPTIMIZE TABLE \"events\" REWRITE DATA WITH (branch = 'o''brien')"] + ["OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'o''brien')"] ); shutdown.send(()).unwrap(); } @@ -2426,7 +3016,7 @@ async fn remote_optimize_full_skips_prune_and_index() { ); assert_eq!( *statements.lock().unwrap(), - ["OPTIMIZE TABLE \"events\" REWRITE DATA"] + ["OPTIMIZE \"events\" REWRITE DATA"] ); shutdown.send(()).unwrap(); } @@ -2537,25 +3127,54 @@ async fn remote_optimize_full_rejects_explicit_pruning_options() { assert_rejected_before_submission(None, None, Some(true)).await; } +fn sql_listing_batch(column: &str, values: &[&str], token: Option<&str>) -> RecordBatch { + let mut columns: Vec<(&str, ArrayRef)> = Vec::new(); + if column == "name" { + columns.push(( + "namespace_path", + Arc::new(StringArray::from(vec![ + r#"["team","reports"]"#; + values.len() + ])), + )); + } + columns.push((column, Arc::new(StringArray::from(values.to_vec())))); + let batch = RecordBatch::try_from_iter(columns).unwrap(); + let metadata = token + .map(|token| HashMap::from([("lancedb.next_page_token".to_owned(), token.to_owned())])) + .unwrap_or_default(); + let schema = Arc::new(batch.schema().as_ref().clone().with_metadata(metadata)); + RecordBatch::try_new(schema, batch.columns().to_vec()).unwrap() +} + #[tokio::test] -async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { +async fn remote_mv_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["a", "b'c", "z"])) as ArrayRef, - )]) - .unwrap(); + let token = "server'opaque:token"; + let next_sql = + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); let headers = service.headers.clone(); - let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; - let db = RemoteDatabase::new_mock(|request| -> http::Response { - panic!("unexpected REST request: {}", request.url().path()); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; @@ -2566,41 +3185,31 @@ async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { ) .await .unwrap(); - assert_eq!(first.items, ["a", "b'c"]); - let token = first.page_token.unwrap(); - db.list_materialized_views( - &namespace, - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(&token), - ) - .await - .unwrap(); + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db + .list_materialized_views( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(second.items, ["z"]); + assert!(second.page_token.is_none()); assert_eq!( *statements.lock().unwrap(), [ - "SHOW MATERIALIZED VIEWS LIMIT 3", - "SHOW MATERIALIZED VIEWS WHERE name > 'b''c' LIMIT 3" + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2", + next_sql ] ); - assert!( - headers - .lock() - .unwrap() - .iter() - .all(|header| header.namespace_path == "team$reports") - ); - for (path, token) in [(vec![], token), (namespace, "invalid".into())] { - assert!(matches!( - db.list_materialized_views( - &path, - crate::listing::ListingOptions::default().page_token(token) - ) - .await, - Err(Error::InvalidInput { .. }) - )); + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } @@ -2609,11 +3218,8 @@ async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { async fn remote_describe_materialized_view_preserves_the_sql_definition() { for defer in [false, true] { let definition = "SELECT s.x, d.label FROM source s JOIN dim d ON s.id = d.id"; - let result = RecordBatch::try_from_iter(vec![( - "query", - Arc::new(StringArray::from(vec![definition])) as ArrayRef, - )]) - .unwrap(); + let result = + description_batch(serde_json::json!({"name":"daily_sales", "query":definition})); let service = TestSqlService { adaptive: true, defer, @@ -2638,7 +3244,7 @@ async fn remote_describe_materialized_view_preserves_the_sql_definition() { assert!(info.parsed_definition.is_none()); assert_eq!( *statements.lock().unwrap(), - ["DESCRIBE MATERIALIZED VIEW \"daily_sales\""] + ["DESCRIBE MATERIALIZED VIEW \"daily_sales\" FORMAT JSON"] ); shutdown.send(()).unwrap(); } @@ -2676,6 +3282,10 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() result: RecordBatch::try_from_iter(columns.clone()).unwrap(), adaptive: true, defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([( + "DESCRIBE STORAGE INTEGRATION \"raw\" FORMAT JSON".into(), + description_batch(info.clone()), + )]))), ..Default::default() }; let statements = service.statements.clone(); @@ -2703,13 +3313,14 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() created.trust_policy["Statement"][0]["Condition"]["StringEquals"]["sts:ExternalId"], created.aws_external_id ); + let described = database + .describe_storage_integration("raw", &namespace) + .await + .unwrap(); + assert_eq!(described.aws_external_id, created.aws_external_id); assert_eq!( - database - .describe_storage_integration("raw", &namespace) - .await - .unwrap() - .aws_external_id, - created.aws_external_id + serde_json::to_value(&described).unwrap(), + serde_json::to_value(&created).unwrap() ); assert_eq!( database @@ -2740,8 +3351,14 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() .unwrap(); let statements = statements.lock().unwrap(); assert!(statements[0].contains("STORAGE_AWS_REGION = 'us-east-1'")); - assert_eq!(statements[1], "DESCRIBE STORAGE INTEGRATION \"raw\""); - assert_eq!(statements[2], "SHOW STORAGE INTEGRATIONS"); + assert_eq!( + statements[1], + "DESCRIBE STORAGE INTEGRATION \"raw\" FORMAT JSON" + ); + assert_eq!( + statements[2], + "SHOW STORAGE INTEGRATIONS IN \"platform$aws\" LIMIT 1000" + ); assert_eq!(statements[3], "DROP STORAGE INTEGRATION \"raw\""); assert!(statements[4].contains( "STORAGE_AWS_ACCESS_KEY_ID_SECRET = \"platform/raw\".\"credentials\".\"key\"" @@ -2765,9 +3382,22 @@ async fn function_creation_and_description_use_sql_query_handles() { const REQUEST: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" ); - for (defer, with_models) in [(false, false), (false, true), (true, false), (true, true)] { + for (defer, with_models, exist_ok) in [ + (false, false, false), + (false, true, false), + (true, false, false), + (true, true, false), + (false, false, true), + (false, true, true), + (true, false, true), + (true, true, true), + ] { let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); request_json["batch_size"] = serde_json::json!(2); + request_json["max_concurrency"] = serde_json::json!(4); + request_json["total_cpu_millis"] = serde_json::json!(8000); + request_json["total_memory_bytes"] = serde_json::json!(17179869184_u64); + request_json["total_gpu_count"] = serde_json::json!(0); request_json["row_timeout_seconds"] = serde_json::json!(0.75); request_json["secret_bindings"] = serde_json::json!([{ "kind": "env", @@ -2775,6 +3405,50 @@ async fn function_creation_and_description_use_sql_query_handles() { "secret_ref": {"name": "hf-prod"}, }]); let mut version_json: serde_json::Value = serde_json::from_str(VERSION).unwrap(); + version_json["batch_size"] = serde_json::json!(12); + for field in ["total_cpu_millis", "total_memory_bytes", "total_gpu_count"] { + version_json[field] = request_json[field].clone(); + } + version_json["max_concurrency"] = serde_json::json!(4); + version_json["row_timeout_seconds"] = serde_json::json!(8.0); + version_json["result_stability"] = serde_json::json!("input_and_context"); + version_json["runtime"] = request_json["runtime"].clone(); + let requested_index_url = "https://requested.example/simple/"; + version_json["runtime"]["environment"]["build"] = serde_json::json!({ + "index_url": requested_index_url, + "find_links": ["https://downloads.example/wheels"], + }); + version_json["resolved_environment"] = serde_json::json!({ + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + }, + { + "name": "transformers", + "version": "4.57.1" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "configured_find_links": [], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "transformers resolved to transformers==4.57.1 but is not pinned exactly; add transformers==4.57.1 to pin it." + ] + }); + version_json["resolved_environments"] = serde_json::json!({ + "linux/amd64": { + "packages": [{"name": "torch", "version": "2.9.0+cu130"}] + }, + "linux/arm64": { + "packages": [] + } + }); if with_models { let models = serde_json::json!([{ "repo": "sentence-transformers/all-MiniLM-L6-v2", @@ -2786,9 +3460,11 @@ async fn function_creation_and_description_use_sql_query_handles() { let expected_models = version_json["image"].get("models"); let mut expected_request = request_json.clone(); expected_request.as_object_mut().unwrap().remove("name"); - let request = + let mut request = crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) .unwrap(); + assert!(!request.exist_ok); + request.exist_ok = exist_ok; let result = RecordBatch::try_from_iter(vec![( "definition", Arc::new(StringArray::from(vec![version_json.to_string()])) as ArrayRef, @@ -2798,6 +3474,16 @@ async fn function_creation_and_description_use_sql_query_handles() { adaptive: true, defer, result, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "DESCRIBE FUNCTION \"embed\" WITH (version = '1') FORMAT JSON".into(), + description_batch(version_json.clone()), + ), + ( + "DESCRIBE FUNCTION \"embed\" FORMAT JSON".into(), + description_batch(version_json.clone()), + ), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -2815,12 +3501,33 @@ async fn function_creation_and_description_use_sql_query_handles() { let created = job.wait().await.unwrap(); assert_eq!(created.name(), "embed"); assert_eq!(created.version(), "1"); + assert_eq!(created.batch_size(), Some(12)); + assert_eq!(created.total_cpu_millis(), Some(8000)); + assert_eq!(created.total_memory_bytes(), Some(17179869184)); + assert_eq!(created.total_gpu_count(), Some(0)); + assert_eq!(created.max_concurrency(), Some(4)); + assert_eq!(created.row_timeout_seconds(), Some(8.0)); + assert_eq!(created.result_stability(), Some("input_and_context")); + assert_eq!(created.runtime().unwrap().kind(), "python"); + assert_eq!( + created.resolved_environment().unwrap().packages[0].version, + "2.9.0+cu130" + ); + assert_eq!(created.resolved_environments().len(), 2); + assert!( + created.resolved_environments()["linux/arm64"] + .packages + .is_empty() + ); // Assert the actual SQL body, after the same native JSON decode used // by the Python binding, rather than only the Python declaration. { let seen = statements.lock().unwrap(); let encoded = seen[0] - .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .strip_prefix(&format!( + "CREATE FUNCTION{} \"normalize_score\" FROM '", + if exist_ok { " IF NOT EXISTS" } else { "" } + )) .unwrap() .strip_suffix('\'') .unwrap(); @@ -2831,6 +3538,27 @@ async fn function_creation_and_description_use_sql_query_handles() { let created_json: serde_json::Value = serde_json::from_str(&created.to_canonical_json().unwrap()).unwrap(); assert_eq!(created_json["image"].get("models"), expected_models); + assert_eq!(created_json["batch_size"], 12); + assert_eq!(created_json["max_concurrency"], 4); + assert_eq!(created_json["row_timeout_seconds"], 8.0); + assert_eq!(created_json["result_stability"], "input_and_context"); + assert_eq!( + created_json["resolved_environment"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert!( + created_json["resolved_environment"]["packages"][1] + .get("source") + .is_none() + ); + assert_eq!( + created_json["resolved_environments"]["linux/amd64"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert_eq!( + created_json["resolved_environments"]["linux/arm64"]["packages"], + serde_json::json!([]) + ); assert_eq!( client.describe(id).await.unwrap().status, QueryStatus::Finished @@ -2840,19 +3568,133 @@ async fn function_creation_and_description_use_sql_query_handles() { .await .unwrap(); assert_eq!(described.name(), "embed"); + assert_eq!(described.batch_size(), Some(12)); + assert_eq!(described.max_concurrency(), Some(4)); + assert_eq!(described.row_timeout_seconds(), Some(8.0)); + assert_eq!(described.result_stability(), Some("input_and_context")); + assert_eq!(described.runtime().unwrap().kind(), "python"); + assert_eq!(described.requested_index_url(), Some(requested_index_url)); + assert_eq!( + described + .resolved_environment() + .unwrap() + .provenance + .as_ref() + .unwrap() + .torch_version + .as_deref(), + Some("torch==2.9.0+cu130") + ); + assert_eq!(described.resolved_environments().len(), 2); let described_json: serde_json::Value = serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap(); assert_eq!(described_json["image"].get("models"), expected_models); + assert_eq!(described_json["batch_size"], 12); + assert_eq!(described_json["max_concurrency"], 4); + assert_eq!(described_json["row_timeout_seconds"], 8.0); + assert_eq!(described_json["result_stability"], "input_and_context"); + assert_eq!( + described_json["runtime"]["environment"]["build"], + serde_json::json!({"index_url": requested_index_url}) + ); + assert_eq!( + described_json["resolved_environment"]["provenance"]["configured_index_urls"], + serde_json::json!(["https://packages.example/simple"]) + ); + let latest = db + .get_function_latest("embed", &["team".into()]) + .await + .unwrap(); + assert_eq!(latest.name(), "embed"); + assert_eq!(latest.version(), "1"); + assert_eq!(latest.batch_size(), Some(12)); let listed = db .list_functions(&["team".into()], Default::default()) .await .unwrap(); assert_eq!(listed.items.len(), 1); + assert_eq!(listed.items[0].batch_size(), Some(12)); + assert_eq!(listed.items[0].max_concurrency(), Some(4)); + assert_eq!(listed.items[0].row_timeout_seconds(), Some(8.0)); + assert_eq!( + listed.items[0].result_stability(), + Some("input_and_context") + ); + assert_eq!(listed.items[0].runtime().unwrap().kind(), "python"); + assert_eq!( + listed.items[0] + .resolved_environment() + .unwrap() + .warnings + .len(), + 1 + ); + assert_eq!(listed.items[0].resolved_environments().len(), 2); let listed_json: serde_json::Value = serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap(); assert_eq!(listed_json["image"].get("models"), expected_models); + assert_eq!(listed_json["batch_size"], 12); + assert_eq!(listed_json["max_concurrency"], 4); + assert_eq!(listed_json["row_timeout_seconds"], 8.0); + assert_eq!(listed_json["result_stability"], "input_and_context"); let seen = statements.lock().unwrap(); - assert_eq!(seen[1], "DESCRIBE FUNCTION \"embed\" WITH (version = '1')"); + assert_eq!( + seen[1], + "DESCRIBE FUNCTION \"embed\" WITH (version = '1') FORMAT JSON" + ); + assert_eq!(seen[2], "DESCRIBE FUNCTION \"embed\" FORMAT JSON"); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn function_creation_refresh_lock_is_forwarded_only_when_true() { + const VERSION: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + const REQUEST: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" + ); + for (refresh_lock, expect_field) in [(false, false), (true, true)] { + let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); + if refresh_lock { + request_json["refresh_lock"] = serde_json::json!(true); + } + let request = + crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) + .unwrap(); + assert_eq!(request.refresh_lock, refresh_lock); + let result = RecordBatch::try_from_iter(vec![( + "definition", + Arc::new(StringArray::from(vec![VERSION.to_string()])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: false, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client.clone()); + let job = db.create_function_async(request, &[]).await.unwrap(); + job.wait().await.unwrap(); + let seen = statements.lock().unwrap(); + let encoded = seen[0] + .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .unwrap() + .strip_suffix('\'') + .unwrap(); + let sent: serde_json::Value = serde_json::from_str(&encoded.replace("''", "'")).unwrap(); + assert_eq!(sent.get("refresh_lock").is_some(), expect_field); + if expect_field { + assert_eq!(sent["refresh_lock"], serde_json::json!(true)); + } + drop(seen); shutdown.send(()).unwrap(); } } @@ -2883,6 +3725,13 @@ async fn function_creation_rejects_invalid_execution_controls_before_sql() { request.batch_size = Some(0); let error = db.create_function_async(request, &[]).await.unwrap_err(); assert!(matches!(error, Error::InvalidInput { message } if message.contains("batch_size"))); + + let mut request = crate::function::FunctionRegistrationRequest::from_json(REQUEST).unwrap(); + request.max_concurrency = Some(0); + let error = db.create_function_async(request, &[]).await.unwrap_err(); + assert!( + matches!(error, Error::InvalidInput { message } if message.contains("max_concurrency")) + ); assert!(statements.lock().unwrap().is_empty()); shutdown.send(()).unwrap(); } @@ -2920,6 +3769,45 @@ async fn function_drop_keeps_the_query_id_and_reports_catalog_removal() { } } +#[tokio::test] +async fn function_drop_decodes_server_warnings_for_the_binding_bridge() { + let mut warning_values = ListBuilder::new(StringBuilder::new()); + warning_values + .values() + .append_value("materialized view \"pinned\" references Function \"embed\" version \"1\""); + warning_values.append(true); + let result = RecordBatch::try_from_iter(vec![ + ( + "status", + Arc::new(StringArray::from(vec!["dropped"])) as ArrayRef, + ), + ("warnings", Arc::new(warning_values.finish()) as ArrayRef), + ]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + result, + ..Default::default() + }; + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + + let (dropped, warnings) = db + .drop_function_with_warnings("embed", "1", &[]) + .await + .unwrap(); + assert!(dropped); + assert_eq!( + warnings, + ["materialized view \"pinned\" references Function \"embed\" version \"1\""] + ); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { for defer in [false, true] { @@ -2930,29 +3818,55 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { }; let exchanges = service.exchanges.clone(); let statements = service.statements.clone(); + let headers = service.headers.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|request| -> http::Response { panic!("unexpected REST request: {}", request.url().path()); }) .with_sql_client(client); - db.create_secret("api-key", "credential's value", &["team".into()]) + let connection = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + connection + .create_secret("api-key", "credential's value", &["team".into()]) .await .unwrap(); - db.alter_secret("api-key", "rotated-value", &["team".into()]) + connection + .create_secret("api-key", "ignored-value", &["team".into()]) + .exist_ok(true) + .await + .unwrap(); + connection + .alter_secret("api-key", "rotated-value", &["team".into()]) + .await + .unwrap(); + connection + .drop_secret("api-key", &["team".into()]) .await .unwrap(); - db.drop_secret("api-key", &["team".into()]).await.unwrap(); assert_eq!( statements.lock().unwrap().as_slice(), ["DROP SECRET IF EXISTS \"api-key\""] ); let seen = exchanges.lock().unwrap(); - assert_eq!(seen.len(), 2); + assert_eq!(seen.len(), 3); assert_eq!( seen[0].0, "CREATE SECRET \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" ); - assert_eq!(seen[1].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert_eq!( + seen[1].0, + "CREATE SECRET IF NOT EXISTS \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" + ); + assert_eq!(seen[2].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); assert_eq!( seen[0] .1 @@ -2975,6 +3889,18 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { .downcast_ref::() .unwrap() .value(0), + "ignored-value" + ); + assert_eq!( + seen[2] + .1 + .as_ref() + .unwrap() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), "rotated-value" ); shutdown.send(()).unwrap(); @@ -2982,27 +3908,16 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { } #[tokio::test] async fn secret_description_uses_the_sql_metadata_projection() { - let result = RecordBatch::try_from_iter(vec![ - ( - "name", - Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, - ), - ( - "created_at_millis", - Arc::new(arrow_array::Int64Array::from(vec![1])) as ArrayRef, - ), - ( - "updated_at_millis", - Arc::new(arrow_array::Int64Array::from(vec![2])) as ArrayRef, - ), - ]) - .unwrap(); + let result = description_batch( + serde_json::json!({"name":"api-key", "created_at_millis":1, "updated_at_millis":2, "history":[]}), + ); let service = TestSqlService { adaptive: true, defer: true, result, ..Default::default() }; + let statements = service.statements.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { panic!("unexpected REST request"); @@ -3011,33 +3926,28 @@ async fn secret_description_uses_the_sql_metadata_projection() { let info = db.describe_secret("api-key", &[]).await.unwrap(); assert_eq!(info.name, "api-key"); assert_eq!(info.updated_at_millis, 2); + assert_eq!( + *statements.lock().unwrap(), + ["DESCRIBE SECRET \"api-key\" FORMAT JSON"] + ); shutdown.send(()).unwrap(); } #[tokio::test] -async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { +async fn secret_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let first_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["api-key", "hf'prod", "openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let second_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ - ("SHOW SECRETS LIMIT 3".to_string(), first_result), - ( - "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3".to_string(), - second_result, - ), - ]))); + let token = "server'opaque:token"; + let next_sql = "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result_overrides, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -3049,11 +3959,10 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { ) .await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - let first = db .list_secrets( &namespace, @@ -3061,90 +3970,144 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { ) .await .unwrap(); - assert_eq!(first.items, ["api-key", "hf'prod"]); - let token = first.page_token.expect("a third row must produce a token"); - + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); let second = db .list_secrets( &namespace, crate::listing::ListingOptions::default() .page_limit(2) - .page_token(&token), + .page_token(first.page_token.unwrap()), ) .await .unwrap(); - assert_eq!(second.items, ["openai-prod"]); + assert_eq!(second.items, ["z"]); assert!(second.page_token.is_none()); - assert_eq!( *statements.lock().unwrap(), - [ - "SHOW SECRETS LIMIT 3", - "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3" - ] + ["SHOW SECRETS IN \"team$reports\" LIMIT 2", next_sql] ); - { - let headers = headers.lock().unwrap(); - assert!(!headers.is_empty()); - for header in headers.iter() { - assert_eq!(header.database, "analytics"); - assert_eq!(header.database_prefix, "tenant/production"); - assert_eq!(header.namespace_path, "team$reports"); - } + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - - for (path, token) in [ - (vec!["other".to_owned()], token), - (namespace.clone(), "invalid".to_owned()), - ] { - assert!(matches!( - db.list_secrets( - &path, - crate::listing::ListingOptions::default().page_token(token) - ) - .await, - Err(Error::InvalidInput { .. }) - )); - } - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } #[tokio::test] -async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() { - let empty = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(Vec::::new())) as ArrayRef, - )]) - .unwrap(); +async fn storage_integration_listing_uses_server_continuation_tokens() { + for defer in [false, true] { + let token = "server'opaque:token"; + let next_sql = + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; + let service = TestSqlService { + adaptive: true, + defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") + }) + .with_sql_client(client); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + let first = db + .list_storage_integrations( + &namespace, + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db + .list_storage_integrations( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(second.items, ["z"]); + assert!(second.page_token.is_none()); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2", + next_sql + ] + ); + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); + } + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn secret_listing_preserves_empty_continuations_and_validates_page_options() { let service = TestSqlService { adaptive: true, defer: true, - result: empty, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &[], Some("continue-empty")), + ), + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'continue-empty'".to_owned(), + sql_listing_batch("name", &["last"], None), + ), + ]))), ..Default::default() }; let statements = service.statements.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - let page = db .list_secrets( &namespace, - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(""), + crate::listing::ListingOptions::default().page_limit(2), ) .await .unwrap(); assert!(page.items.is_empty()); - assert!(page.page_token.is_none()); - - for limit in [0, i32::MAX as u32 + 1] { + assert_eq!(page.page_token.as_deref(), Some("continue-empty")); + let last = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(page.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(last.items, ["last"]); + assert!(last.page_token.is_none()); + for limit in [10_001, u32::MAX] { assert!(matches!( db.list_secrets( &namespace, @@ -3154,12 +4117,29 @@ async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() { Err(Error::InvalidInput { .. }) )); } - assert_eq!(*statements.lock().unwrap(), ["SHOW SECRETS LIMIT 3"]); + assert!( + db.list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_token("") + ) + .await + .is_err() + ); + let zero = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_limit(0), + ) + .await + .unwrap(); + assert!(zero.items.is_empty()); + assert!(zero.page_token.is_none()); + assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } #[tokio::test] -async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { +async fn function_listing_uses_server_tokens_for_numeric_revision_pages() { const VERSION: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" ); @@ -3169,74 +4149,65 @@ async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { let mut tenth: serde_json::Value = serde_json::from_str(VERSION).unwrap(); tenth["version"] = serde_json::json!("10"); let tenth = tenth.to_string(); - let result = RecordBatch::try_from_iter(vec![( - "definition", - Arc::new(StringArray::from(vec![ - VERSION, - second.as_str(), - tenth.as_str(), - ])) as ArrayRef, - )]) - .unwrap(); - let service = TestSqlService { - adaptive: true, - defer: true, - result, - ..Default::default() - }; - service.result_overrides.lock().unwrap().insert( - "SHOW FUNCTIONS HISTORY WITH (limit = 3, include_definition = true, after_name = 'embed', after_version = '2')".into(), - RecordBatch::try_from_iter(vec![("definition", Arc::new(StringArray::from(vec![tenth.as_str()])) as ArrayRef)]).unwrap(), - ); - let statements = service.statements.clone(); - let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; - let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); - }) - .with_sql_client(client); - let first = db - .list_functions( - &["team".into()], - crate::listing::ListingOptions::default().page_limit(2), - ) - .await - .unwrap(); - assert_eq!( - first - .items - .iter() - .map(|item| item.version()) - .collect::>(), - ["1", "2"] - ); - let token = first.page_token.unwrap(); - let second = db - .list_functions( - &["team".into()], - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(token.clone()), - ) - .await - .unwrap(); - assert_eq!(second.items.len(), 1); - assert_eq!(second.items[0].version(), "10"); - assert!(second.page_token.is_none()); - assert!( - db.list_functions( - &["other".into()], - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(token) - ) - .await - .is_err() - ); - let seen = statements.lock().unwrap(); - assert_eq!(seen.len(), 2); - assert!(seen[0].starts_with("SHOW FUNCTIONS HISTORY WITH (limit = 3,")); - assert!(seen[1].contains("after_version = '2'")); - shutdown.send(()).unwrap(); + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2".to_owned(), + sql_listing_batch("definition", &[VERSION, &second], Some("revision-cursor")), + ), + ( + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'".to_owned(), + sql_listing_batch("definition", &[&tenth], None), + ), + ]))), + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") + }) + .with_sql_client(client); + let first = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!( + first + .items + .iter() + .map(|item| item.version()) + .collect::>(), + ["1", "2"] + ); + assert_eq!(first.page_token.as_deref(), Some("revision-cursor")); + let last = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(last.items.len(), 1); + assert_eq!(last.items[0].version(), "10"); + assert!(last.page_token.is_none()); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2", + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'" + ] + ); + shutdown.send(()).unwrap(); + } } #[tokio::test] @@ -3262,29 +4233,58 @@ async fn view_create_and_describe_return_metadata_through_sql() { adaptive: true, defer, result, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([( + "DESCRIBE VIEW \"adults\" FORMAT JSON".into(), + description_batch( + serde_json::json!({"name":"adults", "query":"SELECT name FROM people", "schema":serde_json::from_str::(schema).unwrap()}), + ), + )]))), ..Default::default() }; let statements = service.statements.clone(); + let headers = service.headers.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { panic!("unexpected REST request"); }) .with_sql_client(client); - let created = db + let connection = Connection::new(Arc::new(db), Arc::new(MemoryRegistry::new())); + let created = connection .create_view("adults", "SELECT name FROM people", &["team".into()]) .await .unwrap(); - let described = db.describe_view("adults", &["team".into()]).await.unwrap(); + let existing = connection + .create_view( + "adults", + "SELECT replacement FROM other_people", + &["team".into()], + ) + .exist_ok(true) + .await + .unwrap(); + let described = connection + .describe_view("adults", &["team".into()]) + .await + .unwrap(); assert_eq!(created, described); + assert_eq!(existing, described); assert_eq!(created.schema.fields()[0].name(), "name"); assert_eq!(created.default_namespace_path, ["team"]); assert_eq!( statements.lock().unwrap().as_slice(), [ "CREATE VIEW \"adults\" AS SELECT name FROM people", - "DESCRIBE VIEW \"adults\"" + "CREATE VIEW IF NOT EXISTS \"adults\" AS SELECT replacement FROM other_people", + "DESCRIBE VIEW \"adults\" FORMAT JSON" ] ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); shutdown.send(()).unwrap(); } } @@ -3321,29 +4321,20 @@ async fn view_drop_uses_a_repeatable_query_job() { } #[tokio::test] -async fn view_listing_uses_bounded_sql_and_scoped_cursors() { +async fn view_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let first_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["adults", "hf'prod", "openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let second_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ - ("SHOW VIEWS LIMIT 3".to_string(), first_result), - ( - "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3".to_string(), - second_result, - ), - ]))); + let token = "server'opaque:token"; + let next_sql = "SHOW VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result_overrides, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW VIEWS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -3355,107 +4346,39 @@ async fn view_listing_uses_bounded_sql_and_scoped_cursors() { ) .await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); - let connection = Connection::new( - Arc::new(db), - Arc::new(crate::embeddings::MemoryRegistry::new()), - ); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - - let first = connection + let first = db .list_views( &namespace, crate::listing::ListingOptions::default().page_limit(2), ) - .next_page() .await - .unwrap() .unwrap(); - assert_eq!(first.items, ["adults", "hf'prod"]); - let token = first.page_token.expect("a third row must produce a token"); - - let second = connection + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db .list_views( &namespace, crate::listing::ListingOptions::default() .page_limit(2) - .page_token(&token), + .page_token(first.page_token.unwrap()), ) - .next_page() .await - .unwrap() .unwrap(); - assert_eq!(second.items, ["openai-prod"]); + assert_eq!(second.items, ["z"]); assert!(second.page_token.is_none()); - assert_eq!( *statements.lock().unwrap(), - [ - "SHOW VIEWS LIMIT 3", - "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3" - ] + ["SHOW VIEWS IN \"team$reports\" LIMIT 2", next_sql] ); - { - let headers = headers.lock().unwrap(); - assert!(!headers.is_empty()); - for header in headers.iter() { - assert_eq!(header.database, "analytics"); - assert_eq!(header.database_prefix, "tenant/production"); - assert_eq!(header.namespace_path, "team$reports"); - } + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - - let encode_token = - |kind: &str, database: &str, prefix: Option<&str>, path: &[String], last: &str| { - URL_SAFE_NO_PAD.encode( - serde_json::to_vec(&(kind, database, prefix, path.to_vec(), last)).unwrap(), - ) - }; - for forged in [ - encode_token( - "secret", - "analytics", - Some("tenant/production"), - &namespace, - "hf'prod", - ), - encode_token( - "view", - "billing", - Some("tenant/production"), - &namespace, - "hf'prod", - ), - encode_token("view", "analytics", Some("other"), &namespace, "hf'prod"), - encode_token( - "view", - "analytics", - Some("tenant/production"), - &["other".to_owned()], - "hf'prod", - ), - "not-a-json-token".to_string(), - ] { - let mut listing = connection.list_views( - &namespace, - crate::listing::ListingOptions::default().page_token(forged), - ); - assert!(matches!( - listing.next_page().await, - Err(Error::InvalidInput { .. }) - )); - } - let mut listing = connection.list_views( - &["other".to_owned()], - crate::listing::ListingOptions::default().page_token(&token), - ); - assert!(matches!( - listing.next_page().await, - Err(Error::InvalidInput { .. }) - )); - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } @@ -3521,3 +4444,1281 @@ fn sql_status_keeps_input_category_and_request_ids() { let error = super::sql_status_error("request", &tonic::Status::not_found("column_not_found")); assert!(error.remote_error_metadata().unwrap().error_code.is_none()); } + +#[test] +fn sql_status_reports_structured_resource_identity() { + let mut status = tonic::Status::not_found("Function 'missing' was not found"); + status + .metadata_mut() + .insert("x-lancedb-error-code", "not_found".parse().unwrap()); + status.metadata_mut().insert( + "x-lancedb-resource", + "eyJraW5kIjoiZnVuY3Rpb24iLCJuYW1lIjoibWlzc2luZyIsIm5hbWVzcGFjZV9wYXRoIjpbIm5zIl19" + .parse() + .unwrap(), + ); + status + .metadata_mut() + .insert("x-lancedb-sql-job-id", "sql-job-1".parse().unwrap()); + + let error = super::sql_status_error("current-request", &status); + let resource = error + .remote_error_metadata() + .unwrap() + .resource + .as_ref() + .unwrap(); + assert_eq!(resource.kind, "function"); + assert_eq!(resource.name, "missing"); + assert_eq!(resource.namespace_path, ["ns"]); +} + +#[tokio::test] +async fn remote_optimize_forwards_per_job_options_on_main_and_branch() { + for branch in [None, Some("o'brien")] { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into()], + "team$events".into(), + Default::default(), + Some(sql_client), + ) + .with_branch(branch.map(str::to_string)); + table + .optimize(crate::table::optimize::OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions { + target_rows_per_fragment: 100, + max_source_rows: Some(500), + io_buffer_size: Some(0), + batch_size: Some(16), + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap(); + let prefix = if branch.is_some() { + "branch = 'o''brien', " + } else { + "" + }; + assert_eq!( + *statements.lock().unwrap(), + [format!( + "OPTIMIZE \"events\" REWRITE DATA WITH ({prefix}target_rows_per_fragment = 100, max_source_rows = 500, io_buffer_size = 0, batch_size = 16)" + )] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team") + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_compact_preserves_omissions_and_explicit_default_values() { + use crate::table::{CompactionOptions, CompactionOverrides}; + let target = CompactionOptions::default().target_rows_per_fragment; + for (options, suffix) in [ + (CompactionOverrides::default(), String::new()), + ( + CompactionOverrides { + target_rows_per_fragment: Some(target), + ..Default::default() + }, + format!(" WITH (target_rows_per_fragment = {target})"), + ), + ( + CompactionOverrides { + io_buffer_size: Some(0), + ..Default::default() + }, + " WITH (io_buffer_size = 0)".into(), + ), + ] { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ); + table.compact(options).await.unwrap(); + assert_eq!( + *statements.lock().unwrap(), + [format!("OPTIMIZE \"events\" REWRITE DATA{suffix}")] + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_optimize_parser_errors_are_clear_without_resubmission() { + use crate::table::optimize::CompactionOverrides; + for (code, message, unsupported) in [ + ( + tonic::Code::InvalidArgument, + "ParserError(\"Expected: end of statement, found: REWRITE at Line: 1\")", + true, + ), + ( + tonic::Code::InvalidArgument, + "ParserError: Expected: TABLE, found: events", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown OPTIMIZE option 'io_buffer_size'", + true, + ), + ( + tonic::Code::InvalidArgument, + "ParserError: future grammar diagnostic", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown OPTIMIZE option 'future_option'", + true, + ), + ( + tonic::Code::PermissionDenied, + "ParserError: future grammar diagnostic", + false, + ), + (tonic::Code::PermissionDenied, "permission denied", false), + (tonic::Code::NotFound, "table not found", false), + (tonic::Code::Unavailable, "transport error", false), + ( + tonic::Code::InvalidArgument, + "invalid table configuration", + false, + ), + ] { + let status = Status::new(code, message); + let service = TestSqlService { + adaptive: true, + optimize_error: Some(status), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = + client_with_handler(|_| -> http::Response { panic!("no REST fallback") }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ); + let error = table + .compact(CompactionOverrides::default()) + .await + .unwrap_err(); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error:?}" + ); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("request_id")); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_optimize_branch_options_are_not_dropped() { + let service = TestSqlService { + adaptive: true, + optimize_error: Some(Status::invalid_argument( + "ParserError: Expected: ), found: , at Line: 1", + )), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|_| -> http::Response { panic!("no REST fallback") }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ) + .with_branch(Some("exp".into())); + let error = table + .compact(crate::table::optimize::CompactionOverrides { + io_buffer_size: Some(0), + ..Default::default() + }) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("compatible release")); + assert_eq!( + *statements.lock().unwrap(), + ["OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'exp', io_buffer_size = 0)"] + ); + shutdown.send(()).unwrap(); +} + +fn prewarm_result() -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "job_id", + Arc::new(StringArray::from(vec!["warming-job"])) as ArrayRef, + ), + ( + "table_version", + Arc::new(arrow_array::UInt64Array::from(vec![42])) as ArrayRef, + ), + ]) + .unwrap() +} + +fn receipt_test_table( + sql: SqlClient, +) -> RemoteTable { + RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!( + "unexpected HTTP request while reading a job receipt: {}", + r.url() + ) + }), + "analytics".into(), + "events".into(), + vec!["team".into()], + "team$events".into(), + Default::default(), + Some(sql), + ) +} + +#[tokio::test] +async fn remote_maintenance_job_receipts_require_one_row_and_a_complete_stream() { + let receipt = prewarm_result(); + let empty = receipt.slice(0, 0); + let with_ids = |ids: ArrayRef| { + let versions = arrow_array::UInt64Array::from(vec![42; ids.len()]); + RecordBatch::try_from_iter([ + ("job_id", ids), + ("table_version", Arc::new(versions) as ArrayRef), + ]) + .unwrap() + }; + let ids = |values: Vec>| with_ids(Arc::new(StringArray::from(values))); + let invalid = "inspect jobs before retrying"; + // All three commands receive the same wire response. + for (first, tail, expected) in [ + ( + empty.clone(), + vec![Ok(receipt.clone()), Ok(empty.clone())], + Ok("warming-job"), + ), + (ids(vec![Some(" id ")]), vec![], Ok(" id ")), + (empty, vec![], Err(invalid)), + (ids(vec![None]), vec![], Err(invalid)), + (ids(vec![Some("")]), vec![], Err(invalid)), + (ids(vec![Some(" \t ")]), vec![], Err(invalid)), + ( + with_ids(Arc::new(Int64Array::from(vec![7]))), + vec![], + Err(invalid), + ), + (receipt.project(&[1]).unwrap(), vec![], Err(invalid)), + (ids(vec![Some("one"), Some("two")]), vec![], Err(invalid)), + (receipt.clone(), vec![Ok(receipt.clone())], Err(invalid)), + ( + receipt, + vec![Err(Status::data_loss("receipt stream interrupted"))], + Err("receipt stream interrupted"), + ), + ] { + let service = TestSqlService { + adaptive: true, + result: first, + result_tail: tail, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = receipt_test_table(sql); + let compact = table.compact_async(Default::default()).await; + let prewarm = table.prewarm_data_async(Default::default()).await; + let cleanup = table.cleanup_async(Default::default()).await; + for (result, command) in [ + (compact.as_ref().map(|j| j.id()), "OPTIMIZE"), + (prewarm.as_ref().map(|j| j.id()), "PREWARM"), + (cleanup.as_ref().map(|j| j.id()), "VACUUM"), + ] { + match expected { + Ok(id) => assert_eq!(result.unwrap(), Some(id), "{command}"), + Err(message) => { + let error = result.unwrap_err().to_string(); + assert!(error.contains(message), "{command}: {error}"); + if message == invalid { + assert!(error.contains(command), "{error}"); + } + } + } + } + let commands: Vec<_> = statements + .lock() + .unwrap() + .iter() + .map(|sql| sql.split_whitespace().next().unwrap().to_owned()) + .collect(); + assert_eq!(commands, ["OPTIMIZE", "PREWARM", "VACUUM"]); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_receipt_requires_a_non_null_uint64_version() { + let id = prewarm_result().project(&[0]).unwrap(); + for version in [ + None, + Some(Arc::new(Int64Array::from(vec![42])) as ArrayRef), + Some(Arc::new(arrow_array::UInt64Array::from(vec![None])) as ArrayRef), + ] { + let result = match version { + None => id.clone(), + Some(version) => RecordBatch::try_from_iter([ + ("job_id", id.column(0).clone()), + ("table_version", version), + ]) + .unwrap(), + }; + let service = TestSqlService { + adaptive: true, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = receipt_test_table(sql); + let error = table + .prewarm_data_async(Default::default()) + .await + .unwrap_err() + .to_string(); + assert!( + error.contains("table_version") && error.contains("inspect jobs before retrying"), + "{error}" + ); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_accepts_a_receipt_for_a_bound_filter() { + let statement = r#"PREWARM WITH (branch = 'exp') AS SELECT * FROM "events" WHERE tag = $tag"#; + let parameters = RecordBatch::try_from_iter([( + "tag", + Arc::new(StringArray::from(vec!["train's data"])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + service + .result_overrides + .lock() + .unwrap() + .insert(statement.to_owned(), prewarm_result()); + let exchanges = service.exchanges.clone(); + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = receipt_test_table(sql).with_branch(Some("exp".into())); + let job = table + .prewarm_data_async( + crate::table::PrewarmDataOptions::new() + .filter("tag = $tag") + .parameters(parameters.clone()), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("warming-job")); + assert_eq!( + *exchanges.lock().unwrap(), + [(statement.to_owned(), Some(parameters))] + ); + assert!(statements.lock().unwrap().is_empty()); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.database == "analytics" && h.namespace_path == "team") + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_prewarm_data_returns_the_durable_job_without_polling() { + use crate::table::PrewarmDataOptions; + for branch in [None, Some("experiment"), Some("o'brien")] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| -> http::Response { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let value: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(value["job_id"], "warming-job"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"warming-job", "job_type":"prewarm_page_cache", "job_state":"DONE", + "creation_ms":1,"spec":{"table_version":42}, + "result":{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}, + "operation_progress":{"phase":"reading","executors_completed":2}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clip\"name".into(), + vec!["team".into(), "inner".into()], + "team$inner$clip\"name".into(), + Default::default(), + Some(sql), + ) + .with_branch(branch.map(str::to_string)); + let job = table + .prewarm_data_async( + PrewarmDataOptions::new() + .columns(["attrs.score", "`caption.text`", "attrs.score"]) + .filter("quality > 0.7") + .concurrency(4), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("warming-job")); + assert_eq!( + polls.load(Ordering::SeqCst), + 0, + "acceptance must not eagerly poll HTTP" + ); + let branch_sql = branch + .map(|b| format!("branch = '{}', ", b.replace('\'', "''"))) + .unwrap_or_default(); + assert_eq!( + *statements.lock().unwrap(), + [format!( + "PREWARM WITH ({branch_sql}concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7" + )] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team$inner" && h.database == "analytics") + ); + job.wait().await.unwrap(); + assert_eq!(polls.load(Ordering::SeqCst), 1); + job.refresh().await.unwrap(); + assert_eq!(job.spec().unwrap()["table_version"], 42); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_legacy_prewarm_data_submits_sql_and_returns_on_acceptance() { + for columns in [None, Some(vec![]), Some(vec!["payload".into()])] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!( + "legacy prewarm must neither submit nor poll REST: {}", + r.url() + ); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + table.prewarm_data(columns.clone()).await.unwrap(); + let projection = if columns.as_ref().is_some_and(|c| !c.is_empty()) { + "\"payload\"" + } else { + "*" + }; + assert_eq!( + *statements.lock().unwrap(), + [format!("PREWARM AS SELECT {projection} FROM \"clips\"")] + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_data_rejects_bad_receipts_without_resubmission() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not retry malformed receipt through REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(error.to_string().contains("inspect jobs before retrying")); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_prewarm_errors_preserve_diagnostics_and_never_fall_back() { + for (status, unsupported) in [ + ( + Status::invalid_argument("Unknown PREWARM option 'branch'"), + true, + ), + (Status::permission_denied("source Select denied"), false), + ( + Status::invalid_argument("ParserError: expected expression, found invalid_filter"), + false, + ), + ] { + let service = TestSqlService { + adaptive: true, + prewarm_error: Some(status), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not retry through REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let error = table.prewarm_data(None).await.unwrap_err(); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error}" + ); + let preview_error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert_eq!( + matches!(preview_error, Error::NotSupported { .. }), + unsupported, + "{preview_error}" + ); + assert_eq!(statements.lock().unwrap().len(), 2); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_requires_azure_ack_before_execution() { + for supported in [false, true] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + prewarm_azure_supported: supported, + ..Default::default() + }; + let statements = service.statements.clone(); + let mut config = ClientConfig::default(); + config.extra_headers.insert( + "x-azure-storage-account-name".into(), + "sourceaccount".into(), + ); + let (sql, shutdown) = start_sql_service(service, config).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not use REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let result = table.prewarm_data(None).await; + assert_eq!(result.is_ok(), supported, "{result:?}"); + assert_eq!(statements.lock().unwrap().len(), usize::from(supported)); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_wait_surfaces_warming_job_failure_or_cancellation() { + for state in ["FAILED", "CANCELLED"] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(move |r| -> http::Response { + assert_eq!(r.url().path(), "/v1/jobs/describe"); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"warming-job","job_type":"prewarm_page_cache","job_state":state, + "creation_ms":1,"spec":{"table_version":42}, + "result":{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}, + "operation_progress":{"phase":"reading","executors_completed":2}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let job = table.prewarm_data_async(Default::default()).await.unwrap(); + assert_eq!(job.id(), Some("warming-job")); + let error = job.wait().await.unwrap_err(); + if state == "FAILED" { + assert!(matches!(error, Error::JobFailed { .. }), "{error}"); + } else { + assert!(matches!(error, Error::JobCancelled { .. }), "{error}"); + } + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_rejects_historical_checkout_without_submitting() { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + assert_eq!(r.url().path(), "/v1/table/clips/describe/"); + http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + table.checkout(7).await.unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("historical version 7")); + let error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("historical version 7")); + assert!(statements.lock().unwrap().is_empty()); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_cleanup_tracks_registry_job_and_real_result() { + use crate::table::CleanupOptions; + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([( + "job_id", + Arc::new(StringArray::from(vec!["cleanup-job"])) as ArrayRef, + )]) + .unwrap(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"cleanup-job","job_type":"cleanup","job_state":"DONE", + "result":{"format_version":1,"min_age_seconds":0,"statistics_complete":true, + "old_versions":2,"bytes_removed":123} + }) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "inner".into()], + "team$inner$events".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("o'brien".into())); + let job = table + .cleanup_async(CleanupOptions::new().min_age_seconds(0)) + .await + .unwrap(); + assert_eq!(job.id(), Some("cleanup-job")); + assert_eq!(polls.load(Ordering::SeqCst), 0); + let result = job.wait().await.unwrap(); + assert_eq!(result.old_versions, Some(2)); + assert_eq!(result.bytes_removed, Some(123)); + assert_eq!( + *statements.lock().unwrap(), + ["VACUUM \"events\" WITH (branch = 'o''brien', min_age_seconds = 0)"] + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_cleanup_rejects_historical_checkout_without_submitting() { + let table = RemoteTable::new_with_sql_client( + client_with_handler(|request| { + assert_eq!(request.url().path(), "/v1/table/events/describe/"); + http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + }), + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + None, + ); + table.checkout(7).await.unwrap(); + assert!(table.cleanup_async(Default::default()).await.is_err()); +} + +#[tokio::test] +async fn remote_compaction_tracks_registry_job_and_real_result() { + use crate::table::optimize::CompactionOverrides; + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([( + "job_id", + Arc::new(StringArray::from(vec!["compacting-job"])) as ArrayRef, + )]) + .unwrap(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "compacting-job"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"compacting-job","job_type":"compact","job_state":"DONE", + "result":{"partial_commit":false,"rows_succeeded":12,"rows_failed":0, + "completion_percentage":100.0,"files_added":1,"files_removed":3, + "fragments_added":1,"fragments_removed":3}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "inner".into()], + "team$inner$events".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("experiment".into())); + let job = table + .compact_async(CompactionOverrides { + target_rows_per_fragment: Some(100), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(job.id(), Some("compacting-job")); + assert_eq!(polls.load(Ordering::SeqCst), 0); + let result = job.wait().await.unwrap(); + assert_eq!(result.rows_succeeded, 12); + assert_eq!(result.fragments_removed, Some(3)); + assert!(!result.more_work); + assert_eq!( + *statements.lock().unwrap(), + [ + "OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'experiment', target_rows_per_fragment = 100)" + ] + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_prewarm_preview_uses_sql_without_any_http_jobs() { + use crate::table::PrewarmDataOptions; + for azure in [false, true] { + let preview = serde_json::json!({ + "format_version":1,"table_version":42,"plan":"metadata preview", + "pruning":{"mode":"zonemap_ranges","input_fragments":4, + "selected_fragments":1,"pruned_fragments":3,"selected_row_ranges":2} + }); + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([ + ( + "plan_type", + Arc::new(StringArray::from(vec!["logical_plan"])) as ArrayRef, + ), + ( + "plan", + Arc::new(StringArray::from(vec![preview.to_string()])) as ArrayRef, + ), + ]) + .unwrap(), + prewarm_azure_supported: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let mut config = ClientConfig::default(); + if azure { + config.extra_headers.insert( + "x-azure-storage-account-name".into(), + "sourceaccount".into(), + ); + } + let (sql, shutdown) = start_sql_service(service, config).await; + let client = client_with_handler(|_| -> http::Response { + panic!("preview must not use HTTP job APIs or REST fallback") + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clips".into(), + vec!["team".into()], + "team$clips".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("experiment".into())); + let plan = table + .explain_prewarm_data( + PrewarmDataOptions::new() + .columns(["attrs.score"]) + .filter("id > 0") + .concurrency(4), + ) + .await + .unwrap(); + assert_eq!(plan.table_version, 42); + assert_eq!(plan.pruning.selected_row_ranges, Some(2)); + assert_eq!( + *statements.lock().unwrap(), + [ + "EXPLAIN (FORMAT JSON) PREWARM WITH (branch = 'experiment', concurrency = 4) AS SELECT \"attrs\".\"score\" FROM \"clips\" WHERE id > 0" + ] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team" && h.database == "analytics") + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_cleanup_preview_uses_sql_without_job_calls() { + let payload = serde_json::json!({"format_version":1,"source_version":42,"min_age_seconds":0, + "cutoff_millis":123,"versions_to_remove":2,"bytes_to_remove":100}); + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([ + ( + "plan_type", + Arc::new(StringArray::from(vec!["logical_plan"])) as ArrayRef, + ), + ( + "plan", + Arc::new(StringArray::from(vec![payload.to_string()])) as ArrayRef, + ), + ]) + .unwrap(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|_| -> http::Response { + panic!("preview must not use HTTP jobs or execution fallback") + }), + "analytics".into(), + "events".into(), + vec!["team".into()], + "team$events".into(), + Default::default(), + Some(sql), + ); + let plan = table + .explain_cleanup(crate::table::CleanupOptions::new().min_age_seconds(0)) + .await + .unwrap(); + assert_eq!(plan.source_version, 42); + assert_eq!(plan.versions_to_remove, 2); + assert_eq!( + *statements.lock().unwrap(), + ["EXPLAIN (FORMAT JSON) VACUUM \"events\" WITH (min_age_seconds = 0)"] + ); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn sql_deadline_expires_unread_streamed_and_deferred_queries() { + for deferred in [false, true] { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + defer: deferred, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let headers = service.headers.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT slow get"); + request.parameters = parameters; + request.options.timeout = Some(Duration::from_secs(3)); + let query = client.execute(request).await.unwrap(); + assert!(headers.lock().unwrap()[0].grpc_timeout.is_some()); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(4)).await; + tokio::task::yield_now().await; + tokio::time::resume(); + assert_overall_timeout(query.describe().await, "result"); + assert_overall_timeout(client.describe(query.id()).await, "result"); + assert_overall_timeout(query.reader().await, "result"); + if deferred { + wait_for( + &cancellations, + 1, + "expiry must cancel deferred execution without a reader", + ) + .await; + } + let ordinary = client + .execute(ExecuteQueryRequest::new("SELECT 1")) + .await + .unwrap(); + assert!( + !collect_result(&ordinary).await.unwrap().is_empty(), + "query options must not change the connection defaults" + ); + } + } +} + +#[tokio::test] +async fn a_deferred_result_timeout_sends_cancellation() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT slow get"); + request.options.timeout = Some(Duration::from_secs(3)); + let query = client.execute(request).await.unwrap(); + tokio::time::pause(); + tokio::time::advance(Duration::from_millis(2_900)).await; + let result = query.reader().await; + tokio::time::resume(); + assert_overall_timeout(result, "result"); + wait_for( + &cancellations, + 1, + "a deferred reader timeout must cancel execution", + ) + .await; +} + +#[tokio::test] +async fn sql_read_timeout_is_per_query_and_cancels_deferred_execution() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT slow get"); + request.options.read_timeout = Some(Duration::from_millis(100)); + let query = client.execute(request).await.unwrap(); + let error = collect_result(&query).await.unwrap_err(); + assert!( + error.to_string().contains("SQL result read timed out"), + "{error}" + ); + wait_for( + &cancellations, + 1, + "a read timeout must cancel deferred execution", + ) + .await; + let next = client + .execute(ExecuteQueryRequest::new("SELECT slow get")) + .await + .unwrap(); + assert!(!collect_result(&next).await.unwrap().is_empty()); +} + +#[tokio::test] +async fn deferred_cancellation_on_drop_is_opt_in() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let detached = client + .execute(ExecuteQueryRequest::new("SELECT 1")) + .await + .unwrap(); + let id = detached.id(); + drop(detached); + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!(cancellations.load(Ordering::SeqCst), 0); + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.cancel_on_drop = true; + let query = client.execute(request).await.unwrap(); + let id = query.id(); + // Drop outside the async runtime, as Python garbage collection may do. + std::thread::spawn(move || drop(query)).join().unwrap(); + wait_for(&cancellations, 1, "dropping an opted-in handle must cancel").await; + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Cancelled + ); +} + +#[tokio::test] +async fn deferred_reader_owns_cancellation_after_the_handle_is_dropped() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT slow"); + request.options.cancel_on_drop = true; + let query = client.execute(request).await.unwrap(); + let rows = query.reader().await.unwrap(); + drop(query); + assert_eq!( + cancellations.load(Ordering::SeqCst), + 0, + "an active reader must survive dropping its query handle" + ); + drop(rows); + wait_for( + &cancellations, + 1, + "dropping the reader must cancel deferred execution", + ) + .await; +} + +#[tokio::test] +async fn a_completed_query_is_not_cancelled_on_drop_or_deadline() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let cancellations = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.timeout = Some(Duration::from_secs(3)); + request.options.cancel_on_drop = true; + let query = client.execute(request).await.unwrap(); + assert!(!collect_result(&query).await.unwrap().is_empty()); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(4)).await; + tokio::task::yield_now().await; + tokio::time::resume(); + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Finished + ); + drop(query); + assert_eq!(cancellations.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn sql_deadline_applies_to_buffered_results_and_stops_its_timer_on_completion() { + for deferred in [false, true] { + let service = TestSqlService { + adaptive: true, + defer: deferred, + ..TestSqlService::default() + }; + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.timeout = Some(Duration::from_secs(3)); + let query = client.execute(request).await.unwrap(); + let mut rows = query.reader().await.unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Finished + ); + match client.queries.get(query.id()).unwrap() { + RegisteredQuery::Polled(query) => { + assert!(query.deadline_task.lock().unwrap().is_none()) + } + RegisteredQuery::Streamed(query) => assert!(query.deadline_stopped()), + } + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(4)).await; + tokio::time::resume(); + assert_overall_timeout(rows.try_next().await, "result"); + assert!(rows.try_next().await.unwrap().is_none()); + } +} + +#[tokio::test] +async fn sql_deadline_is_forwarded_to_deferred_result_requests() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..TestSqlService::default() + }; + let deadlines = service.result_deadlines.clone(); + let headers = service.headers.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.timeout = Some(Duration::from_secs(3)); + let query = client.execute(request).await.unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!collect_result(&query).await.unwrap().is_empty()); + let deadlines = deadlines.lock().unwrap(); + let result_deadline = deadlines[0] + .as_deref() + .expect("the result request must carry an execution deadline"); + assert_ne!( + Some(result_deadline), + headers.lock().unwrap()[0].grpc_timeout.as_deref(), + "the timeout budget must not restart for the result request" + ); +} + +#[tokio::test] +async fn sql_rejects_timeouts_that_cannot_be_encoded_by_grpc() { + let (client, _shutdown) = + start_sql_service(TestSqlService::default(), ClientConfig::default()).await; + let mut request = ExecuteQueryRequest::new("SELECT 1"); + request.options.timeout = Some(Duration::from_secs(u64::MAX)); + assert!(matches!( + client.execute(request).await, + Err(Error::InvalidInput { .. }) + )); +} diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs index bdba4f1df..104fbbc13 100644 --- a/rust/lancedb/src/remote/storage_integration.rs +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -54,6 +54,11 @@ pub(super) fn create_sql( namespace: &[String], request: &CreateStorageIntegrationRequest, ) -> Result { + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; if request.storage_provider != StorageProvider::HuggingFace && request.huggingface_token_secret.is_some() { @@ -70,6 +75,7 @@ pub(super) fn create_sql( || request.azure_tenant_id_secret.is_some() || request.azure_client_id_secret.is_some() || request.azure_client_secret_secret.is_some() + || request.azure_storage_account_access_key_secret.is_some() || request.gcp_credentials_json_secret.is_some() { return Err(invalid( @@ -77,7 +83,7 @@ pub(super) fn create_sql( )); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -105,6 +111,7 @@ pub(super) fn create_sql( || request.azure_tenant_id_secret.is_some() || request.azure_client_id_secret.is_some() || request.azure_client_secret_secret.is_some() + || request.azure_storage_account_access_key_secret.is_some() { return Err(invalid( "GCP integrations cannot contain AWS or Azure options", @@ -115,7 +122,7 @@ pub(super) fn create_sql( .as_ref() .ok_or_else(|| invalid("GCP integrations require gcp_credentials_json_secret"))?; return Ok(format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", object_name(name, namespace)?, literal(&request.storage_prefix), secret_name(reference)? @@ -135,29 +142,37 @@ pub(super) fn create_sql( .filter(|account| !account.is_empty()) .ok_or_else(|| invalid("Azure integrations require azure_storage_account"))?; let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", object_name(name, namespace)?, literal(&request.storage_prefix), literal(account) ); - for (key, reference) in [ - ( - "STORAGE_AZURE_TENANT_ID_SECRET", - &request.azure_tenant_id_secret, - ), - ( - "STORAGE_AZURE_CLIENT_ID_SECRET", - &request.azure_client_id_secret, - ), - ( - "STORAGE_AZURE_CLIENT_SECRET_SECRET", - &request.azure_client_secret_secret, - ), - ] { - let reference = reference.as_ref().ok_or_else(|| { - invalid("Azure integrations require all three credential Secret references") - })?; - sql.push_str(&format!(" {key} = {}", secret_name(reference)?)); + match ( + &request.azure_storage_account_access_key_secret, + &request.azure_tenant_id_secret, + &request.azure_client_id_secret, + &request.azure_client_secret_secret, + ) { + (Some(reference), None, None, None) => { + sql.push_str(&format!( + " STORAGE_AZURE_STORAGE_ACCOUNT_ACCESS_KEY_SECRET = {}", + secret_name(reference)? + )); + } + (None, Some(tenant), Some(client), Some(secret)) => { + for (key, reference) in [ + ("STORAGE_AZURE_TENANT_ID_SECRET", tenant), + ("STORAGE_AZURE_CLIENT_ID_SECRET", client), + ("STORAGE_AZURE_CLIENT_SECRET_SECRET", secret), + ] { + sql.push_str(&format!(" {key} = {}", secret_name(reference)?)); + } + } + _ => { + return Err(invalid( + "Specify either azure_storage_account_access_key_secret or all three Azure service principal Secret references", + )); + } } return Ok(sql); } @@ -165,11 +180,12 @@ pub(super) fn create_sql( || request.azure_tenant_id_secret.is_some() || request.azure_client_id_secret.is_some() || request.azure_client_secret_secret.is_some() + || request.azure_storage_account_access_key_secret.is_some() { return Err(invalid("S3 integrations cannot contain Azure options")); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -239,6 +255,7 @@ pub(super) fn decode_info(batches: &[RecordBatch]) -> Result Result Result> { - let mut names = Vec::new(); - for batch in batches { - let column = batch - .column_by_name("name") - .ok_or_else(|| invalid("SQL storage integration listing is missing names"))?; - for row in 0..batch.num_rows() { - if column.is_null(row) { - return Err(invalid("SQL storage integration name cannot be null")); - } - names.push( - string_value(column.as_ref(), row) - .ok_or_else(|| { - invalid("SQL storage integration listing requires string names") - })? - .to_string(), - ); - } - } - names.sort(); - Ok(names) -} - #[cfg(test)] mod tests { use std::sync::Arc; use super::*; + #[test] + fn azure_account_access_key_sql_references_only_the_key_secret() { + let mut request = CreateStorageIntegrationRequest::azure_with_account_access_key( + "az://customer-data/raw/", + "customeraccount", + SecretReference::new("blob_key") + .with_database("shared") + .with_namespace(vec!["credentials".into()]), + ); + let sql = create_sql("blobs", &[], &request).unwrap(); + assert!(sql.contains("STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount'")); + assert!(sql.contains( + r#"STORAGE_AZURE_STORAGE_ACCOUNT_ACCESS_KEY_SECRET = "shared"."credentials"."blob_key""# + )); + assert!(!sql.contains("STORAGE_AZURE_TENANT_ID_SECRET")); + assert!(!sql.contains("STORAGE_AZURE_CLIENT_ID_SECRET")); + assert!(!sql.contains("STORAGE_AZURE_CLIENT_SECRET_SECRET")); + + request.azure_client_id_secret = Some(SecretReference::new("client")); + assert!(create_sql("blobs", &[], &request).is_err()); + } + + #[test] + fn create_if_not_exists_preserves_provider_options() { + let secret = SecretReference::new("credential"); + let requests = [ + CreateStorageIntegrationRequest::s3("s3://bucket/", "role"), + CreateStorageIntegrationRequest::s3_with_secrets( + "s3://bucket/", + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::azure( + "az://container/", + "account", + secret.clone(), + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::gcp("gs://bucket/", secret), + CreateStorageIntegrationRequest::huggingface("hf://datasets/acme/data/"), + ]; + for request in requests { + let legacy_json = serde_json::to_value(&request).unwrap(); + assert!(legacy_json.get("exist_ok").is_none()); + let decoded: CreateStorageIntegrationRequest = + serde_json::from_value(legacy_json).unwrap(); + assert!(!decoded.exist_ok); + let strict = create_sql("raw", &[], &request).unwrap(); + let guarded = request.exist_ok(true); + assert_eq!(serde_json::to_value(&guarded).unwrap()["exist_ok"], true); + assert_eq!( + create_sql("raw", &[], &guarded).unwrap(), + strict.replacen( + "CREATE STORAGE INTEGRATION ", + "CREATE STORAGE INTEGRATION IF NOT EXISTS ", + 1, + ) + ); + } + } + #[test] fn sql_quotes_values_and_keeps_secret_root_namespace_explicit() { let role = CreateStorageIntegrationRequest::s3("s3://bucket/it's/", "role'value"); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3b241dd3a..2f88d7f2f 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2,9 +2,19 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors pub mod blobs; +mod cleanup; pub mod insert; +mod ipc_stream; +mod optimize; +mod prewarm; +#[cfg(test)] +mod profile_tests; +mod receipt; +#[cfg(test)] +mod write_tests; use self::insert::{RemoteWriteExec, WriteOp}; +use self::receipt::JobReceipt; use super::client::RequestResultExt; use super::client::{HttpSend, RestfulLanceDbClient, Sender}; use super::db::ServerVersion; @@ -16,9 +26,9 @@ use crate::error::{HttpErrorSource, RemoteErrorMetadata}; use crate::expr::expr_to_sql_string; use crate::index::Index; use crate::index::IndexStatistics; -use crate::index::scalar::FtsQuery; +use crate::index::scalar::{FtsQuery, Operator}; use crate::index::waiter::{MAX_WAIT, wait_for_index}; -use crate::job::Job; +use crate::job::{FunctionProfile, FunctionProfileOptions, Job}; use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult}; use crate::query::wal_fusion::PkFusionMemory; // WAL-PK-FUSION: delete. use crate::query::{QueryFilter, QueryRequest, Select, VectorQueryRequest}; @@ -40,7 +50,8 @@ use crate::table::query::create_multi_vector_plan; use crate::table::rte_stats::GetRTEStatsResponse; use crate::table::write_progress::FinishOnDrop; use crate::table::{ - AlterColumnsResult, FieldMetadataUpdate, RefreshColumnResult, UpdateFieldMetadataResult, + AlterColumnsResult, FieldMetadataUpdate, FunctionColumnStatus, RefreshColumnResult, + UpdateFieldMetadataResult, }; use crate::table::{AnyQuery, Filter, Predicate, PreprocessingOutput, TableStatistics}; use crate::utils::background_cache::BackgroundCache; @@ -60,20 +71,20 @@ use crate::{ }, }; use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader}; -use arrow_ipc::reader::{FileReader, StreamReader}; -use arrow_schema::{ArrowError, DataType, SchemaRef}; +use arrow_ipc::reader::FileReader; +use arrow_schema::{DataType, SchemaRef}; use async_trait::async_trait; use chrono::{DateTime, Utc}; use datafusion_common::DataFusionError; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ExecutionPlan, RecordBatchStream, SendableRecordBatchStream}; use futures::{StreamExt, TryStreamExt}; -use http::header::CONTENT_TYPE; +use http::header::{ACCEPT, CONTENT_TYPE}; use http::{HeaderName, StatusCode}; use lance::arrow::json::{JsonDataType, JsonSchema}; use lance::dataset::refs::TagContents; use lance::dataset::scanner::DatasetRecordBatchStream; -use lance::dataset::{ColumnAlteration, NewColumnTransform, Version}; +use lance::dataset::{ColumnAlteration, NewColumnTransform, Version, WriteParams}; use lance_core::datatypes::Schema as LanceSchema; use lance_datafusion::exec::{OneShotExec, execute_plan}; use reqwest::{RequestBuilder, Response}; @@ -81,6 +92,7 @@ use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::io::Cursor; use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime}; use tokio::sync::RwLock; @@ -90,6 +102,38 @@ const MIN_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-ve const MIN_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-timestamp"); const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-read-version"); const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version"); +const QUERY_SNAPSHOT_HEADER: &str = "x-lancedb-query-snapshot"; + +fn valid_query_snapshot_identity(value: &str) -> bool { + value.strip_prefix("v1:").is_some_and(|digest| { + digest.len() == 64 + && digest + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} + +fn check_query_snapshot_response( + expected: Option<&str>, + response: &reqwest::Response, +) -> Result<()> { + if let Some(expected) = expected + && response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + != Some(expected) + { + return Err(Error::NotSupported { message: "Blob response did not verify the query snapshot identity; upgrade every serving node".into() }); + } + Ok(()) +} + +const QUERY_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-query-version"); +/// Asks for stream framing, which is decoded as it arrives. Servers that do not +/// stream query results ignore this and answer with file framing. +const QUERY_ACCEPT: &str = + "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9"; const METRIC_TYPE_KEY: &str = "metric_type"; const INDEX_TYPE_KEY: &str = "index_type"; const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(30); @@ -282,6 +326,30 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::describe(&self.inner).await } + async fn timeline(&self) -> Result { + crate::job::JobHandle::timeline(&self.inner).await + } + + async fn stack(&self, worker_id: &str) -> Result { + crate::job::JobHandle::stack(&self.inner, worker_id).await + } + + async fn capture_profile( + &self, + worker_id: &str, + options: FunctionProfileOptions, + ) -> Result { + crate::job::JobHandle::capture_profile(&self.inner, worker_id, options).await + } + + async fn profile_status(&self, profile_id: &str) -> Result { + crate::job::JobHandle::profile_status(&self.inner, profile_id).await + } + + async fn profile_artifact(&self, profile_id: &str) -> Result { + crate::job::JobHandle::profile_artifact(&self.inner, profile_id).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -289,6 +357,10 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::events(&self.inner, request).await } + async fn stats(&self) -> Result> { + crate::job::JobHandle::stats(&self.inner).await + } + async fn wait(&self) -> Result { crate::job::JobHandle::wait_with_progress(self, None).await } @@ -331,6 +403,16 @@ impl crate::job::JobHandle for FreshnessJob { async fn cancel(&self) -> Result<()> { crate::job::JobHandle::cancel(&self.inner).await } + + async fn retry(&self) -> Result> { + Ok(Box::new(Self { + inner: self.inner.retry_attempt().await?, + freshness: self.freshness.clone(), + version: self.version.clone(), + tracked_result: self.tracked_result, + freshness_request: self.freshness_request, + })) + } } /// A registry-backed materialized-view refresh. Registry completion is only @@ -363,6 +445,30 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::describe(&self.inner).await } + async fn timeline(&self) -> Result { + crate::job::JobHandle::timeline(&self.inner).await + } + + async fn stack(&self, worker_id: &str) -> Result { + crate::job::JobHandle::stack(&self.inner, worker_id).await + } + + async fn capture_profile( + &self, + worker_id: &str, + options: FunctionProfileOptions, + ) -> Result { + crate::job::JobHandle::capture_profile(&self.inner, worker_id, options).await + } + + async fn profile_status(&self, profile_id: &str) -> Result { + crate::job::JobHandle::profile_status(&self.inner, profile_id).await + } + + async fn profile_artifact(&self, profile_id: &str) -> Result { + crate::job::JobHandle::profile_artifact(&self.inner, profile_id).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -370,6 +476,10 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::events(&self.inner, request).await } + async fn stats(&self) -> Result> { + crate::job::JobHandle::stats(&self.inner).await + } + async fn wait(&self) -> Result { crate::job::JobHandle::wait_with_progress(self, None).await } @@ -589,6 +699,10 @@ pub struct RemoteTable { version: Arc>>, location: RwLock>, schema_cache: BackgroundCache, + // Only a successful describe can opt into the batched range protocol. + blob_ranges_supported: Arc, + // Only a successful describe can opt into presigned direct Blob reads. + blob_locations_supported: Arc, // WAL-PK-FUSION: delete, with its initializers below. wal_pk_fusion: PkFusionMemory, freshness: Arc>, @@ -596,6 +710,7 @@ pub struct RemoteTable { /// Stamped onto every branch-accepting request so reads and writes resolve /// on the branch's own version chain rather than main's. branch: Option, + expected_query_snapshot: Option, } impl std::fmt::Debug for RemoteTable { @@ -652,9 +767,13 @@ impl RemoteTable { async fn submit_create_index(&self, mut index: IndexBuilder) -> Result> { self.check_mutable().await?; - let request = self + let mut request = self .client .post(&format!("/v1/table/{}/create_index/", self.identifier)); + if index.exist_ok { + request = request.query(&[("exist_ok", true)]); + index.replace = false; + } let column = match index.columns.len() { 0 => { @@ -727,6 +846,12 @@ impl RemoteTable { Index::NGram(p) => ("NGRAM", Some(to_json(p)?)), Index::BloomFilter(p) => ("BLOOM_FILTER", Some(to_json(p)?)), Index::RTree(p) => ("RTREE", Some(to_json(p)?)), + // Keep generic plugin requests distinct from built-in index handling. + // The plugin's params are nested below rather than flattened. + Index::Plugin(p) => { + body["plugin_type"] = p.index_type().to_uppercase().into(); + ("PLUGIN", None) + } Index::FTS(p) => { validate_fts_field(&field)?; let mut params = to_json(p)?; @@ -765,6 +890,14 @@ impl RemoteTable { body[key] = value.clone(); } } + // A plugin's params are arbitrary, so they go under a single `params` + // key. Flattened, they could overwrite request fields such as `column`, + // `name`, `replace` or `branch`. + if let Index::Plugin(plugin) = &index.index + && let Some(params) = plugin.parameters() + { + body["params"] = serde_json::Value::Object(params.clone()); + } self.apply_branch_body(&mut body); let request = request.json(&body); @@ -805,6 +938,45 @@ impl RemoteTable { Ok(job_id) } + async fn submit_refresh( + &self, + operation: &str, + mut body: serde_json::Value, + ) -> Result> { + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/{operation}", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + // Preserve dependency errors: a deleted bound Function also returns 404. + let response = self + .client + .check_response(&request_id, response) + .await + .inspect_err(|error| self.handle_error_invalidation(error))?; + let body = response.text().await.err_to_http(request_id.clone())?; + + #[derive(serde::Deserialize)] + struct RefreshJobResponse { + job_id: String, + } + let response: RefreshJobResponse = + serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse {operation} response: {}", e).into(), + request_id, + status_code: None, + })?; + + Ok(Job::new_typed(Box::new(FreshnessJob { + inner: RemoteJob::new(self.client.clone(), response.job_id), + freshness: self.freshness.clone(), + version: self.version.clone(), + tracked_result: TrackedJobResult::RefreshColumn, + freshness_request: self.snapshot_freshness_headers(), + }))) + } + fn index_job(&self, job_id: String) -> Job { Job::new(Box::new(FreshnessJob { inner: RemoteJob::new(self.client.clone(), job_id), @@ -835,12 +1007,38 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } + pub(super) fn seed_blob_ranges_capability(&self, headers: &http::HeaderMap) { + self.blob_ranges_supported.store( + headers + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + } + + pub(super) fn seed_blob_locations_capability(&self, headers: &http::HeaderMap) { + self.blob_locations_supported.store( + headers + .get("x-lancedb-blob-locations") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + } + + fn seed_blob_capabilities(&self, headers: &http::HeaderMap) { + self.seed_blob_ranges_capability(headers); + self.seed_blob_locations_capability(headers); + } + /// Seed the schema cache from a `describe` body the caller already fetched. /// /// Best effort. `open_table` succeeds today without reading this body, so a @@ -871,9 +1069,12 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: self.blob_ranges_supported.clone(), + blob_locations_supported: self.blob_locations_supported.clone(), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, + expected_query_snapshot: None, } } @@ -895,6 +1096,102 @@ impl RemoteTable { } } + async fn submit_function_declarations( + &self, + plans: Vec, + options: crate::table::computed_columns::ComputedColumnOptions, + ) -> Result { + let new_columns = plans + .iter() + .flat_map(|plan| &plan.outputs) + .map(|output| serde_json::json!({"name": output.output_name, "all_null": true})) + .collect::>(); + let mut body = serde_json::json!({ + "new_columns": new_columns, + "auto_refresh_enabled": options.auto_refresh_enabled, + }); + if let [plan] = plans.as_slice() { + body["function"] = serde_json::json!(plan); + } else { + body["functions"] = serde_json::json!(plans); + } + if let Some(interval) = options.auto_refresh_interval_seconds { + body["auto_refresh_interval_seconds"] = serde_json::json!(interval); + } + for (key, value) in [ + ("total_cpu_millis", options.total_cpu_millis), + ("total_memory_bytes", options.total_memory_bytes), + ("total_gpu_count", options.total_gpu_count.map(u64::from)), + ] { + if let Some(value) = value { + body[key] = serde_json::json!(value); + } + } + if let Some(class) = &options.gpu_class { + body["gpu_class"] = serde_json::json!(class); + } + if let Some(count) = options.gpu_count { + body["gpu_count"] = serde_json::json!(count); + } + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/add_columns/", self.identifier)) + .json(&body); + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; + // A Function declaration can return 404 for the Function rather than the table. + let response = self + .client + .check_response(&request_id, response) + .await + .inspect_err(|error| self.handle_error_invalidation(error))?; + let body = response.text().await.err_to_http(request_id.clone())?; + + if body.trim().is_empty() { + return Ok(AddColumnsResult { version: 0 }); + } + + let result: AddColumnsResult = serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse add Function columns response: {e}").into(), + request_id, + status_code: None, + })?; + + self.invalidate_schema_cache(); + self.track_write_version(freshness_request, result.version); + Ok(result) + } + + async fn require_function_failure_workflow(&self) -> Result<()> { + let mut body = serde_json::json!({"limit": 1}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/errors", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id, + status_code: None, + })?; + if value + .get("workflow_version") + .and_then(serde_json::Value::as_u64) + .is_some_and(|version| version >= 1) + { + Ok(()) + } else { + Err(Error::NotSupported { message: "The server does not support the Function row-failure workflow; upgrade the server before retrying, upgrading, or quarantining rows".into() }) + } + } + async fn describe(&self) -> Result { self.describe_read_snapshot(self.snapshot_read_state().await) .await @@ -972,7 +1269,7 @@ impl RemoteTable { } /// Resolve a tag to its `(branch, version)` coordinate via the `tags/version` - /// endpoint, since the `/branches/create` contract accepts no `from_tag`. + /// endpoint. async fn resolve_tag_ref(&self, tag: &str) -> Result<(Option, u64)> { let request = self .client @@ -1019,10 +1316,15 @@ impl RemoteTable { }; let response = self.check_table_response(&request_id, response).await?; + self.seed_blob_capabilities(response.headers()); + let batch_function_declaration = response + .headers() + .get("x-lancedb-batch-function-declaration") + .is_some_and(|value| value == "1"); match response.text().await { Ok(body) => { - let description: TableDescription = + let mut description: TableDescription = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse table description: {}", e).into(), request_id, @@ -1031,6 +1333,7 @@ impl RemoteTable { if let Some(freshness_request) = freshness_request { freshness_request.observe_version(&self.freshness, description.version); } + description.batch_function_declaration = batch_function_declaration; Ok(description) } Err(err) => { @@ -1153,26 +1456,60 @@ impl RemoteTable { .and_then(|value| value.to_str().ok()) .map(str::to_owned); let framing = resolve_arrow_ipc_framing(content_type.as_deref(), request_id)?; + let table_version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); - // Buffer the whole body. File framing keeps its footer at the end, so /query - // cannot decode incrementally. Stream framing could, via - // arrow_ipc::reader::StreamDecoder, but fetch_blobs concatenates every batch - // before returning, so no caller would see data sooner. - let body = response.bytes().await.err_to_http(request_id.into())?; - type IpcBatchIterator = - Box> + Send>; - let (schema, batches): (SchemaRef, IpcBatchIterator) = match framing { + // Legacy version headers are freshness watermarks, not proof that the + // query and a later Blob read use the same immutable dataset. + let query_version = response + .headers() + .get(&QUERY_VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); + + let query_identity = response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .map(str::to_owned); + + let stream = match framing { ArrowIpcFraming::Stream => { - let reader = StreamReader::try_new(Cursor::new(body), None)?; - (reader.schema(), Box::new(reader)) + ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.to_string(), + table_version, + ) + .await? } ArrowIpcFraming::File => { + // File framing keeps its footer at the end, so the whole body is + // needed before anything can be decoded. + let body = response.bytes().await.err_to_http(request_id.into())?; let reader = FileReader::try_new(Cursor::new(body), None)?; - (reader.schema(), Box::new(reader)) + let schema = reader.schema(); + let stream = futures::stream::iter(reader).map_err(DataFusionError::from); + Box::pin(RecordBatchStreamAdapter::new(schema, stream)) as SendableRecordBatchStream } }; - let stream = futures::stream::iter(batches).map_err(DataFusionError::from); - Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + // Bind subsequent blob reads to the response's snapshot, never to a + // version sampled from the live table before or after the query. + let mut metadata = stream.schema().metadata().clone(); + metadata.remove("lancedb:query_version"); + metadata.remove("lancedb:query_snapshot"); + if let Some(identity) = query_identity { + metadata.insert("lancedb:query_snapshot".into(), identity); + } + if let Some(version) = query_version { + metadata.insert("lancedb:query_version".into(), version.to_string()); + } + Ok(with_stream_metadata(stream, metadata)) } fn apply_query_params( @@ -1181,6 +1518,13 @@ impl RemoteTable { params: &QueryRequest, ) -> Result<()> { params.check_filter()?; + if params.scan_in_order == Some(true) { + return Err(Error::NotSupported { + message: "scan_in_order(true) requires an ordered scan of Embedded storage; \ + LanceDB Enterprise tables do not support storage-order scans yet" + .to_string(), + }); + } body["prefilter"] = params.prefilter.into(); // Only forward use_rte when explicitly set; a server that predates it // ignores the field and routes as it would by default. @@ -1273,6 +1617,20 @@ impl RemoteTable { "query": full_text_search.query.clone(), }); } else { + let has_and = match &full_text_search.query { + FtsQuery::Match(query) => query.operator == Operator::And, + FtsQuery::MultiMatch(query) => query + .match_queries + .iter() + .any(|query| query.operator == Operator::And), + _ => false, + }; + if has_and { + return Err(Error::NotSupported { + message: "AND full-text queries require server version 0.3.0 or later" + .into(), + }); + } body["full_text_query"] = serde_json::json!({ "columns": full_text_search.columns().into_iter().collect::>(), "query": full_text_search.query.query(), @@ -1400,13 +1758,18 @@ impl RemoteTable { Ok(bodies) } - async fn create_multipart_write(&self) -> Result { + async fn create_multipart_write(&self, retries: Option) -> Result { let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/multipart_write/create", self.identifier ))); - let (request_id, response) = self.send(request, true).await?; + let client = self.client.with_retries(retries); + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = client + .send_with_retry(freshness_request.apply(request), None, true) + .await?; let response = self.check_table_response(&request_id, response).await?; + freshness_request.observe_headers(&self.freshness, response.headers()); let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse multipart create response: {}", e).into(), @@ -1432,7 +1795,7 @@ impl RemoteTable { )) .query(&[("upload_id", upload_id)]), ); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self.send(request, false).await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { @@ -1448,7 +1811,7 @@ impl RemoteTable { Ok(AddResult { version }) } - async fn abort_multipart_write(&self, upload_id: &str) -> Result<()> { + async fn abort_multipart_write(&self, upload_id: &str, retries: Option) -> Result<()> { let request = self.apply_branch_query( self.client .post(&format!( @@ -1457,7 +1820,14 @@ impl RemoteTable { )) .query(&[("upload_id", upload_id)]), ); - let (request_id, response) = self.send(request, true).await?; + let freshness = self.snapshot_freshness_headers(); + let client = self.client.with_retries(retries); + let (request_id, response) = client + .send_with_retry(freshness.apply(request), None, true) + .await?; + if response.status().is_success() { + freshness.observe_headers(&self.freshness, response.headers()); + } self.check_table_response(&request_id, response).await?; Ok(()) } @@ -1543,8 +1913,15 @@ impl RemoteTable { ) -> Result>>> { let mut request = self .client - .post(&format!("/v1/table/{}/query/", self.identifier)); + .post(&format!("/v1/table/{}/query/", self.identifier)) + .header(ACCEPT, QUERY_ACCEPT); + // The timeout bounds the whole query, including reading the response, as + // the server's own deadline for this request does. A deadline too far + // away to represent is never reached. + let deadline = options + .timeout + .and_then(|timeout| Some((tokio::time::Instant::now().checked_add(timeout)?, timeout))); if let Some(timeout) = options.timeout { // Also send to server, so it can abort the query if it takes too long. // (If it doesn't fit into u64, it's not worth sending anyways.) @@ -1568,28 +1945,56 @@ impl RemoteTable { }); let streams = futures::future::try_join_all(futures); - let streams = if let Some(timeout) = options.timeout { - let timeout_future = tokio::time::sleep(timeout); - tokio::pin!(timeout_future); - tokio::pin!(streams); - tokio::select! { - _ = &mut timeout_future => { - return Err(Error::Other { - message: format!("Query timeout after {} ms", timeout.as_millis()), - source: None, - }) - } - result = &mut streams => { - result? - } - } + let streams = if let Some((deadline, timeout)) = deadline { + tokio::time::timeout_at(deadline, streams) + .await + .map_err(|_| Error::Other { + message: format!("Query timeout after {} ms", timeout.as_millis()), + source: None, + })?? } else { streams.await? }; + if let Some(first) = streams.first() { + let schema = first.schema(); + if streams.iter().skip(1).any(|stream| { + stream.schema().metadata().get("lancedb:query_version") + != schema.metadata().get("lancedb:query_version") + }) { + return Err(Error::Runtime { + message: "Remote query responses refer to different table snapshots; retry the query against a fixed version".into(), + }); + } + } + + let identities_agree = streams.first().is_none_or(|first| { + streams.iter().skip(1).all(|stream| { + stream.schema().metadata().get("lancedb:query_snapshot") + == first.schema().metadata().get("lancedb:query_snapshot") + }) + }); Ok(streams .into_iter() - .map(|stream| restore_projection_order(stream, &query.base().select)) + .map(|stream| { + // Ordinary descriptor queries remain usable during an upgrade. + // Deferred bytes require every leg's identity, so never preserve + // the first leg's capability when another leg lacks or differs. + let stream = if identities_agree { + stream + } else { + let mut metadata = stream.schema().metadata().clone(); + metadata.remove("lancedb:query_snapshot"); + with_stream_metadata(stream, metadata) + }; + let stream = restore_projection_order(stream, &query.base().select); + match deadline { + Some((deadline, timeout)) => { + Box::pin(TimeoutStream::with_deadline(stream, timeout, deadline)) + } + None => stream, + } + }) .collect()) } @@ -1632,6 +2037,26 @@ impl RemoteTable { } } +fn with_stream_metadata( + stream: SendableRecordBatchStream, + metadata: HashMap, +) -> SendableRecordBatchStream { + let schema = Arc::new( + stream + .schema() + .as_ref() + .clone() + .with_metadata(metadata.clone()), + ); + let batches = stream.map(move |batch| { + batch.map(|mut batch| { + batch.schema_metadata_mut().clone_from(&metadata); + batch + }) + }); + Box::pin(RecordBatchStreamAdapter::new(schema, batches)) +} + fn restore_projection_order( stream: Pin>, select: &Select, @@ -1683,6 +2108,8 @@ struct TableDescription { version: u64, schema: JsonSchema, location: Option, + #[serde(skip)] + batch_function_declaration: bool, } /// Keep server-owned Function assignment columns out of client schemas. @@ -1713,8 +2140,9 @@ fn schema_from_description(schema: JsonSchema) -> Result { ))) } -/// How a response body frames its Arrow IPC payload. `/query` answers with file framing -/// and `fetch_blobs` with stream framing, so the reader is picked per response. +/// How a response body frames its Arrow IPC payload. `fetch_blobs` answers with stream +/// framing, and `/query` with stream framing only on servers that stream query results, +/// so the reader is picked per response. enum ArrowIpcFraming { File, Stream, @@ -1774,7 +2202,7 @@ fn base_media_type(content_type: &str) -> &str { fn unwrap_shared_error(arc: Arc) -> Error { match Arc::try_unwrap(arc) { Ok(err) => err, - Err(arc) => match &*arc { + Err(arc) => arc.clone_shared().unwrap_or_else(|| match &*arc { Error::TableNotFound { name, source } => Error::TableNotFound { name: name.clone(), source: source.to_string().into(), @@ -1782,10 +2210,11 @@ fn unwrap_shared_error(arc: Arc) -> Error { _ => Error::Runtime { message: arc.to_string(), }, - }, + }), } } +#[allow(clippy::too_many_arguments)] async fn fetch_schema( client: &RestfulLanceDbClient, identifier: &str, @@ -1793,6 +2222,8 @@ async fn fetch_schema( read_snapshot: ReadSnapshot, branch: Option, freshness: Arc>, + blob_ranges_supported: Arc, + blob_locations_supported: Arc, ) -> Result { let mut body = serde_json::json!({ "version": read_snapshot.version }); if let Some(branch) = &branch { @@ -1805,20 +2236,25 @@ async fn fetch_schema( let (request_id, response) = client.send_with_retry(request, None, true).await?; - if response.status() == StatusCode::NOT_FOUND { - let body = response.text().await.ok().unwrap_or_default(); - return Err(Error::TableNotFound { - name: table_name.to_string(), - source: Box::new(Error::Http { - source: body.into(), - request_id, - status_code: Some(StatusCode::NOT_FOUND), - }), - }); - } + let response = + RemoteTable::::handle_table_not_found(table_name, response, &request_id).await?; let response = client.check_response(&request_id, response).await?; freshness_headers.observe_headers(&freshness, response.headers()); + blob_ranges_supported.store( + response + .headers() + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + blob_locations_supported.store( + response + .headers() + .get("x-lancedb-blob-locations") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); let body = response.text().await.map_err(|e| { let status_code = e.status(); Error::Http { @@ -1876,9 +2312,12 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -1903,9 +2342,12 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -1939,51 +2381,107 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } } } +#[derive(Debug)] +struct UnknownWriteOutcome { + upload_id: String, + source: Error, +} + +impl std::fmt::Display for UnknownWriteOutcome { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Multipart write {} commit outcome unknown; no abort or replay was attempted. Check the table before retrying: {}", + self.upload_id, self.source + ) + } +} + +impl std::error::Error for UnknownWriteOutcome { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.source) + } +} + impl RemoteTable { fn is_retryable_write_error(&self, err: &Error) -> bool { + // Transaction conflicts and explicit rate limits reject the write. + // A gateway 5xx says nothing about whether its manifest was committed. + let safe_status = |status| { + matches!(status, StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + && self.client.retry_config.statuses.contains(&status) + }; match err { Error::Http { source, status_code, .. } => { - // Don't retry read errors (is_body/is_decode): the - // server may have committed the write already, and - // without an idempotency key we'd duplicate data. source .downcast_ref::() .is_some_and(|e| e.is_connect()) - || status_code.is_some_and(|s| self.client.retry_config.statuses.contains(&s)) - } - // send_with_retry exhausted its internal retries on a retryable - // status. The outer loop can still retry the whole operation with - // a fresh session. - Error::Retry { status_code, .. } => { - status_code.is_some_and(|s| self.client.retry_config.statuses.contains(&s)) + || status_code.is_some_and(safe_status) } + Error::Retry { status_code, .. } => status_code.is_some_and(safe_status), _ => false, } } + async fn send_write_request( + &self, + request: RequestBuilder, + freshness: FreshnessHeaders, + retries: Option, + ) -> Result<(String, Response)> { + let client = self.client.with_retries(retries); + let mut counter = crate::remote::retry::RetryCounter::new( + &client.retry_config, + uuid::Uuid::new_v4().to_string(), + ); + loop { + let req = request.try_clone().ok_or_else(|| Error::Runtime { + message: "Write request cannot be replayed".into(), + })?; + let result = async { + let (id, response) = client.send(freshness.apply(req)).await?; + let response = self.check_table_response(&id, response).await?; + freshness.observe_headers(&self.freshness, response.headers()); + Ok((id, response)) + } + .await; + match result { + Err(err) if self.is_retryable_write_error(&err) => { + counter.increment_from_error(err)?; + tokio::time::sleep(counter.next_sleep_time()).await; + } + result => return result, + } + } + } + async fn add_single_partition(&self, output: PreprocessingOutput) -> Result { use crate::remote::retry::RetryCounter; let _guard = output.tracker.as_ref().map(|t| t.track_task()); + let client = self.client.with_retries(output.retries); let freshness_request = self.snapshot_freshness_headers(); let mut insert: Arc = Arc::new( RemoteWriteExec::new( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client.clone(), output.plan, WriteOp::Insert { overwrite: output.overwrite, @@ -1998,7 +2496,7 @@ impl RemoteTable { ); let mut retry_counter = - RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); + RetryCounter::new(&client.retry_config, uuid::Uuid::new_v4().to_string()); loop { let stream = execute_plan(insert.clone(), Default::default())?; @@ -2034,61 +2532,82 @@ impl RemoteTable { output: PreprocessingOutput, num_partitions: usize, ) -> Result { - use crate::remote::retry::RetryCounter; - - let mut retry_counter = - RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); - - loop { - let freshness_request = self.snapshot_freshness_headers(); - let upload_id = self.create_multipart_write().await?; - - let result = self - .execute_multipart_inserts(&upload_id, &output, num_partitions) - .await; - - match result { - Ok(()) => match self.complete_multipart_write(&upload_id).await { - Ok(result) => { - if output.overwrite { - self.invalidate_schema_cache(); - } - self.track_write_version(freshness_request, result.version); - return Ok(result); + if let Some(tracker) = &output.tracker { + tracker.use_acknowledged_parts(); + } + let freshness_request = self.snapshot_freshness_headers(); + let upload_id = self.create_multipart_write(output.retries).await?; + if let Err(err) = self + .execute_multipart_inserts(&upload_id, &output, num_partitions) + .await + { + if let Err(abort_err) = self.abort_multipart_write(&upload_id, output.retries).await { + log::warn!( + "Failed to abort multipart write {}: {}", + upload_id, + abort_err + ); + } + return Err(err); + } + // A lost complete response can mean a successful commit. Neither repeat + // complete nor start a new upload session without a server commit token. + let result = match self.complete_multipart_write(&upload_id).await { + Ok(result) => result, + Err(err) => { + let (request_id, status_code) = match &err { + Error::Http { + request_id, + status_code, + .. } - Err(e) => { - if let Err(abort_err) = self.abort_multipart_write(&upload_id).await { - log::warn!( - "Failed to abort multipart write {}: {}", - upload_id, - abort_err - ); - } - if output.rescannable && self.is_retryable_write_error(&e) { - retry_counter.increment_from_error(e)?; - tokio::time::sleep(retry_counter.next_sleep_time()).await; - continue; - } - return Err(e); - } - }, - Err(e) => { - if let Err(abort_err) = self.abort_multipart_write(&upload_id).await { + | Error::Retry { + request_id, + status_code, + .. + } => (request_id.clone(), *status_code), + _ => return Err(err), + }; + // These responses positively reject the commit. Cleanup remains + // best effort and must not replace the original write error. + if matches!( + status_code, + Some(StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + ) { + if let Err(abort_err) = + self.abort_multipart_write(&upload_id, output.retries).await + { log::warn!( - "Failed to abort multipart write {}: {}", + "Failed to abort rejected multipart write {}: {}", upload_id, abort_err ); } - if output.rescannable && self.is_retryable_write_error(&e) { - retry_counter.increment_from_error(e)?; - tokio::time::sleep(retry_counter.next_sleep_time()).await; - continue; - } - return Err(e); + return Err(err); } + if status_code.is_some_and(|status| !status.is_server_error()) { + return Err(err); + } + log::warn!( + "Multipart write {} completion failed; commit outcome may be unknown: {}. Check the table before retrying.", + upload_id, + err + ); + return Err(Error::Http { + request_id, + status_code, + source: Box::new(UnknownWriteOutcome { + upload_id, + source: err, + }), + }); } + }; + if output.overwrite { + self.invalidate_schema_cache(); } + self.track_write_version(freshness_request, result.version); + Ok(result) } async fn execute_multipart_inserts( @@ -2097,10 +2616,7 @@ impl RemoteTable { output: &PreprocessingOutput, num_partitions: usize, ) -> Result<()> { - debug_assert!( - output.rescannable, - "multipart inserts require rescannable input for retry support" - ); + let client = self.client.with_retries(output.retries); let plan = Arc::new( datafusion_physical_plan::repartition::RepartitionExec::try_new( @@ -2113,7 +2629,7 @@ impl RemoteTable { RemoteWriteExec::new_multipart( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client, plan, output.overwrite, upload_id.to_string(), @@ -2344,6 +2860,44 @@ impl RemoteTable { } } +/// Reject per-write layout options that the remote insert protocol cannot carry. +/// +/// Remote inserts only transmit `mode`; file and row-group sizing is managed by +/// the server. Silently dropping these values would produce a different layout +/// than the caller requested. +fn ensure_remote_add_supports_write_params(write_params: Option<&WriteParams>) -> Result<()> { + let Some(write_params) = write_params else { + return Ok(()); + }; + let defaults = WriteParams::default(); + let unsupported: Vec<&str> = [ + ( + "max_rows_per_file", + write_params.max_rows_per_file != defaults.max_rows_per_file, + ), + ( + "max_rows_per_group", + write_params.max_rows_per_group != defaults.max_rows_per_group, + ), + ( + "max_bytes_per_file", + write_params.max_bytes_per_file != defaults.max_bytes_per_file, + ), + ] + .into_iter() + .filter_map(|(name, differs)| differs.then_some(name)) + .collect(); + if unsupported.is_empty() { + return Ok(()); + } + Err(Error::NotSupported { + message: format!( + "write_options.lance_write_params layout options are not supported when adding data to a LanceDB Enterprise table: {}; only mode=overwrite is supported", + unsupported.join(", ") + ), + }) +} + #[async_trait] impl BaseTable for RemoteTable { fn as_any(&self) -> &dyn std::any::Any { @@ -2378,6 +2932,17 @@ impl BaseTable for RemoteTable { source_version: Option, full: bool, ) -> Result> { + self.refresh_materialized_view_async_with_options(source_version, full, Default::default()) + .await + } + + async fn refresh_materialized_view_async_with_options( + &self, + source_version: Option, + full: bool, + options: crate::materialized_view::RefreshMaterializedViewOptions, + ) -> Result> { + let with_clause = options.sql_clause(full)?; self.check_mutable().await?; if source_version.is_some() { return Err(Error::NotSupported { @@ -2391,7 +2956,7 @@ impl BaseTable for RemoteTable { let statement = format!( "REFRESH MATERIALIZED VIEW {}{}", quote_sql_identifier(&self.name), - if full { " WITH (full = true)" } else { "" }, + with_clause, ); let namespace = self.namespace.clone(); let client = self.client.clone(); @@ -2406,6 +2971,13 @@ impl BaseTable for RemoteTable { .submit_materialized_view_job(statement, self.namespace.clone()) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Err(Error::Runtime { + message: + "REFRESH MATERIALIZED VIEW returned a create-only already_exists status" + .into(), + }) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new_typed(Box::new(MaterializedViewRefreshJob { @@ -2446,12 +3018,30 @@ impl BaseTable for RemoteTable { } } } + async fn query_snapshot_with_identity( + &self, + version: u64, + identity: &str, + ) -> Result> { + if version == 0 || !valid_query_snapshot_identity(identity) { + return Err(Error::InvalidInput { + message: "invalid or unsupported query snapshot identity".into(), + }); + } + let mut snapshot = self.with_branch(self.branch.clone()); + *snapshot.version.write().await = Some(version); + snapshot.reset_freshness(None, true); + snapshot.expected_query_snapshot = Some(identity.to_owned()); + Ok(Arc::new(snapshot)) + } + async fn query_snapshot(&self) -> Result> { let description = self.describe().await?; let TableDescription { version, schema, location, + .. } = description; let schema = schema_from_description(schema)?; let snapshot = self.with_branch(self.branch.clone()); @@ -2470,6 +3060,7 @@ impl BaseTable for RemoteTable { version, schema, location, + .. } = description; let schema = schema_from_description(schema)?; let snapshot = self.with_branch(self.branch.clone()); @@ -2519,6 +3110,20 @@ impl BaseTable for RemoteTable { Ok(()) } + async fn checkout_latest_if_latest(&self) -> Result<()> { + let write_guard = self.version.write().await; + if write_guard.is_some() || self.expected_query_snapshot.is_some() { + return Ok(()); + } + // Poll within the same timeline: in-flight writes must still advance + // its watermarks. Only an explicit checkout changes the generation. + let mut state = self.freshness.lock().unwrap(); + let now = SystemTime::now(); + state.checkout_baseline = Some(state.checkout_baseline.map_or(now, |t| t.max(now))); + drop(state); + self.invalidate_schema_cache(); + Ok(()) + } async fn snapshot_at_current_version(&self) -> Result>> { // A checked-out handle already names its snapshot. Otherwise resolve // latest exactly once before creating the independent pinned handle. @@ -2633,6 +3238,8 @@ impl BaseTable for RemoteTable { let table_name = self.name.clone(); let branch = self.branch.clone(); let freshness = self.freshness.clone(); + let blob_ranges_supported = self.blob_ranges_supported.clone(); + let blob_locations_supported = self.blob_locations_supported.clone(); match self .schema_cache @@ -2644,6 +3251,8 @@ impl BaseTable for RemoteTable { read_snapshot, branch, freshness, + blob_ranges_supported, + blob_locations_supported, ) .await }) @@ -2796,7 +3405,9 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/branches/delete/", self.identifier)) .json(&serde_json::json!({ "name": name })); - let (request_id, response) = self.send(request, true).await?; + // Deletion is not idempotent: preserve conflicts and partial failures + // instead of replaying a request that may already have removed the ref. + let (request_id, response) = self.send(request, false).await?; if response.status() == StatusCode::NOT_FOUND { return Err(Error::TableNotFound { name: format!("{} (branch: {})", self.name, name), @@ -2945,6 +3556,7 @@ impl BaseTable for RemoteTable { } async fn add(&self, mut add: AddDataBuilder) -> Result { self.check_mutable().await?; + ensure_remote_add_supports_write_params(add.write_options.lance_write_params.as_ref())?; if add.allow_external_blob_outside_bases { return Err(Error::NotSupported { @@ -2959,6 +3571,7 @@ impl BaseTable for RemoteTable { crate::table::computed_columns::ensure_supported_function_metadata(table_schema.as_ref())?; let table_def = TableDefinition::try_from_rich_schema(table_schema.clone())?; + let mut use_multipart = false; let num_partitions = if self.server_version.support_multipart_write() { // Peek at the first batch to estimate write partitions (same as // NativeTable) and, regardless of `write_parallelism`, to detect a @@ -2971,20 +3584,29 @@ impl BaseTable for RemoteTable { // sends one schema-only request. let mut peeked = PeekedScannable::new(add.data); let n = match peeked.peek().await { - Some(first_batch) => match add.write_parallelism { - Some(parallelism) if parallelism > 1 => parallelism, - Some(_) => 1, - None => { - let max_partitions = - lance_core::utils::tokio::get_num_compute_intensive_cpus(); - estimate_write_partitions( - first_batch.get_array_memory_size(), - first_batch.num_rows(), - peeked.num_rows(), - max_partitions, - ) + Some(first_batch) => { + let estimated_bytes = peeked.num_rows().map(|rows| { + first_batch.get_array_memory_size().saturating_mul(rows) + / first_batch.num_rows().max(1) + }); + // Unknown-length streams also need bounded requests, even + // when they cannot be rescanned or only use one writer. + use_multipart = estimated_bytes.is_none_or(|bytes| bytes > 64 * 1024 * 1024); + match add.write_parallelism { + Some(parallelism) if parallelism > 1 => parallelism, + Some(_) => 1, + None => { + let max_partitions = + lance_core::utils::tokio::get_num_compute_intensive_cpus(); + estimate_write_partitions( + first_batch.get_array_memory_size(), + first_batch.num_rows(), + peeked.num_rows(), + max_partitions, + ) + } } - }, + } None => 1, }; add.data = Box::new(peeked); @@ -3000,7 +3622,7 @@ impl BaseTable for RemoteTable { } let _finish = FinishOnDrop(output.tracker.clone()); - if num_partitions > 1 { + if use_multipart || num_partitions > 1 { self.add_multipart(output, num_partitions).await } else { self.add_single_partition(output).await @@ -3013,9 +3635,9 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result> { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::create_take_offsets_plan(self, request, offsets, options, false) + return crate::query::create_take_plan(self, request, options, request.preserve_order) .await; } @@ -3038,14 +3660,13 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - let plan = crate::query::create_take_offsets_plan( + let plan = crate::query::create_take_plan( self, request, - offsets, options.clone(), - false, + request.preserve_order, ) .await?; let inner = execute_plan(plan, Default::default())?; @@ -3108,9 +3729,10 @@ impl BaseTable for RemoteTable { async fn explain_plan(&self, query: &AnyQuery, verbose: bool) -> Result { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::explain_take_offsets_plan(self, request, offsets, verbose).await; + return crate::query::explain_take_plan(self, request, verbose, request.preserve_order) + .await; } let base_request = self @@ -3166,10 +3788,10 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result { let prepared_query = if let AnyQuery::Query(request) = query - && request.take_offsets.is_some() + && request.has_take() { Some(AnyQuery::Query( - crate::query::prepare_take_offsets_request(self, request).await?, + crate::query::prepare_take_request(self, request).await?, )) } else { None @@ -3244,7 +3866,7 @@ impl BaseTable for RemoteTable { let freshness_request = self.snapshot_freshness_headers(); let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) + .send_write_request(request, freshness_request, update.retries) .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3282,7 +3904,7 @@ impl BaseTable for RemoteTable { .json(&body); let freshness_request = self.snapshot_freshness_headers(); let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) + .send_write_request(request, freshness_request, None) .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3329,6 +3951,7 @@ impl BaseTable for RemoteTable { self.check_mutable().await?; let timeout = params.timeout; + let client = self.client.with_retries(params.retries); let query = MergeInsertRequest::try_from(params)?; // Drive merge_insert through the same RemoteWriteExec streaming path as @@ -3373,7 +3996,7 @@ impl BaseTable for RemoteTable { RemoteWriteExec::new( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client.clone(), input, WriteOp::MergeInsert { query, timeout }, None, @@ -3386,7 +4009,7 @@ impl BaseTable for RemoteTable { ); let mut retry_counter = crate::remote::retry::RetryCounter::new( - &self.client.retry_config, + &client.retry_config, uuid::Uuid::new_v4().to_string(), ); @@ -3405,7 +4028,17 @@ impl BaseTable for RemoteTable { return Ok(merge_result); } Err(err) if rescannable && self.is_retryable_write_error(&err) => { + let status = err.status_code(); retry_counter.increment_from_error(err)?; + log::warn!( + "Retrying merge insert {} after status {:?}; attempt {}", + retry_counter.request_id, + status.map(|s| s.as_u16()), + u16::from(retry_counter.request_failures) + + u16::from(retry_counter.connect_failures) + + u16::from(retry_counter.read_failures) + + 1, + ); tokio::time::sleep(retry_counter.next_sleep_time()).await; merge = merge.reset_state()?; continue; @@ -3614,6 +4247,9 @@ impl BaseTable for RemoteTable { }); } }; + if patch.is_empty() { + return Ok(serde_json::Value::Object(current)); + } Self::merge_table_overrides(&mut current, patch); let merged = serde_json::Value::Object(current); let body = self.table_overrides_set_body(merged); @@ -3650,26 +4286,23 @@ impl BaseTable for RemoteTable { // Resolve the tag without attaching freshness headers; a stale // `min_version` from a previous write should not ride along on an // explicit time-travel request. - let request = self - .client - .post(&format!("/v1/table/{}/tags/version/", self.identifier)); - let version = self - .resolve_tag_version_with_request(tag, request, false) - .await?; + let (branch, version) = self.resolve_tag_ref(tag).await?; + if branch != self.branch { + return Err(Error::InvalidInput { + message: format!( + "Tag '{tag}' belongs to branch '{}', but this table handle is scoped to branch '{}'. Check out the tag's branch first.", + branch.as_deref().unwrap_or("main"), + self.branch.as_deref().unwrap_or("main"), + ), + }); + } - let mut write_guard = self.version.write().await; - // Commit the selector and its freshness mode while holding the selector - // write lock, with no cancellation point between the two updates. - self.reset_freshness(None, true); - *write_guard = Some(version); - self.invalidate_schema_cache(); - drop(write_guard); - - Ok(()) + // Validate the version before pinning the handle. + self.checkout(version).await } - /// Only `OptimizeAction::Compact` with default `options` and no custom + /// Only `OptimizeAction::Compact` with supported `options` and no custom /// `remap_options` is supported remotely: it submits a durable - /// compaction job through the server's `OPTIMIZE TABLE ... REWRITE DATA` + /// compaction job through the server's `OPTIMIZE ... REWRITE DATA` /// SQL statement, the same atomic, single-worker, index-safe path the /// server uses for its own automatic compaction. `.wait()` below waits /// for that SQL statement's own execution to finish, which only confirms @@ -3683,13 +4316,14 @@ impl BaseTable for RemoteTable { /// `OptimizeAction::All`, `::Prune`, and `::Index` remain unsupported /// remotely: there is no SQL statement yet for version pruning or index /// optimization. A branch-scoped table handle submits a - /// `WITH (branch = '')` clause; the statement does not itself - /// validate the branch exists, so a nonexistent branch surfaces as an - /// async job failure rather than an error from this call. A non-default - /// `CompactionOptions` (for example `target_rows_per_fragment` or - /// `max_source_bytes`) is rejected: the SQL statement has no `WITH` - /// clause to carry it yet, so accepting it would silently ignore - /// settings a caller may be relying on to bound the job. + /// `WITH (branch = '')` clause; the server resolves and validates + /// the selected target. Per-job + /// `target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and + /// `batch_size` are forwarded in the SQL `WITH` clause. Other non-default + /// options are rejected before submission. Servers must support these + /// SQL options. Parser errors and unknown optimize option errors become + /// `NotSupported` with the server diagnostic after one SQL submission. + /// No settings are removed and the operation is never resubmitted. async fn optimize(&self, action: OptimizeAction) -> Result { self.check_mutable().await?; let OptimizeAction::Compact { @@ -3712,41 +4346,118 @@ impl BaseTable for RemoteTable { .into(), }); } - if *options != lance::dataset::optimize::CompactionOptions::default() { - return Err(Error::NotSupported { - message: "custom CompactionOptions are not supported in LanceDB \ - Enterprise; the OPTIMIZE TABLE ... REWRITE DATA SQL \ - statement has no WITH clause to carry them yet, so a \ - non-default value would be silently ignored rather than \ - applied. Omit options to use the server's managed \ - compaction settings." - .into(), - }); + let mut overrides = crate::table::optimize::CompactionOverrides::try_from(options.clone())?; + // The legacy Lance options type has no presence bit for this field. + // Use Table::compact to explicitly send a target equal to Lance's default. + if options.target_rows_per_fragment + == crate::table::CompactionOptions::default().target_rows_per_fragment + { + overrides.target_rows_per_fragment = None; } + self.compact(overrides).await + } + + async fn compact( + &self, + options: crate::table::optimize::CompactionOverrides, + ) -> Result { + self.check_mutable().await?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; let sql_client = self.sql_client.clone().ok_or_else(|| Error::NotSupported { message: "SQL is unavailable for this remote table client".to_string(), })?; - let mut statement = format!( - "OPTIMIZE TABLE {} REWRITE DATA", - quote_sql_identifier(&self.name) - ); - if let Some(branch) = &self.branch { - statement.push_str(&format!(" WITH (branch = {})", quote_sql_string(branch))); - } // `OptimizeStats` carries `lance::dataset::optimize` metric types that // are not `Serialize`/`Deserialize`/`Clone`, which `Job` requires, // so the job itself only signals completion; the real (placeholder) // value is built afterward. sql_client .submit_as_job(statement, self.namespace.clone(), || async { Ok(()) }) - .await? + .await + .map_err(optimize::map_optimize_error)? .wait() - .await?; + .await + .map_err(optimize::map_optimize_error)?; Ok(OptimizeStats { compaction: Some(lance::dataset::optimize::CompactionMetrics::default()), prune: None, }) } + async fn explain_cleanup( + &self, + options: crate::table::CleanupOptions, + ) -> Result { + self.check_mutable().await?; + let statement = format!( + "EXPLAIN (FORMAT JSON) {}", + cleanup::statement(&self.name, self.branch.as_deref(), &options)? + ); + let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported { + message: "cleanup previews require a Flight SQL endpoint with EXPLAIN (FORMAT JSON) VACUUM support".into(), + })?; + let query = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + options: Default::default(), + }) + .await + .map_err(cleanup::map_error)?; + let mut reader = query.reader().await.map_err(cleanup::map_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? { + batches.push(batch); + } + cleanup::plan(&batches) + } + + async fn cleanup_async( + &self, + options: crate::table::CleanupOptions, + ) -> Result> { + self.check_mutable().await?; + let statement = cleanup::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "manual cleanup requires a Flight SQL endpoint and SQL VACUUM support" + .into(), + })?; + let submission = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + options: Default::default(), + }) + .await; + JobReceipt::Cleanup.accept(submission, &self.client).await + } + + async fn compact_async( + &self, + options: crate::table::optimize::CompactionOverrides, + ) -> Result> { + self.check_mutable().await?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "compaction jobs require a Flight SQL endpoint".into(), + })?; + let submission = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + options: Default::default(), + }) + .await; + JobReceipt::Compact.accept(submission, &self.client).await + } + async fn add_columns( &self, transforms: NewColumnTransform, @@ -3892,61 +4603,24 @@ impl BaseTable for RemoteTable { application, output_name, )?; - let new_columns = plan - .outputs - .iter() - .map(|output| { - serde_json::json!({ - "name": output.output_name, - "all_null": true, - }) - }) - .collect::>(); - let mut body = serde_json::json!({ - "new_columns": new_columns, - "auto_refresh_enabled": options.auto_refresh_enabled, - "function": { - "application": plan.application, - "binding_metadata_version": plan.binding_metadata_version, - "input_bindings": plan.input_bindings, - "input_schema": plan.input_schema, - "output_schema": plan.output_schema, - "outputs": plan.outputs, - }, - }); - if let Some(interval) = options.auto_refresh_interval_seconds { - body["auto_refresh_interval_seconds"] = serde_json::json!(interval); + self.submit_function_declarations(vec![plan], options).await + } + + async fn add_function_bindings( + &self, + bindings: &[(crate::function::FunctionApplication, Option)], + options: crate::table::computed_columns::ComputedColumnOptions, + ) -> Result { + self.check_mutable().await?; + let description = self.describe().await?; + if !description.batch_function_declaration { + return Err(Error::NotSupported { + message: "This LanceDB Enterprise server does not support declaring multiple Function bindings in one call".into(), + }); } - self.apply_branch_body(&mut body); - let request = self - .client - .post(&format!("/v1/table/{}/add_columns/", self.identifier)) - .json(&body); - let freshness_request = self.snapshot_freshness_headers(); - let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) - .await?; - // A Function declaration can return 404 for the Function rather than the table. - let response = self - .client - .check_response(&request_id, response) - .await - .inspect_err(|error| self.handle_error_invalidation(error))?; - let body = response.text().await.err_to_http(request_id.clone())?; - - if body.trim().is_empty() { - return Ok(AddColumnsResult { version: 0 }); - } - - let result: AddColumnsResult = serde_json::from_str(&body).map_err(|e| Error::Http { - source: format!("Failed to parse add Function columns response: {e}").into(), - request_id, - status_code: None, - })?; - - self.invalidate_schema_cache(); - self.track_write_version(freshness_request, result.version); - Ok(result) + let schema = schema_from_description(description.schema)?; + let plans = crate::table::computed_columns::plan_function_bindings(&schema, bindings)?; + self.submit_function_declarations(plans, options).await } async fn refresh_column(&self, _column: &str) -> Result { @@ -3974,54 +4648,37 @@ impl BaseTable for RemoteTable { ) -> Result> { options.validate()?; self.check_mutable().await?; - let mut body = serde_json::json!({ "column": column }); - if let Some(batch_size) = options.batch_size { - body["batch_size"] = serde_json::json!(batch_size); + if options.retry_errors == Some(true) || options.function_version.is_some() { + self.require_function_failure_workflow().await?; } - if let Some(gpu_class) = options.gpu_class { - body["gpu_class"] = serde_json::json!(gpu_class); - } - if let Some(gpu_count) = options.gpu_count { - body["gpu_count"] = serde_json::json!(gpu_count); - } - self.apply_branch_body(&mut body); - let request = self - .client - .post(&format!("/v1/table/{}/backfill_column", self.identifier)) - .json(&body); - let (request_id, response) = self.send(request, true).await?; - // Preserve dependency errors: a deleted bound Function also returns 404. - let response = self - .client - .check_response(&request_id, response) - .await - .inspect_err(|error| self.handle_error_invalidation(error))?; - let body = response.text().await.err_to_http(request_id.clone())?; - - #[derive(serde::Deserialize)] - struct BackfillResponse { - job_id: String, - } - let response: BackfillResponse = serde_json::from_str(&body).map_err(|e| Error::Http { - source: format!("Failed to parse backfill_column response: {}", e).into(), - request_id, - status_code: None, + let mut body = serde_json::to_value(&options).map_err(|e| Error::Runtime { + message: format!("failed to serialize refresh options: {e}"), })?; + body["column"] = serde_json::json!(column); + self.submit_refresh("backfill_column", body).await + } - Ok(Job::new_typed(Box::new(FreshnessJob { - inner: RemoteJob::new(self.client.clone(), response.job_id), - freshness: self.freshness.clone(), - version: self.version.clone(), - tracked_result: TrackedJobResult::RefreshColumn, - freshness_request: self.snapshot_freshness_headers(), - }))) + async fn resume_refresh( + &self, + job_id: &str, + ) -> Result> { + self.check_mutable().await?; + self.submit_refresh("resume_refresh", serde_json::json!({ "job_id": job_id })) + .await } async fn function_errors( &self, request: &crate::function::FunctionErrorsRequest, ) -> Result { + if request.history { + self.require_function_failure_workflow().await?; + } + let paged = request.page_token.is_some(); let mut body = serde_json::json!({}); + if request.history || paged { + body["history"] = serde_json::json!(true); + } if let Some(job_id) = &request.job_id { body["job_id"] = serde_json::json!(job_id); } @@ -4031,6 +4688,9 @@ impl BaseTable for RemoteTable { if let Some(limit) = request.limit { body["limit"] = serde_json::json!(limit); } + if let Some(token) = &request.page_token { + body["page_token"] = serde_json::json!(token); + } self.apply_branch_body(&mut body); let request = self .client @@ -4039,13 +4699,130 @@ impl BaseTable for RemoteTable { let (request_id, response) = self.send(request, true).await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; - serde_json::from_str(&body).map_err(|e| Error::Http { - source: format!("Failed to parse errors response: {}", e).into(), + let errors: crate::function::FunctionErrors = + serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse errors response: {}", e).into(), + request_id, + status_code: None, + })?; + if paged && errors.truncated && errors.page_token.is_none() { + return Err(Error::NotSupported {message: "server truncated Function errors without a page token; paged errors require server support".to_string()}); + } + Ok(errors) + } + + async fn quarantine_function_errors( + &self, + column: &str, + options: &crate::function::FunctionQuarantineOptions, + ) -> Result { + self.require_function_failure_workflow().await?; + self.check_mutable().await?; + if options.after_attempts == Some(0) { + return Err(Error::InvalidInput { + message: "after_attempts must be at least 1".into(), + }); + } + let mut body = serde_json::json!({"column": column, "quarantined": options.quarantined, + "job_id": options.job_id, "error_type": options.error_type, "after_attempts": options.after_attempts}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/errors/quarantine", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, false).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id: request_id.clone(), + status_code: None, + })?; + value + .get("rows_affected") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| Error::Http { + source: "Function quarantine response has no rows_affected".into(), + request_id, + status_code: None, + }) + } + + async fn function_provenance( + &self, + column: &str, + options: &crate::function::FunctionProvenanceOptions, + ) -> Result { + self.require_function_failure_workflow().await?; + let mut body = serde_json::json!({"column": column, "limit": options.limit, + "version": match options.version { Some(version) => version, None => self.version().await? }}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!( + "/v1/table/{}/function_provenance", + self.identifier + )) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), request_id, status_code: None, }) } + async fn function_column_statuses( + &self, + column: Option<&str>, + ) -> Result> { + let mut request = self.apply_branch_query(self.client.get(&format!( + "/v1/table/{}/function_columns/status", + self.identifier + ))); + if let Some(column) = column { + request = request.query(&[("column", column)]); + } + let read_snapshot = self.snapshot_read_state().await; + if let Some(version) = read_snapshot.version { + request = request.query(&[("version", version)]); + } + let request = read_snapshot.freshness.apply(request); + // A typed finalization-pending 503 is a domain result. Let the caller's + // bounded wait policy handle it instead of a generic 5xx retry loop. + let (request_id, response) = self.client.send_with_retry(request, None, false).await?; + if response.status().is_success() { + read_snapshot + .freshness + .observe_headers(&self.freshness, response.headers()); + } + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let statuses: Vec = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse Function column status response: {error}").into(), + request_id, + status_code: None, + })?; + crate::table::function_column_status::validate_statuses(&statuses)?; + if let Some(requested_version) = read_snapshot.version + && let Some(returned_version) = statuses + .iter() + .map(|status| status.table_version) + .find(|version| *version != requested_version) + { + return Err(Error::Runtime { + message: format!( + "Function column status response returned table version {returned_version}, but the table handle is pinned to version {requested_version}" + ), + }); + } + Ok(statuses) + } + async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result { self.check_mutable().await?; let body = alterations @@ -4215,10 +4992,10 @@ impl BaseTable for RemoteTable { async fn prewarm_index(&self, index_name: &str) -> Result<()> { let encoded_name = urlencoding::encode(index_name); - let request = self.client.post(&format!( + let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/index/{encoded_name}/prewarm/", self.identifier - )); + ))); let (request_id, response) = self.send(request, true).await?; if response.status() == StatusCode::NOT_FOUND { return Err(Error::IndexNotFound { @@ -4230,19 +5007,82 @@ impl BaseTable for RemoteTable { } async fn prewarm_data(&self, columns: Option>) -> Result<()> { - let mut request = self.client.post(&format!( - "/v1/table/{}/page_cache/prewarm/", - self.identifier - )); - let body = serde_json::json!({ - "columns": columns.unwrap_or_default(), - }); - request = request.json(&body); - let (request_id, response) = self.send(request, true).await?; - self.check_table_response(&request_id, response).await?; + self.prewarm_data_async( + crate::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()), + ) + .await?; Ok(()) } + async fn prewarm_data_async( + &self, + options: crate::table::PrewarmDataOptions, + ) -> Result> { + if let Some(version) = *self.version.read().await { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM does not support historical version {version}; use checkout_latest() to prewarm the current branch" + ), + }); + } + let statement = prewarm::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "data prewarm requires a Flight SQL endpoint and SQL PREWARM support" + .into(), + })?; + let submission = client + .execute_prewarm(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: options.parameters, + options: Default::default(), + }) + .await; + JobReceipt::Prewarm.accept(submission, &self.client).await + } + + async fn explain_prewarm_data( + &self, + options: crate::table::PrewarmDataOptions, + ) -> Result { + if let Some(version) = *self.version.read().await { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM does not support historical version {version}; use checkout_latest() to preview the current branch" + ), + }); + } + let statement = format!( + "EXPLAIN (FORMAT JSON) {}", + prewarm::statement(&self.name, self.branch.as_deref(), &options)? + ); + let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported { + message: "data prewarm previews require a Flight SQL endpoint supporting EXPLAIN (FORMAT JSON) PREWARM".into(), + })?; + let query = client + .execute_prewarm(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: options.parameters, + options: Default::default(), + }) + .await + .map_err(prewarm::map_explain_error)?; + let mut reader = query.reader().await.map_err(prewarm::map_explain_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader + .try_next() + .await + .map_err(prewarm::map_explain_error)? + { + batches.push(batch); + } + prewarm::plan(&batches) + } + async fn table_definition(&self) -> Result { let schema = self.schema().await?; TableDefinition::try_from_rich_schema(schema) @@ -4411,8 +5251,8 @@ impl TryFrom for MergeInsertRequest { #[cfg(test)] mod tests { - use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; use std::time::Duration; use std::{collections::HashMap, pin::Pin}; @@ -4429,6 +5269,7 @@ mod tests { BinaryArray, Int32Array, Int64Array, RecordBatch, RecordBatchIterator, StringArray, StructArray, record_batch, }; + use arrow_ipc::reader::StreamReader; use arrow_schema::{DataType, Field, Schema}; use chrono::{DateTime, Utc}; use futures::{StreamExt, TryFutureExt, TryStreamExt, future::BoxFuture}; @@ -4534,6 +5375,19 @@ mod tests { } } + #[tokio::test] + async fn test_delta_not_supported() { + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("table.delta must not send a remote request") + }); + + let error = table.delta(1u64, None).await.unwrap_err(); + assert!( + matches!(error, Error::NotSupported { .. }), + "expected NotSupported, got {error:?}" + ); + } + #[tokio::test] async fn test_version() { let table = Table::new_with_handler("my_table", |request| { @@ -4579,6 +5433,49 @@ mod tests { assert_eq!(schema, expected); } + #[tokio::test] + async fn test_server_info_survives_schema_cache_errors() { + let expected = crate::server_info::ServerBuildInfo { + release: "1.2.3".into(), + git_sha: "0123456789ab".into(), + build_date: Some("2024-01-01T00:00:00Z".into()), + }; + for header_only in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + let response = http::Response::builder().status(404); + if header_only { + response + .header("x-lancedb-server-build", server.to_string()) + .body("missing".to_string()) + .unwrap() + } else { + response + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let original = Arc::new(table.schema().await.unwrap_err()); + // Keep another reader's reference alive to exercise the shared result. + let shared = unwrap_shared_error(original.clone()); + for error in [original.as_ref(), &shared] { + assert!(matches!(error, Error::TableNotFound { name, .. } if name == "my_table")); + assert_eq!(error.status_code(), Some(StatusCode::NOT_FOUND)); + assert_eq!( + error + .remote_error_metadata() + .and_then(|metadata| metadata.server.as_ref()), + Some(&expected), + ); + assert!(error.to_string().contains("0123456789ab")); + } + } + } + #[tokio::test] async fn test_count_rows() { let table = Table::new_with_handler("my_table", |request| { @@ -4815,6 +5712,96 @@ mod tests { assert!(err.to_string().contains("LanceDB Embedded")); } + #[rstest] + #[case("max_rows_per_file")] + #[case("max_rows_per_group")] + #[case("max_bytes_per_file")] + #[tokio::test] + async fn add_rejects_layout_write_params_before_any_request(#[case] field: &str) { + for write_parallelism in [None, Some(2)] { + let table = Table::new_with_handler::("my_table", |request| { + panic!("Unexpected request: {}", request.url().path()) + }); + let data = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let mut params = WriteParams::default(); + match field { + "max_rows_per_file" => params.max_rows_per_file = 50_000, + "max_rows_per_group" => params.max_rows_per_group = 100, + "max_bytes_per_file" => params.max_bytes_per_file = 64 * 1024 * 1024, + other => panic!("unexpected field: {other}"), + } + + let mut add = table.add(data).write_options(crate::table::WriteOptions { + lance_write_params: Some(params), + }); + if let Some(write_parallelism) = write_parallelism { + add = add.write_parallelism(write_parallelism); + } + + let err = add.execute().await.unwrap_err(); + assert!( + matches!(err, Error::NotSupported { .. }), + "{field}: {err:?}" + ); + let message = err.to_string(); + assert!(message.contains(field), "{field}: {message}"); + assert!( + message.contains("only mode=overwrite is supported"), + "{field}: {message}" + ); + } + } + + #[rstest] + #[case(None, false)] + #[case(Some(lance::dataset::WriteMode::Create), false)] + #[case(Some(lance::dataset::WriteMode::Append), false)] + #[case(Some(lance::dataset::WriteMode::Overwrite), true)] + #[tokio::test] + async fn add_preserves_supported_write_params( + #[case] mode: Option, + #[case] expect_overwrite: bool, + ) { + let data = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let describe_body = describe_response(&data.schema()); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_body.clone()) + .unwrap(), + "/v1/table/my_table/insert/" => { + let mode = request + .url() + .query_pairs() + .find(|(k, _)| k == "mode") + .map(|(_, v)| v.into_owned()); + assert_eq!( + mode.as_deref(), + expect_overwrite.then_some("overwrite"), + "unexpected insert mode for {mode:?}" + ); + http::Response::builder() + .status(200) + .body(r#"{"version": 9}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected request path: {}", path), + }); + + let mut add = table.add(data); + if let Some(mode) = mode { + add = add.write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + mode, + ..Default::default() + }), + }); + } + + assert_eq!(add.execute().await.unwrap().version, 9); + } + #[tokio::test] async fn add_string_blob_becomes_uri_struct_without_the_local_flag() { let table_schema = Schema::new(vec![ @@ -5937,6 +6924,27 @@ mod tests { assert_eq!(result.version, if old_server { 0 } else { 43 }); } + #[tokio::test] + async fn test_query_scan_in_order_true_is_not_supported() { + let table = Table::new_with_handler::<&str>("my_table", |_| { + panic!("scan_in_order(true) must fail before sending a request") + }); + + let err = table + .query() + .scan_in_order(true) + .execute() + .await + .err() + .expect("remote scans cannot guarantee manifest order"); + assert!( + matches!(&err, Error::NotSupported { message } + if message.contains("scan_in_order(true)") + && message.contains("Enterprise tables")), + "unexpected error: {err}" + ); + } + #[tokio::test] async fn test_query_plain() { let expected_data = RecordBatch::try_new( @@ -6517,8 +7525,15 @@ mod tests { assert_eq!(request_sizes.lock().unwrap().as_slice(), &[1024, 1]); } + #[rstest::rstest] + #[case(false)] + #[case(true)] #[tokio::test] - async fn test_fetch_blobs_splits_byte_limited_requests_and_reads_large_blob_by_range() { + async fn test_fetch_blobs_splits_byte_limited_requests_and_reads_large_blob_by_range( + #[case] guarded: bool, + ) { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // Simulate a lower byte cap so this test exercises the same 400 response // without allocating 64 MiB of blob data. let requests = Arc::new(std::sync::Mutex::new(Vec::new())); @@ -6527,8 +7542,15 @@ mod tests { "my_table", semver::Version::new(0, 5, 0), move |request| { + if guarded { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + } let path = request.url().path(); if path == "/v1/table/my_table/describe/" { + assert!( + !guarded, + "a later describe cannot establish the producing identity" + ); return http::Response::builder() .status(200) .body(br#"{"version":42,"schema":{"fields":[]}}"#.to_vec()) @@ -6579,6 +7601,7 @@ mod tests { return http::Response::builder() .status(200) .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .body(write_ipc_stream_uncompressed(&batch)) .unwrap(); } @@ -6594,12 +7617,14 @@ mod tests { match range { "bytes=0-0" => http::Response::builder() .status(206) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .header(reqwest::header::CONTENT_RANGE, "bytes 0-0/10") .header(VERSION_HEADER, "42") .body(b"0".to_vec()) .unwrap(), "bytes=0-9" => http::Response::builder() .status(206) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .header(reqwest::header::CONTENT_RANGE, "bytes 0-9/10") .body(b"0123456789".to_vec()) .unwrap(), @@ -6608,6 +7633,14 @@ mod tests { }, ); + let table = if guarded { + table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap() + } else { + table + }; let blobs = table .fetch_blobs("image", &[10, 20, 30, 40, 20]) .await @@ -7083,25 +8116,36 @@ mod tests { assert_eq!(blobs.value(0), b"alpha"); } + // Read as a stream, a file's leading magic declares a message longer than the + // whole body, so the body ends before the stream does. #[rstest] - #[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")))] + #[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")), true)] #[case( ARROW_FILE_CONTENT_TYPE, - write_ipc_stream_uncompressed(&one_row_blob_batch("image")) + write_ipc_stream_uncompressed(&one_row_blob_batch("image")), + false )] #[tokio::test] async fn test_fetch_blobs_fails_when_the_body_contradicts_the_content_type( #[case] content_type: &'static str, #[case] body: Vec, + #[case] ends_early: bool, ) { let table = table_with_fetch_blobs_content_type(Some(content_type), body); let error = table.fetch_blobs("image", &[10]).await.unwrap_err(); - assert!( - matches!(error, Error::Arrow { .. }), - "expected an Arrow decode failure, got {error}" - ); + if ends_early { + assert!( + matches!(error, Error::ResponseInterrupted { batches: 0, .. }), + "expected an incomplete stream, got {error}" + ); + } else { + assert!( + matches!(error, Error::Arrow { .. }), + "expected an Arrow decode failure, got {error}" + ); + } } #[tokio::test] @@ -7373,7 +8417,8 @@ mod tests { #[rstest] #[case::unset(None)] #[case::minimum(Some(0.0))] - #[case::low(Some(0.25))] + #[case::recall80(Some(0.1))] + #[case::recall90(Some(0.25))] #[case::auto(Some(0.5))] #[case::high(Some(0.75))] #[case::maximum(Some(1.0))] @@ -7741,8 +8786,11 @@ mod tests { assert_eq!(result, "analyzed plan"); } + #[rstest::rstest] + #[case::offsets(false)] + #[case::row_ids(true)] #[tokio::test] - async fn test_take_offsets_explain_plan_does_not_execute_query() { + async fn test_take_explain_plan_does_not_execute_query(#[case] by_row_id: bool) { let table = Table::new_with_handler("my_table", |request| { assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/explain_plan/"); @@ -7753,8 +8801,12 @@ mod tests { .unwrap() }); - let explained = table - .take_offsets(vec![0, 1, 0, 2]) + let take = if by_row_id { + table.take_row_ids(vec![0, 1, 0, 2]) + } else { + table.take_offsets(vec![0, 1, 0, 2]) + }; + let explained = take .select(crate::query::Select::columns(&["id"])) .limit(3) .explain_plan(false) @@ -7763,7 +8815,7 @@ mod tests { assert!(explained.contains("GlobalLimitExec")); assert!(explained.contains("TakeRestoreExec")); - assert!(!explained.contains("CoalescePartitionsExec")); + assert_eq!(explained.contains("CoalescePartitionsExec"), by_row_id); assert!(explained.contains("RemoteLookupExec")); } @@ -7783,8 +8835,8 @@ mod tests { Field::new("_rowoffset", DataType::UInt64, false), ])), vec![ - Arc::new(Int32Array::from(vec![5])), - Arc::new(arrow_array::UInt64Array::from(vec![5])), + Arc::new(Int32Array::from(vec![1, 5])), + Arc::new(arrow_array::UInt64Array::from(vec![1, 5])), ], ) .unwrap(); @@ -7796,7 +8848,8 @@ mod tests { }); let request = table - .take_offsets(vec![5, 5]) + .take_offsets(vec![5, 1, 5]) + .preserve_order() .select(crate::query::Select::columns(&["id"])) .into_request(); let batches = table @@ -7808,16 +8861,31 @@ mod tests { .await .unwrap(); - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 3); assert!( batches .iter() .all(|batch| batch.schema().fields().len() == 1) ); + let ids = batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect::>(); + assert_eq!(ids, vec![5, 1, 5]); } + #[rstest::rstest] + #[case::offsets(false)] + #[case::row_ids(true)] #[tokio::test] - async fn test_take_offsets_analyze_plan_delegates_to_remote() { + async fn test_take_analyze_plan_delegates_to_remote(#[case] by_row_id: bool) { let table = Table::new_with_handler("my_table", |request| { assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/analyze_plan/"); @@ -7835,8 +8903,12 @@ mod tests { .unwrap() }); - let analyzed = table - .take_offsets(vec![0, 1, 0, 2]) + let take = if by_row_id { + table.take_row_ids(vec![0, 1, 0, 2]) + } else { + table.take_offsets(vec![0, 1, 0, 2]) + }; + let analyzed = take .select(crate::query::Select::columns(&["id"])) .limit(3) .analyze_plan_with_options(QueryExecutionOptions { @@ -7849,6 +8921,84 @@ mod tests { assert_eq!(analyzed, "Remote analyzed plan: worker metrics"); } + #[rstest::rstest] + #[tokio::test] + async fn test_take_row_ids_restores_remote_order( + #[values(false, true)] with_row_id: bool, + #[values(false, true)] converted: bool, + ) { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/query/"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["columns"], json!(["id"])); + assert_eq!(body["with_row_id"], true); + assert_eq!(body["k"], json!(isize::MAX as usize)); + assert!(body.get("offset").is_none()); + assert!(body["filter"].as_str().unwrap().contains("_rowid IN")); + assert!(body.get("take_row_ids").is_none()); + + // The server can return the physical rows in any order and batches. + let data = arrow_array::record_batch!( + ("id", Int32, [1, 5, 17]), + ("_rowid", UInt64, [1, 5, 17]) + ) + .unwrap(); + let mut response = Vec::new(); + { + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut response, &data.schema()).unwrap(); + writer.write(&data.slice(0, 2)).unwrap(); + writer.write(&data.slice(2, 1)).unwrap(); + writer.finish().unwrap(); + } + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(response) + .unwrap() + }); + let mut take = table + .take_row_ids(vec![17, 5, u64::MAX, 17, 1]) + .select(crate::query::Select::columns(&["id"])) + .offset(1) + .limit(3); + if with_row_id { + take = take.with_row_id(); + } + let options = QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }; + let batches = if converted { + table + .base_table() + .query(&AnyQuery::Query(take.into_request()), options) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + } else { + take.execute_with_options(options) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + }; + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + let actual = arrow::compute::concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"] + .as_primitive::() + .values() + .as_ref(), + &[5, 17, 1] + ); + assert_eq!(actual.column_by_name("_rowid").is_some(), with_row_id); + } + #[tokio::test] async fn test_query_structured_fts() { let table = @@ -8450,6 +9600,103 @@ mod tests { .unwrap(); } + /// Generic index requests use `PLUGIN` and a separate `plugin_type`. Params + /// stay nested so they cannot replace routing fields or request metadata. + #[tokio::test] + async fn test_create_plugin_index_nests_params() { + use crate::index::scalar::PluginIndexBuilder; + + let colliding_params = json!({ + "column": "not_a", + "name": "not_my_index", + "replace": true, + "index_type": "BTREE", + "plugin_type": "ZONEMAP", + "branch": "not_my_branch", + "keys": ["label", "confidence"], + }); + let cases = [ + ( + PluginIndexBuilder::new(" ZoneMap ").unwrap(), + None, + true, + json!({"column": "a", "index_type": "PLUGIN", "plugin_type": "ZONEMAP"}), + ), + ( + PluginIndexBuilder::new("BloomFilter") + .unwrap() + .params(json!({"number_of_items": 4096})) + .unwrap(), + None, + true, + json!({ + "column": "a", + "index_type": "PLUGIN", + "plugin_type": "BLOOMFILTER", + "params": {"number_of_items": 4096}, + }), + ), + ( + PluginIndexBuilder::new("listelement") + .unwrap() + .params(colliding_params.clone()) + .unwrap(), + Some("my_index"), + false, + json!({ + "column": "a", + "index_type": "PLUGIN", + "plugin_type": "LISTELEMENT", + "name": "my_index", + "replace": false, + "params": colliding_params, + }), + ), + ( + PluginIndexBuilder::new("zonemap") + .unwrap() + .params(json!({})) + .unwrap(), + None, + true, + json!({"column": "a", "index_type": "PLUGIN", "plugin_type": "ZONEMAP", "params": {}}), + ), + ]; + + for (plugin, name, replace, expected_body) in cases { + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "POST"); + match request.url().path() { + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap() + } + "/v1/table/my_table/create_index/" => { + let body = request.body().unwrap().as_bytes().unwrap(); + let body: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!(body, expected_body); + http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap() + } + path => panic!("Unexpected path: {}", path), + } + }); + + let mut builder = table + .create_index(&["a"], Index::Plugin(plugin)) + .replace(replace); + if let Some(name) = name { + builder = builder.name(name.to_string()); + } + builder.execute().await.unwrap(); + } + } + #[tokio::test] async fn test_create_index_returns_job() { let describe_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); @@ -8592,6 +9839,7 @@ mod tests { // The server said only that it failed, so nothing may be invented. assert!(failure.message.is_none(), "{failure:?}"); assert!(failure.phase.is_none(), "{failure:?}"); + assert!(failure.traceback.is_none(), "{failure:?}"); assert!(failure.retryable.is_none(), "{failure:?}"); assert_eq!(err.to_string(), "Job job-err failed"); } @@ -8616,7 +9864,7 @@ mod tests { "/v1/jobs/describe" => http::Response::builder() .status(200) .body( - r#"{"job_id": "job-err", "job_state": "FAILED", "failure": {"phase": "commit", "message": "preempted", "retryable": true}}"# + r#"{"job_id": "job-err", "job_state": "FAILED", "failure": {"phase": "commit", "message": "preempted", "traceback": "Traceback (most recent call last):\nValueError: preempted", "retryable": true}}"# .to_string(), ) .unwrap(), @@ -8634,6 +9882,10 @@ mod tests { panic!("expected JobFailed, got {err:?}"); }; assert_eq!(failure.message.as_deref(), Some("preempted")); + assert_eq!( + failure.traceback.as_deref(), + Some("Traceback (most recent call last):\nValueError: preempted") + ); assert_eq!(failure.phase.as_deref(), Some("commit")); assert_eq!(failure.retryable, Some(true)); assert_eq!(err.to_string(), "Job job-err failed: preempted (in commit)"); @@ -10221,8 +11473,13 @@ mod tests { .add_columns() .computed("doubled", "x * 2") .computed_options(crate::table::computed_columns::ComputedColumnOptions { + gpu_class: Default::default(), + gpu_count: Default::default(), auto_refresh_enabled: false, auto_refresh_interval_seconds: interval, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, }) .execute() .await @@ -10231,9 +11488,17 @@ mod tests { } } + #[rstest] + #[case::column_only(None)] + #[case::sixteen(Some(serde_json::json!(16)))] + #[case::eight(Some(serde_json::json!(8)))] + #[case::null(Some(serde_json::Value::Null))] #[tokio::test] - async fn test_add_scalar_function_column_sends_atomic_null_declaration() { - let table = Table::new_with_handler("my_table", |request| { + async fn test_add_scalar_function_column_sends_atomic_null_declaration( + #[case] literal: Option, + ) { + let expected_literal = literal.clone(); + let table = Table::new_with_handler("my_table", move |request| { match request.url().path() { "/v1/table/my_table/describe/" => http::Response::builder() .status(200) @@ -10251,6 +11516,13 @@ mod tests { )) .unwrap(); expected["auto_refresh_enabled"] = serde_json::json!(true); + if let Some(literal) = &expected_literal { + expected["function"]["binding_metadata_version"] = serde_json::json!(2); + expected["function"]["application"]["inputs"] + .as_array_mut().unwrap().push(serde_json::json!({ + "parameter": "num_frames", "kind": "literal", "value": literal, + })); + } assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -10260,18 +11532,179 @@ mod tests { path => panic!("Unexpected path: {path}"), } }); + let mut application: serde_json::Value = serde_json::from_str( + r#"{ + "function":{"name":"embed","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], + "output":{"kind":"scalar","arrow_type":"list","nullable":false} + }"#, + ) + .unwrap(); + if let Some(literal) = literal { + application["inputs"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "parameter": "num_frames", "kind": "literal", "value": literal, + })); + } + let application = crate::function::FunctionApplication::from_json( + &serde_json::to_string(&application).unwrap(), + ) + .unwrap(); + + let result = table + .add_columns() + .function_as("embedding", application) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 8); + } + + #[rstest] + #[case::supported(Some("1"))] + #[case::older_server(None)] + #[case::unknown_version(Some("2"))] + #[tokio::test] + async fn test_declare_function_bindings_in_one_request( + #[case] capability: Option<&'static str>, + ) { + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => { + let mut response = http::Response::builder().status(200); + if let Some(value) = capability { + response = response.header("x-lancedb-batch-function-declaration", value); + } + response.body(r#"{"version":1,"schema":{"fields":[{"name":"text","nullable":true,"type":{"type":"string"}}]}}"#).unwrap() + } + "/v1/table/my_table/add_columns/" => { + assert_eq!(capability, Some("1")); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert!(body.get("function").is_none()); + assert_eq!( + body["new_columns"], + serde_json::json!([ + {"name":"leaf","all_null":true}, {"name":"root","all_null":true} + ]) + ); + let functions = body["functions"].as_array().unwrap(); + assert_eq!(functions.len(), 2); + for (plan, (input, output, nullable)) in functions + .iter() + .zip([("root", "leaf", false), ("text", "root", true)]) + { + assert_eq!( + plan["input_bindings"][0], + serde_json::json!({ + "parameter":"x", "field_path":input, "arrow_type":"utf8", "nullable":nullable + }) + ); + assert_eq!(plan["outputs"][0]["output_name"], output); + assert_eq!(plan["output_schema"]["fields"][0]["name"], output); + } + http::Response::builder() + .status(200) + .body(r#"{"version":2}"#) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + } + }); + let bindings = [("root", "leaf"), ("text", "root")].map(|(input, output)| { + let value = serde_json::json!({ + "function":{"name":"normalize","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "inputs":[{"parameter":"x","kind":"column","value":{"path":input}}], + "output":{"kind":"scalar","arrow_type":"utf8","nullable":false} + }); + (crate::function::FunctionApplication::from_json(&value.to_string()).unwrap(), Some(output.to_string())) + }); + let result = table + .add_columns() + .function_bindings(bindings) + .execute() + .await; + if capability == Some("1") { + assert_eq!(result.unwrap().version, 2); + } else { + assert!(matches!(result, Err(crate::Error::NotSupported { .. }))); + } + } + + #[tokio::test] + async fn test_add_nullable_scalar_function_column_sends_atomic_null_declaration() { + let table = Table::new_with_handler("my_table", |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body( + r#"{"version":1,"schema":{"fields":[{"name":"description","nullable":true,"type":{"type":"string"}}]}}"#, + ) + .unwrap(), + "/v1/table/my_table/add_columns/" => { + let actual: serde_json::Value = serde_json::from_slice( + request.body().unwrap().as_bytes().unwrap(), + ) + .unwrap(); + assert_eq!( + actual["new_columns"], + serde_json::json!([ + {"name": "maybe", "all_null": true} + ]) + ); + assert_eq!( + actual["function"]["application"]["output"], + serde_json::json!({ + "kind": "scalar", + "arrow_type": "int64", + "nullable": true + }) + ); + assert_eq!( + actual["function"]["output_schema"], + serde_json::json!({ + "fields": [{ + "name": "maybe", + "nullable": true, + "type": {"type": "int64"} + }] + }) + ); + assert_eq!( + actual["function"]["outputs"], + serde_json::json!([ + { + "result_field": "$value", + "output_name": "maybe", + "output_ordinal": 0 + } + ]) + ); + assert!(actual["function"].get("assignment").is_none()); + assert_eq!(actual["auto_refresh_enabled"], serde_json::json!(true)); + http::Response::builder() + .status(200) + .body(r#"{"version":8}"#) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + } + }); let application = crate::function::FunctionApplication::from_json( r#"{ - "function":{"name":"embed","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "function":{"name":"nullable_scalar","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], - "output":{"kind":"scalar","arrow_type":"list","nullable":false} + "output":{"kind":"scalar","arrow_type":"int64","nullable":true} }"#, ) .unwrap(); let result = table .add_columns() - .function_as("embedding", application) + .function_as("maybe", application) .execute() .await .unwrap(); @@ -10319,19 +11752,64 @@ mod tests { /// Only a column the binding uses is refused, and it is refused before /// any request goes out; the rest reach the server as usual. + #[rstest] + #[case::column_only(false)] + #[case::literal(true)] #[tokio::test] - async fn test_add_columns_scopes_to_the_columns_a_binding_uses() { - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_response(&fixture_bound_schema())) - .unwrap(), - "/v1/table/my_table/add_columns/" => http::Response::builder() - .status(200) - .body(r#"{"version":10}"#.to_string()) - .unwrap(), - path => panic!("Unexpected path: {path}"), - }); + async fn test_add_columns_scopes_to_the_columns_a_binding_uses(#[case] literal: bool) { + let mut schema = fixture_bound_schema(); + if literal { + let key = crate::table::computed_columns::FUNCTION_BINDINGS_META_KEY; + let mut metadata = schema.metadata().clone(); + let mut envelope: serde_json::Value = + serde_json::from_str(metadata.get(key).unwrap()).unwrap(); + envelope["version"] = serde_json::json!(2); + envelope["bindings"][0]["inputs"] + .as_array_mut() + .unwrap() + .pop(); + envelope["bindings"][0]["literal_inputs"] = + serde_json::json!([{"parameter": "body", "value": null}]); + let binding = + crate::function::FunctionBinding::from_json(&envelope["bindings"][0].to_string()) + .unwrap(); + let fields = schema + .fields() + .iter() + .map(|field| { + let mut field = field.as_ref().clone(); + if let Some(output) = binding + .outputs() + .iter() + .find(|output| output.output_name == *field.name()) + { + field = field.with_metadata( + crate::table::computed_columns::function_computed_column_metadata( + binding.binding_id(), + output.output_ordinal, + &["title".into()], + ), + ); + } + field + }) + .collect::>(); + metadata.insert(key.to_string(), envelope.to_string()); + schema = Schema::new_with_metadata(fields, metadata); + } + let allowed_schema = schema.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&allowed_schema)) + .unwrap(), + "/v1/table/my_table/add_columns/" => http::Response::builder() + .status(200) + .body(r#"{"version":10}"#.to_string()) + .unwrap(), + path => panic!("Unexpected path: {path}"), + }); table .add_columns() .computed("doubled", "spare * 2") @@ -10348,13 +11826,14 @@ mod tests { .await .unwrap(); - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_response(&fixture_bound_schema())) - .unwrap(), - path => panic!("mutation request must not be sent: {path}"), - }); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(), + path => panic!("mutation request must not be sent: {path}"), + }); for name in ["title", "search_text"] { let err = table .add_columns() @@ -10659,6 +12138,11 @@ mod tests { )) .unwrap(); expected["auto_refresh_enabled"] = serde_json::json!(true); + expected["total_cpu_millis"] = serde_json::json!(8000); + expected["total_memory_bytes"] = serde_json::json!(17179869184_u64); + expected["total_gpu_count"] = serde_json::json!(2); + expected["gpu_class"] = serde_json::json!("any"); + expected["gpu_count"] = serde_json::json!(2); assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -10686,6 +12170,15 @@ mod tests { let result = table .add_columns() .function(application) + .computed_options(crate::table::computed_columns::ComputedColumnOptions { + gpu_class: Some("any".into()), + gpu_count: Some(2), + auto_refresh_enabled: true, + auto_refresh_interval_seconds: None, + total_cpu_millis: Some(8000), + total_memory_bytes: Some(17179869184), + total_gpu_count: Some(2), + }) .execute() .await .unwrap(); @@ -10699,7 +12192,7 @@ mod tests { "/v1/table/my_table/describe/" => http::Response::builder() .status(200) .body( - r#"{"version":1,"schema":{"fields":[{"name":"x","nullable":true,"type":{"type":"int32"}}],"metadata":{"lancedb::function_bindings":"{\"version\":2,\"bindings\":[]}"}}}"#, + r#"{"version":1,"schema":{"fields":[{"name":"x","nullable":true,"type":{"type":"int32"}}],"metadata":{"lancedb::function_bindings":"{\"version\":3,\"bindings\":[]}"}}}"#, ) .unwrap(), path => panic!("mutation request must not be sent: {path}"), @@ -10768,6 +12261,19 @@ mod tests { .to_string(), ) .unwrap(), + "/v1/jobs/stats" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], "job-1"); + http::Response::builder() + .status(200) + .body( + r#"{"job_id":"job-1","profile":{},"report":"Function job: finished\nRows: 1600\n"}"# + .to_string(), + ) + .unwrap() + } "/v1/table/ns$view/describe/" => http::Response::builder() .status(200) .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) @@ -10790,6 +12296,10 @@ mod tests { })); assert_eq!(job.id(), Some("job-1")); + assert_eq!( + job.stats().await.unwrap().as_deref(), + Some("Function job: finished\nRows: 1600\n") + ); let observations = Arc::new(Mutex::new(Vec::new())); let observed = observations.clone(); let result: RefreshMaterializedViewResult = if with_progress { @@ -10872,7 +12382,7 @@ mod tests { serde_json::json!({ "column": "quality", "gpu_class": "a10g", - "gpu_count": 2, + "total_gpu_count": 2, }) ); http::Response::builder() @@ -10882,7 +12392,7 @@ mod tests { }); let options = RefreshColumnOptions::default() .gpu_class("a10g") - .gpu_count(2); + .total_gpu_count(2); let job = table .refresh_column_async_with_options("quality", options) .await @@ -10890,9 +12400,291 @@ mod tests { assert_eq!(job.id(), Some("j-gpu")); } + #[rstest] + #[case(None, 0)] + #[case(Some(2), 2)] + #[tokio::test] + async fn test_refresh_column_async_resource_budget( + #[case] total_gpu_count: Option, + #[case] expected_gpu_count: u32, + ) { + use crate::table::{FunctionWorkerResourceBudget, RefreshColumnOptions}; + + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "total_cpu_millis": 8_000, + "total_memory_bytes": 17_179_869_184_u64, + "total_gpu_count": expected_gpu_count, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j-budget"}"#) + .unwrap() + }); + let mut budget = FunctionWorkerResourceBudget::new(8_000, 17_179_869_184); + if let Some(total_gpu_count) = total_gpu_count { + budget = budget.with_total_gpu_count(total_gpu_count); + } + let job = table + .refresh_column_async_with_options( + "quality", + RefreshColumnOptions::default() + .total_cpu_millis((budget).total_cpu_millis) + .total_memory_bytes((budget).total_memory_bytes) + .total_gpu_count((budget).total_gpu_count), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-budget")); + } + + #[tokio::test] + async fn test_refresh_column_async_structured_resource_options() { + use crate::table::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, RefreshColumnOptions, + }; + + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "supervisor_resources": { + "cpu_millis": 2_000, + "memory_bytes": 4_294_967_296_u64, + "ephemeral_storage_bytes": 10_737_418_240_u64, + }, + "planning_workers": { + "resources": { + "cpu_millis": 1_000, + "memory_bytes": 2_147_483_648_u64, + "ephemeral_storage_bytes": 5_368_709_120_u64, + }, + "max_workers": 4, + "rows_per_worker": 100_000, + "fragments_per_worker": 8, + }, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j-structured"}"#) + .unwrap() + }); + let supervisor = FunctionRefreshPodResources::new(2_000, 4_294_967_296, 10_737_418_240); + let planning = FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1_000, 2_147_483_648, 5_368_709_120), + 4, + 100_000, + 8, + ); + let job = table + .refresh_column_async_with_options( + "quality", + RefreshColumnOptions::default() + .supervisor_resources(supervisor) + .planning_workers(planning), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-structured")); + } + + #[tokio::test] + async fn test_refresh_column_async_retry_policy() { + use crate::function::{FunctionErrorPolicy, FunctionRetryPolicy}; + use crate::table::RefreshColumnOptions; + let policy = FunctionRetryPolicy::transient(); + let expected_policy = serde_json::to_value(&policy).unwrap(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column":"quality", "retry_policy": expected_policy, "error_policy":"skip", + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j-retry"}"#.to_string()) + .unwrap() + }); + let options = RefreshColumnOptions::default() + .retry_policy(policy) + .error_policy(FunctionErrorPolicy::Skip); + assert_eq!( + table + .refresh_column_async_with_options("quality", options) + .await + .unwrap() + .id(), + Some("j-retry") + ); + } + + #[tokio::test] + async fn test_refresh_column_async_filter_and_failure_options() { + use crate::function::FunctionErrorPolicy; + use crate::table::RefreshColumnOptions; + + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "where": "id % 2 = 0", + "max_concurrency": 3, + "publication_interval_rows": 60, + "error_policy": "skip", + "max_failed_fraction": 0.01, + "max_failed_rows": 50, + "row_timeout_seconds": 30.0, + "init_timeout_seconds": 120.0, + "num_workers": 4, + "max_executor_processes_per_worker": 2, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-filtered"}"#) + .unwrap() + }); + let options = RefreshColumnOptions::default() + .where_clause("id % 2 = 0") + .max_concurrency(3) + .publication_interval_rows(60) + .error_policy(FunctionErrorPolicy::Skip) + .max_failed_fraction(0.01) + .max_failed_rows(50) + .row_timeout_seconds(30.0) + .init_timeout_seconds(120.0) + .num_workers(4) + .max_executor_processes_per_worker(2); + let job = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-filtered")); + } + + #[tokio::test] + async fn test_refresh_column_rejects_invalid_filter_and_limit_options_before_request() { + use crate::table::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, RefreshColumnOptions, + }; + + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("invalid refresh options must not send a request") + }); + for (options, expected) in [ + (RefreshColumnOptions::default().where_clause(" "), "where"), + ( + RefreshColumnOptions::default().max_failed_fraction(1.5), + "max_failed_fraction", + ), + ( + RefreshColumnOptions::default().max_failed_fraction(f64::NAN), + "max_failed_fraction", + ), + ( + RefreshColumnOptions::default().row_timeout_seconds(0.0), + "row_timeout_seconds", + ), + ( + RefreshColumnOptions::default().init_timeout_seconds(f64::INFINITY), + "init_timeout_seconds", + ), + ( + RefreshColumnOptions::default().num_workers(0), + "num_workers", + ), + ( + RefreshColumnOptions::default().max_concurrency(0), + "max_concurrency", + ), + ( + RefreshColumnOptions::default().max_job_attempts(0), + "max_job_attempts", + ), + ( + RefreshColumnOptions::default().max_executor_processes_per_worker(0), + "max_executor_processes_per_worker", + ), + ( + RefreshColumnOptions::default().publication_interval_rows(0), + "publication_interval_rows", + ), + ( + RefreshColumnOptions::default() + .supervisor_resources(FunctionRefreshPodResources::new(0, 1, 1)), + "supervisor_resources.cpu_millis", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 0), + 1, + 1, + 1, + ), + ), + "planning_workers.resources.ephemeral_storage_bytes", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 0, + 1, + 1, + ), + ), + "planning_workers.max_workers", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 1, + 0, + 1, + ), + ), + "planning_workers.rows_per_worker", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 1, + 1, + 0, + ), + ), + "planning_workers.fragments_per_worker", + ), + ] { + let error = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap_err(); + assert!( + matches!(&error, Error::InvalidInput { message } if message.contains(expected)), + "{error:?}" + ); + } + } + #[tokio::test] async fn test_refresh_column_rejects_invalid_gpu_options_before_request() { - use crate::table::RefreshColumnOptions; + use crate::table::{FunctionWorkerResourceBudget, RefreshColumnOptions}; let table = Table::new_with_handler("my_table", |_| -> http::Response { panic!("invalid GPU options must not send a request") @@ -10906,7 +12698,24 @@ mod tests { RefreshColumnOptions::default().gpu_class("-a10g"), "gpu_class", ), - (RefreshColumnOptions::default().gpu_count(0), "gpu_count"), + ( + RefreshColumnOptions::default() + .total_cpu_millis((FunctionWorkerResourceBudget::new(0, 1)).total_cpu_millis) + .total_memory_bytes( + (FunctionWorkerResourceBudget::new(0, 1)).total_memory_bytes, + ) + .total_gpu_count((FunctionWorkerResourceBudget::new(0, 1)).total_gpu_count), + "total_cpu_millis", + ), + ( + RefreshColumnOptions::default() + .total_cpu_millis((FunctionWorkerResourceBudget::new(1, 0)).total_cpu_millis) + .total_memory_bytes( + (FunctionWorkerResourceBudget::new(1, 0)).total_memory_bytes, + ) + .total_gpu_count((FunctionWorkerResourceBudget::new(1, 0)).total_gpu_count), + "total_memory_bytes", + ), ] { let error = table .refresh_column_async_with_options("quality", options) @@ -11006,6 +12815,855 @@ mod tests { assert_eq!(schema_requests.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn test_function_column_status_decodes_one_exact_snapshot() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().path(), + "/v1/table/my_table/function_columns/status" + ); + assert_eq!(request.url().query(), None); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":10, + "fresh":6, + "stale":2, + "never_computed":1, + "failed":1, + "last_refresh_job":{ + "job_id":"job-7", + "state":"finished", + "automatic":true, + "completed_at_millis":1790000000000 + }, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "active_job_id":null, + "state":"unobservable", + "failure_streak":0, + "next_run_at_millis":null, + "next_run_at_reason":"authoritative_scheduler_projection_unavailable" + } + }]"#, + ) + .unwrap() + }); + + let statuses = table.function_column_statuses(None).await.unwrap(); + assert_eq!(statuses.len(), 1); + assert_eq!(statuses[0].table_version, 42); + assert_eq!(statuses[0].failed, 1); + assert_eq!( + statuses[0] + .last_refresh_job + .as_ref() + .map(|job| job.job_id.as_str()), + Some("job-7") + ); + assert_eq!( + statuses[0].auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Unobservable + ); + } + + #[tokio::test] + async fn test_function_column_status_filters_with_a_get_query() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "GET"); + assert_eq!(request.url().query(), Some("column=embedding")); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!(status.column, "embedding"); + assert!(status.last_refresh_job.is_none()); + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Disabled + ); + } + + #[tokio::test] + async fn test_wait_for_function_column_retries_only_typed_finalization_pending() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .header( + "x-lancedb-error-code", + crate::table::function_column_status::FINALIZATION_PENDING_ERROR_CODE, + ) + .body(b"finalization pending".to_vec()) + .unwrap() + } else { + http::Response::builder() + .status(200) + .body( + br#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"# + .to_vec(), + ) + .unwrap() + } + } + }); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_finalization_code_on_other_status_is_not_retried() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + calls.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .header( + "x-lancedb-error-code", + crate::table::function_column_status::FINALIZATION_PENDING_ERROR_CODE, + ) + .body(b"misclassified pending".to_vec()) + .unwrap() + } + }); + + let error = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap_err(); + assert!(error.to_string().contains("misclassified pending")); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_wait_for_function_column_does_not_retry_generic_500() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + calls.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(b"corrupt freshness evidence".to_vec()) + .unwrap() + } + }); + + let error = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap_err(); + assert!(error.to_string().contains("corrupt freshness evidence")); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_wait_for_function_column_observes_latest_publications_without_checkout() { + let calls = Arc::new(AtomicUsize::new(0)); + let observed_headers = Arc::new(Mutex::new(Vec::new())); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + let observed_headers = observed_headers.clone(); + move |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().path(), + "/v1/table/my_table/function_columns/status" + ); + let query: std::collections::BTreeMap<_, _> = request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert!( + !query.contains_key("version"), + "a latest status poll must not use an explicit version" + ); + + let min_timestamp = request + .headers() + .get("x-lancedb-min-timestamp") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let min_read_version = request + .headers() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + observed_headers + .lock() + .unwrap() + .push((min_timestamp.clone(), min_read_version)); + + let call = calls.fetch_add(1, Ordering::SeqCst); + let (version, fresh, never_computed) = if call > 0 && min_timestamp.is_some() { + (11, 2, 0) + } else { + (4, 0, 2) + }; + http::Response::builder() + .status(200) + .header("x-lancedb-version", version.to_string()) + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":{version}, + "rows":2, + "fresh":{fresh}, + "stale":0, + "never_computed":{never_computed}, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + }); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 11); + assert_eq!(status.fresh, 2); + assert_eq!(status.never_computed, 0); + assert_eq!(calls.load(Ordering::SeqCst), 2); + + let observed_headers = observed_headers.lock().unwrap(); + assert_eq!(observed_headers.len(), 2); + assert!( + observed_headers[0].0.is_some(), + "the first latest poll must establish a current timestamp baseline" + ); + assert!( + observed_headers[1].0.is_some(), + "each latest poll must advance the timestamp baseline" + ); + assert_eq!( + observed_headers[1].1.as_deref(), + Some("4"), + "the latest poll must retain the monotonic read watermark" + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_wait_for_function_column_preserves_inflight_write_fence() { + let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = std::sync::Arc::new(std::sync::Mutex::new(release_rx)); + let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let captured = requests.clone(); + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/update/" => { + arrived_tx.send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(std::time::Duration::from_secs(15)) + .unwrap(); + http::Response::builder() + .status(200) + .header("x-lancedb-version", "5") + .body(r#"{"rows_updated":2,"version":5}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + // This node caches version 4 during the status request, + // after its timestamp fence and before the write commits. + assert!(request.headers().contains_key("x-lancedb-min-timestamp")); + http::Response::builder() + .status(200) + .header("x-lancedb-version", "4") + .body( + r#"[{"column":"embedding","binding_id":"fb_01", + "function":{"name":"embed","object_id":"embed", + "location":"objects/embed","version":"7", + "manifest_digest":"sha256:abc"}, + "table_version":4,"rows":2,"fresh":2,"stale":0, + "never_computed":0,"failed":0, + "auto_refresh":{"enabled":false,"state":"disabled", + "failure_streak":0,"next_run_at_millis":null}}]"# + .to_string(), + ) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + captured.lock().unwrap().push(request.headers().clone()); + // The timestamp still admits the cached pre-write view. + // The write-version fence is what must force a refresh. + let count = if request + .headers() + .get("x-lancedb-min-version") + .and_then(|v| v.to_str().ok()) + == Some("5") + { + "2" + } else { + "1" + }; + http::Response::builder() + .status(200) + .body(count.to_string()) + .unwrap() + } + path => panic!("unexpected path: {path}"), + } + }); + let update = tokio::spawn({ + let table = table.clone(); + async move { table.update().column("a", "a + 1").execute().await } + }); + tokio::task::spawn_blocking(move || { + arrived_rx + .recv_timeout(std::time::Duration::from_secs(15)) + .unwrap() + }) + .await + .unwrap(); + table + .wait_for_function_column("embedding", Some(std::time::Duration::from_secs(2))) + .await + .unwrap(); + release_tx.send(()).unwrap(); + assert_eq!(update.await.unwrap().unwrap().version, 5); + // With initial values [0, 1], a += 1 changes a > 0 from one row to two. + let count = table.count_rows(Some("a > 0".to_string())).await.unwrap(); + let requests = requests.lock().unwrap(); + let headers = &requests[0]; + assert_eq!( + headers + .get("x-lancedb-min-version") + .and_then(|v| v.to_str().ok()), + Some("5"), + "polling must not discard an in-flight write's returned version" + ); + assert_eq!( + count, 2, + "read after completed write must observe the write" + ); + } + + #[tokio::test] + async fn test_wait_for_function_column_does_not_unpin_a_pinned_handle() { + let status_calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let status_calls = status_calls.clone(); + move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + assert_eq!(request_body_json(&request)["version"], 42); + http::Response::builder() + .status(200) + .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + let query: std::collections::BTreeMap<_, _> = + request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert_eq!(query.get("version").map(|value| value.as_ref()), Some("42")); + assert!( + !request.headers().contains_key("x-lancedb-min-timestamp"), + "a pinned status poll must not carry latest freshness headers" + ); + let call = status_calls.fetch_add(1, Ordering::SeqCst); + let (fresh, never_computed) = if call == 0 { (0, 2) } else { (2, 0) }; + http::Response::builder() + .status(200) + .header("x-lancedb-version", "42") + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":42, + "rows":2, + "fresh":{fresh}, + "stale":0, + "never_computed":{never_computed}, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + table.checkout(42).await.unwrap(); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(status.fresh, 2); + assert_eq!(status.never_computed, 0); + assert_eq!(status_calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_function_column_status_decodes_agent_up_to_date() { + let table = Table::new_with_handler("my_table", |_request| { + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":4, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"up_to_date", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::UpToDate + ); + } + + #[tokio::test] + async fn test_function_column_status_decodes_scheduler_lifecycle_and_failures() { + let table = Table::new_with_handler("my_table", |_request| { + http::Response::builder() + .status(200) + .body( + r#"[ + { + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":2, + "stale":2, + "never_computed":0, + "failed":0, + "last_refresh_job":{ + "job_id":"job-cancelled", + "state":"cancelled", + "automatic":true, + "completed_at_millis":1790000002000 + }, + "last_failure_job":{ + "job_id":"job-failed", + "state":"failed", + "automatic":true, + "completed_at_millis":1790000001000, + "failure":{ + "phase":"finalize", + "message":"worker timed out", + "traceback":"Traceback: timeout", + "retryable":true, + "sql_job_id":"sql-job-7" + } + }, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "active_job_id":"job-queued", + "state":"queued", + "failure_streak":1, + "next_run_at_millis":null, + "next_run_at_reason":"job_queued_not_started" + } + }, + { + "column":"rerank", + "binding_id":"fb_02", + "function":{ + "name":"rerank", + "object_id":"rerank", + "location":"objects/rerank", + "version":"3", + "manifest_digest":"sha256:def" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":5, + "blocked_reason":"failure_threshold_reached", + "next_run_at_millis":null + } + }, + { + "column":"classify", + "binding_id":"fb_03", + "function":{ + "name":"classify", + "object_id":"classify", + "location":"objects/classify", + "version":"2", + "manifest_digest":"sha256:ghi" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":0, + "blocked_reason":"binding_revision_missing", + "next_run_at_millis":null + } + }, + { + "column":"summarize", + "binding_id":"fb_04", + "function":{ + "name":"summarize", + "object_id":"summarize", + "location":"objects/summarize", + "version":"4", + "manifest_digest":"sha256:jkl" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":3, + "effective_cooldown_millis":8000, + "blocked_reason":"preparation_backoff", + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let statuses = table.function_column_statuses(None).await.unwrap(); + assert_eq!(statuses.len(), 4); + let status = &statuses[0]; + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Queued + ); + assert_eq!( + status.auto_refresh.active_job_id.as_deref(), + Some("job-queued") + ); + assert_eq!( + status.auto_refresh.next_run_at_reason.as_deref(), + Some("job_queued_not_started") + ); + assert_eq!( + status + .last_refresh_job + .as_ref() + .map(|job| job.state.as_str()), + Some("cancelled") + ); + let failure_job = status.last_failure_job.as_ref().unwrap(); + assert_eq!(failure_job.job_id, "job-failed"); + let failure = failure_job.failure.as_ref().unwrap(); + assert_eq!(failure.phase.as_deref(), Some("finalize")); + assert_eq!(failure.message.as_deref(), Some("worker timed out")); + assert_eq!(failure.retryable, Some(true)); + assert_eq!(failure.sql_job_id.as_deref(), Some("sql-job-7")); + + assert_eq!(statuses[1].auto_refresh.failure_streak, 5); + assert_eq!( + statuses[1].auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::FailureThresholdReached) + ); + assert_eq!( + statuses[2].auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::BindingRevisionMissing) + ); + assert_eq!(statuses[3].auto_refresh.failure_streak, 3); + assert_eq!( + statuses[3].auto_refresh.effective_cooldown_millis, + Some(8000) + ); + assert_eq!( + statuses[3].auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::PreparationBackoff) + ); + } + + #[tokio::test] + async fn test_function_column_status_passes_a_pinned_version() { + let calls = Arc::new(AtomicUsize::new(0)); + let status_calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + let status_calls = status_calls.clone(); + move |request| { + calls.fetch_add(1, Ordering::SeqCst); + match request.url().path() { + "/v1/table/my_table/describe/" => { + assert_eq!(request_body_json(&request)["version"], 42); + http::Response::builder() + .status(200) + .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + assert_eq!(request.method(), "GET"); + let query: std::collections::BTreeMap<_, _> = + request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert_eq!(query.get("version").map(|value| value.as_ref()), Some("42")); + let returned_version = if status_calls.fetch_add(1, Ordering::SeqCst) == 0 { + 42 + } else { + 43 + }; + http::Response::builder() + .status(200) + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":{returned_version}, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + } + }); + table.checkout(42).await.unwrap(); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(calls.load(Ordering::SeqCst), 2); + + let error = table.function_column_status("embedding").await.unwrap_err(); + assert!( + error.to_string().contains( + "returned table version 43, but the table handle is pinned to version 42" + ) + ); + assert_eq!(status_calls.load(Ordering::SeqCst), 2); + assert_eq!(calls.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn test_function_column_status_keeps_latest_freshness_headers() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().query_pairs().collect::>(), + vec![( + std::borrow::Cow::Borrowed("column"), + std::borrow::Cow::Borrowed("embedding") + )] + ); + assert_eq!( + request + .headers() + .get("x-lancedb-min-version") + .and_then(|value| value.to_str().ok()), + Some("7") + ); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }, + None, + ); + table.freshness.lock().unwrap().min_version = Some(7); + + let statuses = table + .function_column_statuses(Some("embedding")) + .await + .unwrap(); + assert_eq!(statuses.len(), 1); + } + /// The error listing is table-addressed with optional job and column /// filters, mirroring the server's SQL surface, and the two non-record /// signals come back as their own fields rather than as rows. @@ -11026,10 +13684,11 @@ mod tests { .status(200) .body( r#"{"records": [{"job_id": "j-7", "fragment_id": 3, "row_offset": 9, - "row_address": 12884901897, + "row_id": 42, "row_address": 12884901897, "column": "embedding", "function": "embed", "function_version": "2", "table_version": 11, "error_type": "ValueError", - "error_message": "bad input 'x'", "created_at_millis": 1700000000000}], + "error_message": "bad input 'x'", "traceback": "Traceback (most recent call last):\nValueError: bad input 'x'", + "created_at_millis": 1700000000000, "attempts": 3}], "fragments": [{"job_id": "j-7", "fragment_id": 4, "rows_skipped": 500, "rows_recorded": 100}], "truncated": true}"#, @@ -11049,9 +13708,15 @@ mod tests { assert_eq!( errors.records, [FunctionErrorRecord { + first_seen_at_millis: None, + last_seen_at_millis: None, + quarantined: false, + input: None, + attempts: Some(3), job_id: "j-7".into(), fragment_id: 3, row_offset: Some(9), + row_id: Some(42), row_address: Some(12_884_901_897), column: "embedding".into(), function: "embed".into(), @@ -11059,6 +13724,9 @@ mod tests { table_version: 11, error_type: "ValueError".into(), error_message: "bad input 'x'".into(), + traceback: Some( + "Traceback (most recent call last):\nValueError: bad input 'x'".into() + ), created_at_millis: 1_700_000_000_000, }] ); @@ -11073,7 +13741,8 @@ mod tests { ); assert!(errors.truncated); - // Servers before row_address omit it; the record still decodes. + // Servers before row_address or row_id omit them; the record still + // decodes. let legacy: FunctionErrorRecord = serde_json::from_value(serde_json::json!({ "job_id": "j-6", "fragment_id": 2, @@ -11087,7 +13756,9 @@ mod tests { "created_at_millis": 1_700_000_000_000_i64, })) .unwrap(); + assert!(legacy.row_id.is_none()); assert!(legacy.row_address.is_none()); + assert!(legacy.traceback.is_none()); // No filter sends no filter, and an empty listing reads as such. let table = Table::new_with_handler("my_table", |request| { @@ -11154,11 +13825,31 @@ mod tests { .body(events.clone()) .unwrap() } + "/v1/jobs/stats" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], "j-42"); + http::Response::builder() + .status(200) + .body( + r#"{"job_id":"j-42","profile":{},"report":"Function job: finished\nRows: 1600\n"}"# + .as_bytes() + .to_vec(), + ) + .unwrap() + } + "/v1/jobs/timeline" => http::Response::builder().status(200) + .body(br#"{"traceEvents":[],"metadata":{"partial":true}}"#.to_vec()).unwrap(), other => panic!("unexpected path {other}"), } }); let job = table.refresh_column_async("doubled").await.unwrap(); + assert_eq!( + job.stats().await.unwrap().as_deref(), + Some("Function job: finished\nRows: 1600\n") + ); job.refresh().await.unwrap(); assert_eq!(job.state().as_deref(), Some("running")); assert_eq!(job.job_type().as_deref(), Some("refresh_column")); @@ -11170,6 +13861,7 @@ mod tests { .await .unwrap(); assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(job.timeline().await.unwrap()["metadata"]["partial"], true); } /// A newly submitted refresh returns a freshness-wrapped handle. Waiting @@ -11251,6 +13943,84 @@ mod tests { ); } + #[tokio::test] + async fn retrying_a_refresh_preserves_result_decoding_and_read_freshness() { + let saw_version = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let observed = saw_version.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let body = match request.url().path() { + "/v1/table/my_table/backfill_column" => r#"{"job_id":"attempt-1"}"#.to_string(), + "/v1/jobs/retry" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], "attempt-1"); + r#"{"job_id":"attempt-2"}"#.to_string() + } + "/v1/jobs/describe" => refresh_done("attempt-2"), + "/v1/table/my_table/count_rows/" => { + observed.store( + request + .headers() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()) + == Some("8"), + Ordering::SeqCst, + ); + "1".to_string() + } + path => panic!("unexpected path {path}"), + }; + http::Response::builder() + .status(if request.url().path().ends_with("backfill_column") { + 202 + } else { + 200 + }) + .body(body) + .unwrap() + }); + let submitted = table.refresh_column_async("doubled").await.unwrap(); + let retry = submitted.retry().await.unwrap(); + assert_eq!(retry.id(), Some("attempt-2")); + assert_eq!(retry.wait().await.unwrap().rows_assigned, 12); + table.count_rows(None).await.unwrap(); + assert!(saw_version.load(Ordering::SeqCst)); + } + + #[tokio::test] + async fn paged_row_errors_preserve_tokens_and_refuse_silent_truncation() { + for legacy in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["page_token"], ""); + assert_eq!(body["history"], true); + assert_eq!(body["job_id"], "attempt-1"); + let mut response = json!({"records":[],"fragments":[],"truncated":true}); + if !legacy { + response["page_token"] = json!("next"); + } + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let result = table + .function_errors( + crate::function::FunctionErrorsRequest::new() + .job_id("attempt-1") + .page_token(""), + ) + .await; + if legacy { + assert!(matches!(result, Err(Error::NotSupported { .. }))); + } else { + assert_eq!(result.unwrap().page_token.as_deref(), Some("next")); + } + } + } + /// Index submissions use the same freshness wrapper. Its wait must forward /// observations and retain the successful-wait timestamp bookkeeping. #[tokio::test] @@ -11684,35 +14454,48 @@ mod tests { } #[tokio::test] - async fn test_prewarm_data() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/table/my_table/page_cache/prewarm/" + async fn test_prewarm_data_requires_sql_without_rest_fallback() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!( + "data prewarm must not submit through REST: {}", + request.url() ); - http::Response::builder().status(200).body("{}").unwrap() }); - table.prewarm_data(None).await.unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("SQL")); } #[tokio::test] - async fn test_prewarm_data_with_columns() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/table/my_table/page_cache/prewarm/" - ); - let body = request.body().unwrap().as_bytes().unwrap(); - let body: serde_json::Value = serde_json::from_slice(body).unwrap(); - assert_eq!(body["columns"], serde_json::json!(["col_a", "col_b"])); - http::Response::builder().status(200).body("{}").unwrap() - }); - table - .prewarm_data(Some(vec!["col_a".into(), "col_b".into()])) + async fn test_prewarm_index_sends_the_checked_out_branch() { + use lance::dataset::refs::Ref; + + let table = + Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { + match request.url().path() { + "/v1/table/my_table/branches/create/" => { + http::Response::builder().status(200).body("{}").unwrap() + } + "/v1/table/my_table/index/my_index/prewarm/" => { + let branch = request + .url() + .query_pairs() + .find(|(key, _)| key == "branch") + .map(|(_, value)| value.into_owned()); + assert_eq!(branch.as_deref(), Some("feature/dev")); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"prewarm-job"}"#) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let branch = table + .create_branch("feature/dev", Ref::Version(None, None)) .await .unwrap(); + branch.prewarm_index("my_index").await.unwrap(); } #[tokio::test] @@ -12050,6 +14833,31 @@ mod tests { assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2); } + #[tokio::test] + async fn test_update_table_overrides_empty_patch_only_reads() { + for current in [ + serde_json::json!({}), + serde_json::json!({"job_types": {"compaction": {"enabled": false}}}), + ] { + let snapshot = current.clone(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "GET"); + assert_eq!(request.url().path(), "/admin/table/overrides"); + http::Response::builder() + .status(200) + .body(snapshot.to_string()) + .unwrap() + }); + assert_eq!( + table + .update_table_overrides(serde_json::json!({})) + .await + .unwrap(), + current + ); + } + } + #[tokio::test] async fn test_reset_table_overrides() { let table = Table::new_with_handler("my_table", |request| { @@ -13380,12 +16188,13 @@ mod tests { .checkout_tag("v2") .await .expect("checkout_tag should succeed"); + assert_eq!(call_count.load(Ordering::SeqCst), 2); // Schema call after checkout_tag should re-fetch (cache was invalidated) let schema3 = table.schema().await.unwrap(); assert_eq!( call_count.load(Ordering::SeqCst), - 2, + 3, "Cache should have been invalidated and re-fetched" ); assert_ne!( @@ -13756,41 +16565,116 @@ mod tests { } #[tokio::test] - async fn test_add_retries_on_retryable_status() { - // Verify that rescannable data retries on retryable status codes (e.g. 502) - // and eventually succeeds. - let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); - let describe_body = describe_response(&batch.schema()); - - let attempt = Arc::new(AtomicUsize::new(0)); - let attempt_clone = attempt.clone(); - - let table = - Table::new_with_handler("my_table", move |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_body.clone()) - .unwrap(), - "/v1/table/my_table/insert/" => { - let n = attempt_clone.fetch_add(1, Ordering::SeqCst); - if n < 2 { - http::Response::builder() - .status(502) - .body("bad gateway".to_string()) - .unwrap() - } else { - http::Response::builder() + async fn test_add_write_retry_policy_and_override() { + for status in [429, 500, 502, 503, 504] { + for retries in [None, Some(0)] { + let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let describe = describe_response(&batch.schema()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let table = Table::new_with_handler("my_table", move |req| { + if req.url().path().ends_with("describe/") { + return http::Response::builder() .status(200) - .body(r#"{"version": 3}"#.to_string()) - .unwrap() + .body(describe.clone()) + .unwrap(); } + let n = observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(if n == 0 { status } else { 200 }) + .body(r#"{"version":3}"#.to_string()) + .unwrap() + }); + let mut add = table.add(batch); + if let Some(retries) = retries { + add = add.retries(retries); } - path => panic!("Unexpected request path: {}", path), - }); + let result = add.execute().await; + let safe_retry = status == 429 && retries.is_none(); + assert_eq!( + result.is_ok(), + safe_retry, + "{status}, {retries:?}: {result:?}" + ); + assert_eq!( + attempts.load(Ordering::SeqCst), + if safe_retry { 2 } else { 1 } + ); + } + } + } - let result = table.add(batch).execute().await.unwrap(); - assert_eq!(result.version, 3); - assert_eq!(attempt.load(Ordering::SeqCst), 3); + #[tokio::test] + async fn test_mutations_do_not_replay_gateway_failures() { + for status in [500, 502, 503, 504] { + for op in ["update", "delete", "merge_insert"] { + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let describe = describe_response(&batch.schema()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let table = Table::new_with_handler("my_table", move |req| { + if req.url().path().ends_with("describe/") { + return http::Response::builder() + .status(200) + .body(describe.clone()) + .unwrap(); + } + assert!(req.url().path().contains(op)); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(status) + .body("gateway fault".to_string()) + .unwrap() + }); + let result = match op { + "update" => table + .update() + .column("id", "id + 1") + .execute() + .await + .map(|_| ()), + "delete" => table.delete("true").await.map(|_| ()), + _ => { + let reader = + RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let mut merge = table.merge_insert(&["id"]); + merge.when_not_matched_insert_all(); + merge.execute(Box::new(reader)).await.map(|_| ()) + } + }; + assert!(result.is_err(), "{op}, {status}"); + assert_eq!(attempts.load(Ordering::SeqCst), 1, "{op}, {status}"); + } + } + } + + #[test] + fn test_write_retry_policy_for_both_error_variants() { + let table = RemoteTable::new_mock_with_config( + "my_table".into(), + |_| http::Response::builder().body("").unwrap(), + ClientConfig { + retry_config: RetryConfig { + retries: Some(1), + statuses: Some(vec![429, 500, 502, 503, 504]), + ..Default::default() + }, + ..Default::default() + }, + ); + for status in [429, 500, 502, 503, 504] { + let err = Error::Http { + request_id: "test".into(), + status_code: Some(StatusCode::from_u16(status).unwrap()), + source: "gateway response".into(), + }; + assert_eq!(table.is_retryable_write_error(&err), status == 429); + let mut counter = + crate::remote::retry::RetryCounter::new(&table.client.retry_config, "test".into()); + let exhausted = counter.increment_request_failures(err).unwrap_err(); + assert!(matches!(exhausted, Error::Retry { .. })); + assert_eq!(table.is_retryable_write_error(&exhausted), status == 429); + } } #[tokio::test] @@ -13939,7 +16823,7 @@ mod tests { let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap(); let result = table - .add(vec![batch]) + .add(vec![batch.clone(), batch]) .write_parallelism(2) .execute() .await @@ -14343,7 +17227,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_write_abort_on_complete_failure() { + async fn test_multipart_write_does_not_abort_on_complete_failure() { let abort_count = Arc::new(AtomicUsize::new(0)); let abort_count_c = abort_count.clone(); @@ -14394,7 +17278,7 @@ mod tests { let result = table.add(vec![batch]).write_parallelism(2).execute().await; assert!(result.is_err()); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); } fn retry_config_no_backoff() -> ClientConfig { @@ -14413,9 +17297,9 @@ mod tests { #[tokio::test] async fn test_multipart_write_retry_on_partition_failure() { - // All inserts for the first upload session return 503 (retryable). - // After exhausting internal retries, the outer loop retries with a - // new session and succeeds. + // A staging failure is retried in the same upload session. + let insert_count = Arc::new(AtomicUsize::new(0)); + let insert_count_c = insert_count.clone(); let create_count = Arc::new(AtomicUsize::new(0)); let complete_count = Arc::new(AtomicUsize::new(0)); let abort_count = Arc::new(AtomicUsize::new(0)); @@ -14443,7 +17327,9 @@ mod tests { if path == "/v1/table/my_table/insert/" { // Fail all inserts for the first session - if query.contains("upload_id=upload-1") { + assert!(query.contains("upload_id=upload-1")); + assert!(query.contains("upload_part_id=")); + if insert_count_c.fetch_add(1, Ordering::SeqCst) == 0 { return http::Response::builder() .status(503) .body("Service Unavailable".to_string()) @@ -14485,14 +17371,16 @@ mod tests { .unwrap(); assert_eq!(result.version, 7); - assert_eq!(create_count.load(Ordering::SeqCst), 2); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert_eq!(create_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); assert_eq!(complete_count.load(Ordering::SeqCst), 1); } #[tokio::test] - async fn test_multipart_write_retry_on_complete_failure() { - // Complete returns 503 for the first session, succeeds for the second. + async fn test_multipart_complete_unknown_outcome_never_aborts_or_replays() { + // A gateway failure may hide a committed write. No abort or replay is safe. + let complete_count = Arc::new(AtomicUsize::new(0)); + let complete_count_c = complete_count.clone(); let create_count = Arc::new(AtomicUsize::new(0)); let abort_count = Arc::new(AtomicUsize::new(0)); @@ -14524,6 +17412,7 @@ mod tests { } if path == "/v1/table/my_table/multipart_write/complete" { + complete_count_c.fetch_add(1, Ordering::SeqCst); // Fail complete for first session if query.contains("upload_id=upload-1") { return http::Response::builder() @@ -14556,11 +17445,12 @@ mod tests { .write_parallelism(2) .execute() .await - .unwrap(); + .unwrap_err(); - assert_eq!(result.version, 9); - assert_eq!(create_count.load(Ordering::SeqCst), 2); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert!(result.to_string().contains("commit outcome unknown")); + assert_eq!(complete_count.load(Ordering::SeqCst), 1); + assert_eq!(create_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); } // ---- Read freshness header tests ------------------------------------ @@ -15238,12 +18128,13 @@ mod tests { } #[tokio::test] - async fn test_freshness_checkout_tag_resolve_sends_no_min_version() { - // Same invariant for checkout_tag: the tag-resolve request must not - // pick up a stale min_version from a prior write. + async fn test_freshness_checkout_tag_validation_sends_no_min_version() { + // Neither the tag lookup nor the version validation should pick up a + // stale min_version from a prior write. let (handler, captured) = path_capturing_handler(|path| match path { "/v1/table/my_table/update/" => r#"{"rows_updated":1,"version":7}"#.to_string(), "/v1/table/my_table/tags/version/" => r#"{"version":5}"#.to_string(), + "/v1/table/my_table/describe/" => r#"{"version":5,"schema":{"fields":[]}}"#.to_string(), _ => panic!("unexpected path: {}", path), }); let table = Table::new_with_handler("my_table", handler); @@ -15252,14 +18143,20 @@ mod tests { table.checkout_tag("v_initial").await.unwrap(); let captured = captured.lock().unwrap(); - let resolve_headers = captured - .get("/v1/table/my_table/tags/version/") - .expect("tags/version should have been called by checkout_tag"); - assert!( - !resolve_headers.contains_key("x-lancedb-min-version"), - "checkout_tag resolve must not carry stale min_version", - ); - assert!(!resolve_headers.contains_key("x-lancedb-min-timestamp")); + for path in [ + "/v1/table/my_table/tags/version/", + "/v1/table/my_table/describe/", + ] { + let headers = captured + .get(path) + .expect("checkout_tag should call endpoint"); + assert!( + !headers.contains_key("x-lancedb-min-version"), + "{path} must not carry stale min_version", + ); + assert!(!headers.contains_key("x-lancedb-min-timestamp")); + assert!(!headers.contains_key("x-lancedb-min-read-version")); + } } #[tokio::test] @@ -15648,7 +18545,7 @@ mod tests { } #[tokio::test] - async fn test_optimize_rejects_non_default_compaction_options() { + async fn test_optimize_rejects_unsupported_compaction_options() { let table = Table::new_with_handler("my_table", move |_| -> http::Response { panic!("custom compaction options must be rejected before any request is sent") }); @@ -15870,6 +18767,73 @@ mod tests { assert!(matches!(err, Error::TableNotFound { .. }), "got {err:?}"); } + #[tokio::test] + async fn test_delete_branch_conflict_is_not_retried() { + let requests = Arc::new(AtomicUsize::new(0)); + let captured = requests.clone(); + let reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files"; + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/branches/delete/"); + captured.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(409) + .body(json!({ "code": 14, "error": reason }).to_string()) + .unwrap() + }); + + let err = table.delete_branch("exp").await.unwrap_err(); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert!(err.to_string().contains(reason), "got {err:?}"); + assert!( + matches!( + err, + Error::Http { + status_code: Some(StatusCode::CONFLICT), + .. + } + ), + "expected the original conflict, got {err:?}" + ); + } + + #[tokio::test] + async fn test_delete_branch_partial_failure_is_not_retried() { + let requests = Arc::new(AtomicUsize::new(0)); + let captured = requests.clone(); + let table = Table::new_with_handler("my_table", move |_| { + // The ref was removed before the first response failed. Replaying + // the deletion would hide that failure behind a missing-branch error. + if captured.fetch_add(1, Ordering::SeqCst) == 0 { + http::Response::builder() + .status(500) + .body("failed after removing branch ref") + .unwrap() + } else { + http::Response::builder() + .status(404) + .body("no such branch") + .unwrap() + } + }); + + let err = table.delete_branch("exp").await.unwrap_err(); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert!( + err.to_string().contains("failed after removing branch ref"), + "got {err:?}" + ); + assert!( + matches!( + err, + Error::Http { + status_code: Some(StatusCode::INTERNAL_SERVER_ERROR), + .. + } + ), + "expected the original server error, got {err:?}" + ); + } + fn sample_branch_diff_json() -> &'static str { r#"{ "fromBranch":"exp", @@ -16058,6 +19022,221 @@ mod tests { } } + #[rstest] + #[case(None, Some("exp"))] + #[case(Some("exp"), None)] + #[case(Some("exp"), Some("main"))] + #[case(Some("exp"), Some("other"))] + #[tokio::test] + async fn test_checkout_tag_rejects_other_branch( + #[case] handle_branch: Option<&'static str>, + #[case] tag_branch: Option<&'static str>, + #[values(None, Some(1))] initial_version: Option, + ) { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let body = request_body_json(&request); + let response = match request.url().path() { + "/v1/table/my_table/tags/version/" => { + assert_eq!(body, json!({"tag": "cross_branch"})); + json!({"branch": tag_branch, "version": 2}).to_string() + } + "/v1/table/my_table/describe/" => { + assert_eq!(body["branch"].as_str(), handle_branch); + assert_eq!(body["version"].as_u64(), initial_version); + json!({"version": initial_version.unwrap_or(7), "schema": {"fields": []}}) + .to_string() + } + "/v1/table/my_table/count_rows/" => { + assert_eq!(body["branch"].as_str(), handle_branch); + assert_eq!(body["version"].as_u64(), initial_version); + "3".to_string() + } + path => panic!("unexpected request: {path}"), + }; + http::Response::builder() + .status(200) + .body(response) + .unwrap() + }, + None, + ) + .with_branch(handle_branch.map(String::from)); + if let Some(version) = initial_version { + table.checkout(version).await.unwrap(); + } else { + table.checkout_latest().await.unwrap(); + } + let schema = table.schema().await.unwrap(); + let before = table.snapshot_read_state().await; + + let error = table.checkout_tag("cross_branch").await.unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. }), "{error:?}"); + let message = error.to_string(); + assert!(message.contains("cross_branch"), "{message}"); + assert!(message.contains(tag_branch.unwrap_or("main")), "{message}"); + assert!( + message.contains(handle_branch.unwrap_or("main")), + "{message}" + ); + + let after = table.snapshot_read_state().await; + assert_eq!(after.version, before.version); + assert_eq!( + after.freshness_state.generation, + before.freshness_state.generation + ); + assert_eq!(after.freshness_state.pinned, before.freshness_state.pinned); + assert_eq!( + after.freshness_state.min_version, + before.freshness_state.min_version + ); + assert_eq!( + after.freshness_state.min_read_version, + before.freshness_state.min_read_version + ); + assert_eq!( + after.freshness_state.checkout_baseline, + before.freshness_state.checkout_baseline + ); + assert_eq!(table.current_branch().as_deref(), handle_branch); + assert!(Arc::ptr_eq(&schema, &table.schema().await.unwrap())); + assert_eq!(table.count_rows(None).await.unwrap(), 3); + } + + #[rstest] + #[case(None, None)] + #[case(None, Some("main"))] + #[case(None, Some(""))] + #[case(None, Some(" main "))] + #[case(Some("exp"), Some("exp"))] + #[tokio::test] + async fn test_checkout_tag_on_same_branch( + #[case] handle_branch: Option<&'static str>, + #[case] tag_branch: Option<&'static str>, + ) { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let body = request_body_json(&request); + let response = match request.url().path() { + "/v1/table/my_table/tags/version/" => { + assert_eq!(body, json!({"tag": "snapshot"})); + json!({"branch": tag_branch, "version": 2}).to_string() + } + "/v1/table/my_table/describe/" => { + assert_eq!(body["branch"].as_str(), handle_branch); + assert_eq!(body["version"], 2); + for header in [ + MIN_VERSION_HEADER, + MIN_READ_VERSION_HEADER, + MIN_TIMESTAMP_HEADER, + ] { + assert!(!request.headers().contains_key(header)); + } + r#"{"version":2,"schema":{"fields":[]}}"#.to_string() + } + "/v1/table/my_table/count_rows/" => { + assert_eq!(body["branch"].as_str(), handle_branch); + if body["version"].is_null() { + "4".to_string() + } else { + assert_eq!(body["version"], 2); + "3".to_string() + } + } + path => panic!("unexpected request: {path}"), + }; + http::Response::builder() + .status(200) + .body(response) + .unwrap() + }, + None, + ) + .with_branch(handle_branch.map(String::from)); + + table.checkout_latest().await.unwrap(); + table.checkout_tag("snapshot").await.unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 3); + assert_eq!(table.current_branch().as_deref(), handle_branch); + table.checkout_latest().await.unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 4); + assert_eq!(table.current_branch().as_deref(), handle_branch); + } + + #[rstest] + #[case(None)] + #[case(Some("exp"))] + #[tokio::test] + async fn test_checkout_tag_missing_version_leaves_handle_unchanged( + #[case] branch: Option<&'static str>, + #[values(None, Some(1))] initial_version: Option, + ) { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let body = request_body_json(&request); + if request.url().path() == "/v1/table/my_table/tags/version/" { + return http::Response::builder() + .status(200) + .body(json!({"branch": branch, "version": 99}).to_string()) + .unwrap(); + } + assert_eq!(body["branch"].as_str(), branch); + if body["version"] == 99 { + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + return http::Response::builder() + .status(404) + .body("not found".to_string()) + .unwrap(); + } + assert_eq!(body["version"].as_u64(), initial_version); + let response = match request.url().path() { + "/v1/table/my_table/describe/" => { + json!({"version": initial_version.unwrap_or(7), "schema": {"fields": []}}) + .to_string() + } + "/v1/table/my_table/count_rows/" => "3".to_string(), + path => panic!("unexpected request: {path}"), + }; + http::Response::builder() + .status(200) + .body(response) + .unwrap() + }, + None, + ) + .with_branch(branch.map(String::from)); + if let Some(version) = initial_version { + table.checkout(version).await.unwrap(); + } else { + table.checkout_latest().await.unwrap(); + } + let schema = table.schema().await.unwrap(); + let before = table.snapshot_read_state().await; + + let error = table.checkout_tag("missing_version").await.unwrap_err(); + assert!(matches!(error, Error::TableNotFound { .. }), "{error:?}"); + assert!(error.to_string().contains("version: 99")); + let after = table.snapshot_read_state().await; + assert_eq!(after.version, before.version); + assert_eq!( + after.freshness_state.generation, + before.freshness_state.generation + ); + assert_eq!( + after.freshness_state.checkout_baseline, + before.freshness_state.checkout_baseline + ); + // HTTP errors invalidate the schema cache, but the refreshed schema + // must still come from the original selector. + assert_eq!(schema, table.schema().await.unwrap()); + assert_eq!(table.current_branch().as_deref(), branch); + assert_eq!(table.count_rows(None).await.unwrap(), 3); + } + #[tokio::test] async fn test_checkout_branch_validates_via_list() { let table = Table::new_with_handler("my_table", |request| { @@ -16073,6 +19252,33 @@ mod tests { assert_eq!(branch.current_branch(), Some("exp".to_string())); } + #[tokio::test] + async fn resume_refresh_preserves_the_branch_and_server_rejection() { + let table = Table::new_with_handler("my_table", |request| { + match request.url().path() { + "/v1/table/my_table/branches/list/" => http::Response::builder() + .status(200) + .body(r#"{"branches":{"exp":{"parentBranch":null,"parentVersion":1,"createAt":1,"manifestSize":1}}}"#) + .unwrap(), + "/v1/table/my_table/resume_refresh" => { + let payload: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(payload, json!({"job_id":"failed","branch":"exp"})); + http::Response::builder() + .status(400) + .body("Check the external result before issuing another refresh") + .unwrap() + } + path => panic!("unexpected path {path}"), + } + }); + let branch = table.checkout_branch("exp", None).await.unwrap(); + let error = branch.resume_refresh("failed").await.unwrap_err(); + assert!( + error.to_string().contains("Check the external result"), + "{error}" + ); + } + #[tokio::test] async fn test_checkout_branch_missing() { let table = Table::new_with_handler("my_table", |_| { @@ -16578,6 +19784,42 @@ mod tests { branch.restore().await.unwrap(); } + #[tokio::test] + async fn test_index_exist_ok_query_and_replacement_policy() { + for exist_ok in [false, true] { + for background in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/create_index/" => { + assert_eq!(request.url().query(), exist_ok.then_some("exist_ok=true")); + let body = request_body_json(&request); + assert_eq!( + body.get("replace"), + exist_ok.then_some(&serde_json::Value::Bool(false)) + ); + assert!(body.get("exist_ok").is_none()); + http::Response::builder() + .status(200) + .body("{}".into()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let builder = table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(exist_ok); + if background { + builder.execute_async().await.unwrap().wait().await.unwrap(); + } else { + builder.execute().await.unwrap(); + } + } + } + } + #[tokio::test] async fn test_branch_create_index_carries_branch_in_body() { use lance::dataset::refs::Ref; diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 65ab13935..6c70bfbd5 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -3,11 +3,16 @@ //! Cloud blob column listing, whole-byte fetch, and seekable HTTP byte-range handles. +mod aggregate; + +use aggregate::BlobAccumulator; +use arrow_buffer::{Buffer, OffsetBuffer}; + use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Duration; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arrow_array::builder::LargeBinaryBuilder; use arrow_array::{Array, LargeBinaryArray, StructArray, UInt8Array, UInt64Array}; @@ -18,7 +23,8 @@ use futures::{StreamExt, TryStreamExt}; use lance::dataset::ROW_ID; use lance_core::datatypes::BlobKind; use reqwest::{Response, StatusCode, header}; -use tokio::sync::{Mutex, OwnedSemaphorePermit}; +use serde::Deserialize; +use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock}; use crate::Error; use crate::blob::{BlobDescriptor, BlobDescriptorSource, BlobFile, BlobRangeRequest}; @@ -28,13 +34,22 @@ use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; use crate::table::{AnyQuery, BaseTable}; use super::{ - FreshnessHeaders, FreshnessState, ReadSnapshot, RemoteTable, VERSION_HEADER, - freshness_headers_snapshot, + FreshnessHeaders, FreshnessState, QUERY_SNAPSHOT_HEADER, ReadSnapshot, RemoteTable, + VERSION_HEADER, check_query_snapshot_response, freshness_headers_snapshot, + valid_query_snapshot_identity, }; // The Cloud route rejects larger row-id lists. Its separate 64 MiB byte limit // is handled by splitting a rejected request below. const MAX_FETCH_BLOBS_ROW_IDS: usize = 1024; +const MAX_FETCH_BLOB_RANGE_BYTES: u64 = 64 * 1024 * 1024; +// Refresh shortly before expiry so a request does not start with a URL that +// expires while it is being signed and sent. +const BLOB_PRESIGN_REFRESH_SKEW: Duration = Duration::from_secs(30); + +fn is_blob_locations_unavailable(error: &Error) -> bool { + error.status_code() == Some(StatusCode::SERVICE_UNAVAILABLE) +} fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { matches!(error, Error::Http { @@ -56,7 +71,7 @@ enum RangeRequestMode { trait BlobRangeRequester: Send + Sync + std::fmt::Debug { async fn request_range( &self, - range_header: &str, + range: Range, mode: RangeRequestMode, version: Option, ) -> Result; @@ -67,6 +82,10 @@ trait BlobRangeRequester: Send + Sync + std::fmt::Debug { struct BlobRangeResponse { request_id: String, response: Response, + /// Whether the requester already validated the response's status and + /// `Content-Range` against the logical blob. Direct object-store responses + /// use physical coordinates, so the outer handle cannot re-check them. + validated: bool, _permit: Option, } @@ -76,6 +95,7 @@ impl From<(String, Response)> for BlobRangeResponse { Self { request_id, response, + validated: false, _permit: None, } } @@ -88,6 +108,7 @@ struct TableBlobRangeRequester { version: Option, branch: Option, source_uri: Option, + expected_query_snapshot: Option, source_commit_micros: Option, row_is_address: bool, freshness: Arc>, @@ -100,10 +121,11 @@ struct TableBlobRangeRequester { impl BlobRangeRequester for TableBlobRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, mode: RangeRequestMode, version: Option, ) -> Result { + let range_header = format!("bytes={}-{}", range.start, range.end.saturating_sub(1)); let permit = self .client .blob_request_semaphore @@ -120,6 +142,9 @@ impl BlobRangeRequester for TableBlobRangeRequester { .apply(self.client.get(&self.path)) .header(header::RANGE, range_header) }; + if let Some(identity) = &self.expected_query_snapshot { + request = request.header(QUERY_SNAPSHOT_HEADER, identity); + } if let Some(version) = version.or(self.version) { request = request.query(&[("version", version)]); } @@ -135,6 +160,10 @@ impl BlobRangeRequester for TableBlobRangeRequester { request = request.query(&[("source_commit_micros", timestamp)]); } let (request_id, response) = self.client.send_with_retry(request, None, true).await?; + if response.status().is_success() || response.status() == StatusCode::RANGE_NOT_SATISFIABLE + { + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + } // Preserve 416 size-probe responses so the caller can detect empty blobs. if response.status() == StatusCode::RANGE_NOT_SATISFIABLE && matches!(mode, RangeRequestMode::SizeProbe) @@ -142,6 +171,7 @@ impl BlobRangeRequester for TableBlobRangeRequester { return Ok(BlobRangeResponse { request_id, response, + validated: false, _permit: Some(permit), }); } @@ -154,14 +184,31 @@ impl BlobRangeRequester for TableBlobRangeRequester { Ok(BlobRangeResponse { request_id, response, + validated: false, _permit: Some(permit), }) } } -#[derive(Debug, Default)] +#[derive(Debug)] struct RemoteBlobState { cursor: u64, + buffer_size: usize, +} + +impl Default for RemoteBlobState { + fn default() -> Self { + Self { + cursor: 0, + buffer_size: BlobFile::DEFAULT_READ_BUFFER_SIZE, + } + } +} + +#[derive(Debug, Default)] +struct RemoteBlobBuffer { + start: u64, + bytes: Bytes, } /// Seekable Cloud blob handle over HTTP Range. @@ -171,6 +218,9 @@ struct RemoteBlobState { pub struct RemoteBlobFile { requester: Arc, state: Mutex, + // Never held across I/O: close can release cached bytes even while a read + // holds the cursor lock. A reader may retain its own prefix until it ends. + buffer: std::sync::Mutex, closed: AtomicBool, size: u64, version: Option, @@ -181,6 +231,7 @@ impl RemoteBlobFile { Self { requester, state: Mutex::new(RemoteBlobState::default()), + buffer: std::sync::Mutex::new(RemoteBlobBuffer::default()), closed: AtomicBool::new(false), size, version, @@ -190,6 +241,18 @@ impl RemoteBlobFile { /// Close the handle without waiting for an in-flight read. pub(crate) async fn close(&self) -> lance_core::Result<()> { self.closed.store(true, Ordering::Release); + self.buffer.lock().unwrap().bytes = Bytes::new(); + Ok(()) + } + + pub(crate) async fn set_buffer_size(&self, size: usize) -> lance_core::Result<()> { + self.ensure_open()?; + let mut state = self.state.lock().await; + self.ensure_open()?; + if state.buffer_size != size { + state.buffer_size = size; + self.buffer.lock().unwrap().bytes = Bytes::new(); + } Ok(()) } @@ -224,31 +287,23 @@ impl RemoteBlobFile { if range.is_empty() { return Ok(Bytes::new()); } - let range_header = format!("bytes={}-{}", range.start, range.end - 1); let BlobRangeResponse { request_id, response, - _permit, + validated, + _permit: permit, } = self .requester - .request_range(&range_header, RangeRequestMode::DataRead, self.version) + .request_range(range.clone(), RangeRequestMode::DataRead, self.version) .await .map_err(remote_blob_error)?; self.ensure_open()?; - validate_partial_response(&response, range.clone(), self.size)?; - let bytes = response - .bytes() - .await - .err_to_http(request_id) - .map_err(remote_blob_error)?; - self.ensure_open()?; - if bytes.len() as u64 != range.end - range.start { - return Err(remote_blob_error(format!( - "byte range returned {} bytes, expected {}", - bytes.len(), - range.end - range.start - ))); + if !validated { + validate_partial_response(&response, range.clone(), self.size)?; } + let bytes = read_blob_body(response, range.end - range.start, request_id).await?; + drop(permit); + self.ensure_open()?; Ok(bytes) } @@ -275,7 +330,16 @@ impl RemoteBlobFile { let remaining = usize::try_from(remaining).map_err(|_| { lance_core::Error::invalid_input("remaining blob length exceeds addressable memory") })?; - self.read_up_to_locked(&mut state, remaining).await + // Joining a small cached prefix to a large tail would copy the entire + // blob while both allocations are live. Match the native reader's + // bounded reuse rule for whole-blob reads. + let held_len = cached_prefix(&self.buffer.lock().unwrap(), state.cursor, remaining).len(); + if remaining > held_len.saturating_mul(2) { + self.buffer.lock().unwrap().bytes = Bytes::new(); + } + let bytes = self.read_up_to_locked(&mut state, remaining).await?; + self.buffer.lock().unwrap().bytes = Bytes::new(); + Ok(bytes) } pub(crate) async fn read_up_to(&self, len: usize) -> lance_core::Result { @@ -296,14 +360,51 @@ impl RemoteBlobFile { return Ok(Bytes::new()); } - // A partial read must release its HTTP response before returning. Keeping - // it open across calls would hold a connection slot indefinitely and - // prevent other handles from making progress. - let end = state.cursor + target_len as u64; - let bytes = self.read_range(state.cursor..end).await?; + let prefix = cached_prefix(&self.buffer.lock().unwrap(), state.cursor, target_len); + if prefix.len() == target_len { + state.cursor += target_len as u64; + return Ok(prefix); + } + let fetch_start = state.cursor + prefix.len() as u64; + let still_need = target_len - prefix.len(); + let fetch_len = if state.buffer_size == 0 { + still_need as u64 + } else { + (state.buffer_size.max(still_need) as u64).min(self.size - fetch_start) + }; + // Fully consume the response before retaining only its Bytes. read_range + // releases both the connection and the concurrency permit before return. + let data = self + .read_range(fetch_start..fetch_start + fetch_len) + .await?; self.ensure_open()?; - state.cursor = end; - Ok(bytes) + let tail = data.slice(..still_need); + let result = if prefix.is_empty() { + tail + } else { + let mut joined = Vec::new(); + joined.try_reserve_exact(target_len).map_err(|error| { + remote_blob_error(format!( + "cannot allocate blob read of {target_len} bytes: {error}" + )) + })?; + joined.extend_from_slice(&prefix); + joined.extend_from_slice(&tail); + Bytes::from(joined) + }; + { + let mut buffer = self.buffer.lock().unwrap(); + // Serialize publishing a new window with close clearing the cache. + self.ensure_open()?; + if state.buffer_size != 0 { + buffer.start = fetch_start; + buffer.bytes = data; + } else { + buffer.bytes = Bytes::new(); + } + } + state.cursor += target_len as u64; + Ok(result) } pub(crate) async fn seek(&self, new_cursor: u64) -> lance_core::Result<()> { @@ -326,6 +427,83 @@ impl RemoteBlobFile { } } +/// Collect a range without retaining a second payload's worth of network chunks. +async fn read_blob_body( + response: Response, + expected: u64, + request_id: String, +) -> lance_core::Result { + let expected = usize::try_from(expected).map_err(|_| { + lance_core::Error::invalid_input("blob range length exceeds addressable memory") + })?; + let length_error = |received| { + remote_blob_error(format!( + "byte range returned {received} bytes, expected {expected}" + )) + }; + let mut chunks = response.bytes_stream(); + let first = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + .ok_or_else(|| length_error(0))?; + if first.len() > expected { + return Err(length_error(first.len())); + } + if first.len() == expected { + while let Some(chunk) = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + { + if !chunk.is_empty() { + return Err(length_error(expected.saturating_add(chunk.len()))); + } + } + return Ok(first); + } + let mut bytes = Vec::new(); + bytes.try_reserve_exact(expected).map_err(|error| { + remote_blob_error(format!( + "cannot allocate blob range of {expected} bytes: {error}" + )) + })?; + bytes.extend_from_slice(&first); + drop(first); + while let Some(chunk) = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + { + let received = bytes.len().saturating_add(chunk.len()); + if received > expected { + return Err(length_error(received)); + } + bytes.extend_from_slice(&chunk); + } + if bytes.len() != expected { + return Err(length_error(bytes.len())); + } + Ok(Bytes::from(bytes)) +} + +fn cached_prefix(buffer: &RemoteBlobBuffer, cursor: u64, length: usize) -> Bytes { + let Some(offset) = cursor.checked_sub(buffer.start) else { + return Bytes::new(); + }; + let Ok(offset) = usize::try_from(offset) else { + return Bytes::new(); + }; + if offset >= buffer.bytes.len() { + return Bytes::new(); + } + let end = offset.saturating_add(length).min(buffer.bytes.len()); + buffer.bytes.slice(offset..end) +} + fn remote_blob_error(error: impl std::fmt::Display) -> lance_core::Error { lance_core::Error::io(format!("remote blob read failed: {error}")) } @@ -349,6 +527,37 @@ fn validate_partial_response( response: &Response, expected: Range, size: u64, +) -> lance_core::Result<()> { + validate_content_range(response, expected.start, expected.end - 1, size, true) +} + +/// Validate a direct object-store response whose `Content-Range` uses physical +/// offsets in a shared sidecar. The object may be larger than the logical blob; +/// only its total must cover the full logical value. +fn validate_physical_content_range( + response: &Response, + expected: Range, + base_offset: u64, + logical_size: u64, +) -> lance_core::Result<()> { + let start = base_offset + .checked_add(expected.start) + .ok_or_else(|| remote_blob_error("blob physical range start overflows u64"))?; + let end = base_offset + .checked_add(expected.end) + .ok_or_else(|| remote_blob_error("blob physical range end overflows u64"))?; + let minimum_total = base_offset + .checked_add(logical_size) + .ok_or_else(|| remote_blob_error("blob physical range total overflows u64"))?; + validate_content_range(response, start, end - 1, minimum_total, false) +} + +fn validate_content_range( + response: &Response, + expected_start: u64, + expected_end: u64, + expected_total: u64, + exact_total: bool, ) -> lance_core::Result<()> { if response.status() != StatusCode::PARTIAL_CONTENT { return Err(remote_blob_error(format!( @@ -362,12 +571,14 @@ fn validate_partial_response( .and_then(|value| value.to_str().ok()) .and_then(parse_content_range) .ok_or_else(|| remote_blob_error("response is missing a valid Content-Range header"))?; - if content_range != (expected.start, expected.end - 1, size) { + if content_range.0 != expected_start + || content_range.1 != expected_end + || (exact_total && content_range.2 != expected_total) + || (!exact_total && content_range.2 < expected_total) + { return Err(remote_blob_error(format!( - "expected Content-Range 'bytes {}-{}/{}', got 'bytes {}-{}/{}'", - expected.start, - expected.end - 1, - size, + "expected Content-Range 'bytes {expected_start}-{expected_end}/{expected_total}{}', got 'bytes {}-{}/{}'", + if exact_total { "" } else { " or larger" }, content_range.0, content_range.1, content_range.2 @@ -376,12 +587,592 @@ fn validate_partial_response( Ok(()) } +#[derive(Debug, Clone, Deserialize)] +struct BlobLocationSource { + url: String, + #[serde(default)] + expires_at_unix_secs: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +enum BlobLocationItem { + Presigned { + source_index: usize, + offset: u64, + size: u64, + }, + Inline { + size: u64, + data_base64: String, + }, + Proxy { + size: u64, + }, +} + +#[derive(Debug)] +struct ResolvedBlobLocations { + sources: Vec, + items: Vec>, + version: u64, + identity: Option, +} + +#[derive(Deserialize)] +struct BlobLocationsBody { + sources: Vec, + items: Vec>, +} + +/// One pinned table/column position used to resolve or refresh Blob locations. +#[derive(Clone)] +struct BlobLocationsContext { + client: RestfulLanceDbClient, + identifier: String, + table_name: String, + column: String, + version: Option, + branch: Option, + source_uri: Option, + source_commit_micros: Option, + row_is_address: bool, + expected_query_snapshot: Option, + freshness: Option, +} + +impl BlobLocationsContext { + async fn resolve( + &self, + row_ids: &[u64], + include_inline_data: bool, + ) -> Result { + let started = Instant::now(); + let mut body = serde_json::json!({ + "column": &self.column, + "version": self.version, + "row_ids": row_ids, + "row_is_address": self.row_is_address, + "include_inline_data": include_inline_data, + }); + if let Some(branch) = &self.branch { + body["branch"] = serde_json::Value::String(branch.clone()); + } + if let Some(source_uri) = &self.source_uri { + body["source_uri"] = serde_json::Value::String(source_uri.clone()); + } + if let Some(timestamp) = self.source_commit_micros { + body["source_commit_micros"] = serde_json::Value::Number(timestamp.into()); + } + + let mut request = self + .client + .post(&format!("/v1/table/{}/blob_locations/", self.identifier)) + .json(&body); + if let Some(identity) = &self.expected_query_snapshot { + request = request.header(QUERY_SNAPSHOT_HEADER, identity); + } + if let Some(freshness) = self.freshness { + request = freshness.apply(request); + } + // A resolver 503 means a PE lost the plan after describe. Do not spend + // transport retries on it: the caller falls back to proxy immediately. + let (request_id, response) = self.client.send(request).await?; + let response = + RemoteTable::::handle_table_not_found(&self.table_name, response, &request_id) + .await?; + let response = self + .client + .check_response(&request_id, response) + .await + .map_err(|error| { + if let Error::Http { + source, + request_id, + status_code: Some(StatusCode::BAD_REQUEST), + } = error + { + Error::InvalidInput { + message: format!("blob_locations (request {request_id}): {source}"), + } + } else { + error + } + })?; + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + + let version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version != 0) + .ok_or_else(|| Error::Http { + source: "blob_locations response has no valid x-lancedb-version".into(), + request_id: request_id.clone(), + status_code: None, + })?; + if let Some(expected) = self.version + && expected != version + { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {version}, expected pinned version {expected}" + ) + .into(), + request_id, + status_code: None, + }); + } + let identity = match &self.expected_query_snapshot { + Some(expected) => Some(expected.clone()), + None => Some( + response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .map(str::to_owned) + .ok_or_else(|| Error::NotSupported { + message: + "Blob locations require a snapshot identity; upgrade every serving node" + .into(), + })?, + ), + }; + + let body = response.text().await.err_to_http(request_id.clone())?; + let parsed: BlobLocationsBody = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse blob_locations response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if parsed.items.len() != row_ids.len() { + return Err(Error::Http { + source: format!( + "blob_locations returned {} items for {} row ids", + parsed.items.len(), + row_ids.len() + ) + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + for item in parsed.items.iter().flatten() { + match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + if *source_index >= parsed.sources.len() { + return Err(Error::Http { + source: format!( + "blob_locations item references source {source_index} of {}", + parsed.sources.len() + ) + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + offset.checked_add(*size).ok_or_else(|| Error::Http { + source: "blob_locations physical range overflows u64".into(), + request_id: request_id.clone(), + status_code: None, + })?; + } + BlobLocationItem::Inline { size, data_base64 } => { + if data_base64.len() as u64 > size.saturating_mul(4) { + return Err(Error::Http { + source: "blob_locations inline payload is larger than its decoded size" + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + } + BlobLocationItem::Proxy { .. } => {} + } + } + log::debug!( + "blob_locations resolved rows={} version={} identity={} elapsed_ms={:.3}", + row_ids.len(), + version, + identity.as_deref().unwrap_or(""), + started.elapsed().as_secs_f64() * 1000.0 + ); + Ok(ResolvedBlobLocations { + sources: parsed.sources, + items: parsed.items, + version, + identity, + }) + } +} + +fn decode_inline_data(data_base64: &str, expected_size: u64) -> Result { + use base64::Engine as _; + let bytes = base64::engine::general_purpose::STANDARD + .decode(data_base64) + .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(data_base64)) + .map_err(|error| Error::InvalidInput { + message: format!("blob_locations returned invalid inline base64: {error}"), + })?; + if bytes.len() as u64 != expected_size { + return Err(Error::InvalidInput { + message: format!( + "blob_locations inline item decoded to {} bytes, expected {expected_size}", + bytes.len() + ), + }); + } + Ok(Bytes::from(bytes)) +} + +enum PresignedBlobState { + Presigned { + url: String, + expires_at_unix_secs: Option, + base_offset: u64, + }, + Inline { + bytes: Bytes, + }, + Proxy, +} + +enum PresignedReadError { + Expired, + Failed(Error), +} + +struct PresignedBlobRangeRequester { + context: BlobLocationsContext, + row_id: u64, + logical_size: u64, + threshold_bytes: u64, + proxy: Arc, + state: RwLock, + refresh_lock: Mutex<()>, +} + +impl std::fmt::Debug for PresignedBlobRangeRequester { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PresignedBlobRangeRequester") + .field("row_id", &self.row_id) + .field("logical_size", &self.logical_size) + .finish_non_exhaustive() + } +} + +impl PresignedBlobRangeRequester { + fn new( + context: BlobLocationsContext, + row_id: u64, + logical_size: u64, + threshold_bytes: u64, + proxy: Arc, + source: &BlobLocationSource, + base_offset: u64, + ) -> Self { + Self { + context, + row_id, + logical_size, + threshold_bytes, + proxy, + state: RwLock::new(PresignedBlobState::Presigned { + url: source.url.clone(), + expires_at_unix_secs: source.expires_at_unix_secs, + base_offset, + }), + refresh_lock: Mutex::new(()), + } + } + + async fn proxy_validated( + &self, + range: Range, + mode: RangeRequestMode, + version: Option, + ) -> Result { + let mut response = self + .proxy + .request_range(range.clone(), mode, version) + .await?; + validate_partial_response(&response.response, range, self.logical_size)?; + response.validated = true; + Ok(response) + } + + async fn refresh(&self) -> Result<()> { + let _guard = self.refresh_lock.lock().await; + let resolved = match self.context.resolve(&[self.row_id], false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => { + // The resolver lost its PE plan. Keep this handle usable by + // switching it to the proxy route instead of failing the read. + *self.state.write().await = PresignedBlobState::Proxy; + return Ok(()); + } + Err(error) => return Err(error), + }; + let item = + resolved + .items + .into_iter() + .next() + .flatten() + .ok_or_else(|| Error::InvalidInput { + message: "presigned blob is no longer stored as a non-null value".into(), + })?; + let next = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + if size != self.logical_size { + return Err(Error::InvalidInput { + message: format!( + "presigned blob size changed from {} to {size} at the pinned version", + self.logical_size + ), + }); + } + let source = + resolved + .sources + .get(source_index) + .ok_or_else(|| Error::InvalidInput { + message: format!( + "presigned blob refresh references source {source_index} of {}", + resolved.sources.len() + ), + })?; + PresignedBlobState::Presigned { + url: source.url.clone(), + expires_at_unix_secs: source.expires_at_unix_secs, + base_offset: offset, + } + } + BlobLocationItem::Inline { size, data_base64 } => PresignedBlobState::Inline { + bytes: decode_inline_data(&data_base64, size)?, + }, + BlobLocationItem::Proxy { size } => { + if size != self.logical_size { + return Err(Error::InvalidInput { + message: format!( + "proxied blob size changed from {} to {size} at the pinned version", + self.logical_size + ), + }); + } + PresignedBlobState::Proxy + } + }; + *self.state.write().await = next; + Ok(()) + } + + async fn direct_read( + &self, + url: &str, + base_offset: u64, + range: Range, + ) -> std::result::Result { + let permit = self + .context + .client + .blob_request_semaphore + .clone() + .acquire_owned() + .await + .expect("blob request semaphore is never closed"); + let start = base_offset.checked_add(range.start).ok_or_else(|| { + PresignedReadError::Failed(Error::InvalidInput { + message: "presigned physical range start overflows u64".into(), + }) + })?; + let end = base_offset.checked_add(range.end).ok_or_else(|| { + PresignedReadError::Failed(Error::InvalidInput { + message: "presigned physical range end overflows u64".into(), + }) + })?; + let request = self + .context + .client + .object_store_get(url) + .header(header::RANGE, format!("bytes={start}-{}", end - 1)); + let (request_id, response) = self + .context + .client + .send_object_store(request) + .await + .map_err(PresignedReadError::Failed)?; + if matches!( + response.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) { + return Err(PresignedReadError::Expired); + } + if response.status() != StatusCode::PARTIAL_CONTENT { + return Err(PresignedReadError::Failed(Error::Http { + source: format!( + "expected HTTP 206 Partial Content, got {}", + response.status() + ) + .into(), + request_id, + status_code: Some(response.status()), + })); + } + validate_physical_content_range(&response, range.clone(), base_offset, self.logical_size) + .map_err(|error| PresignedReadError::Failed(error.into()))?; + let content_range = response + .headers() + .get(header::CONTENT_RANGE) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + log::debug!( + "blob_direct row={} content_range={} logical_range={}..{}", + self.row_id, + content_range, + range.start, + range.end + ); + Ok(BlobRangeResponse { + request_id, + response, + validated: true, + _permit: Some(permit), + }) + } +} + +#[async_trait::async_trait] +impl BlobRangeRequester for PresignedBlobRangeRequester { + async fn request_range( + &self, + range: Range, + mode: RangeRequestMode, + version: Option, + ) -> Result { + if !matches!(mode, RangeRequestMode::DataRead) { + return Err(Error::InvalidInput { + message: "presigned blob handles only serve data reads".into(), + }); + } + let range_len = range.end.saturating_sub(range.start); + if range_len < self.threshold_bytes { + return self.proxy_validated(range, mode, version).await; + } + let mut refreshed = false; + loop { + let state = self.state.read().await; + match &*state { + PresignedBlobState::Proxy => { + drop(state); + return self.proxy_validated(range, mode, version).await; + } + PresignedBlobState::Inline { bytes } => { + let bytes = bytes.clone(); + drop(state); + return inline_range_response(bytes, range, self.logical_size); + } + PresignedBlobState::Presigned { + url, + expires_at_unix_secs, + base_offset, + } => { + let url = url.clone(); + let expires = *expires_at_unix_secs; + let base_offset = *base_offset; + drop(state); + let now = unix_now_secs(); + if expires.is_some_and(|expires| { + expires <= now.saturating_add(BLOB_PRESIGN_REFRESH_SKEW.as_secs()) + }) && !refreshed + { + log::debug!( + "blob_direct refresh row={} reason=proactive expires_at={expires:?}", + self.row_id + ); + self.refresh().await?; + refreshed = true; + continue; + } + match self.direct_read(&url, base_offset, range.clone()).await { + Ok(response) => return Ok(response), + Err(PresignedReadError::Expired) if !refreshed => { + log::debug!("blob_direct refresh row={} reason=reactive", self.row_id); + self.refresh().await?; + refreshed = true; + } + Err(PresignedReadError::Expired) => { + return Err(Error::InvalidInput { + message: "presigned blob URL expired after refresh".into(), + }); + } + Err(PresignedReadError::Failed(error)) => return Err(error), + } + } + } + } + } +} + +fn unix_now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_secs()) +} + +fn inline_range_response(bytes: Bytes, range: Range, size: u64) -> Result { + let start = usize::try_from(range.start).map_err(|_| Error::InvalidInput { + message: "inline blob range start exceeds addressable memory".into(), + })?; + let end = usize::try_from(range.end).map_err(|_| Error::InvalidInput { + message: "inline blob range end exceeds addressable memory".into(), + })?; + let slice = bytes + .get(start..end) + .ok_or_else(|| Error::InvalidInput { + message: "inline blob range exceeds the resolved value".into(), + })? + .to_vec(); + let response = http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header( + header::CONTENT_RANGE, + format!("bytes {}-{}/{size}", range.start, range.end - 1), + ) + .body(slice) + .map_err(|error| Error::Other { + message: format!("failed to build inline blob response: {error}"), + source: None, + })?; + Ok(BlobRangeResponse { + request_id: "blob-inline".into(), + response: Response::from(response), + validated: true, + _permit: None, + }) +} + impl RemoteTable { async fn reject_list_blob_path_if_known(&self, column: &str) -> Result<()> { // A dotted path needs client-side validation because the server may // report an internal type mismatch when the path crosses a list. Use // an already cached schema for top-level list fields as well. - if column.contains('.') || self.schema_cache.try_get().is_some() { + // Guarded readers must validate the producing identity on the server + // before consulting any schema resolved from a later logical binding. + if self.expected_query_snapshot.is_none() + && (column.contains('.') || self.schema_cache.try_get().is_some()) + { let schema = self.schema().await?; crate::blob::reject_list_blob_column(schema.as_ref(), column)?; } @@ -389,6 +1180,9 @@ impl RemoteTable { } async fn explain_list_blob_bad_request(&self, column: &str, error: Error) -> Error { + if self.expected_query_snapshot.is_some() { + return error; + } let is_bad_request = match &error { Error::Http { status_code: Some(code), @@ -428,16 +1222,36 @@ impl RemoteTable { }); } let mut read_snapshot = self.snapshot_read_state().await; + let mut identity = self.expected_query_snapshot.clone(); + let mut allow_direct_fallback = true; + if self.blob_locations_supported.load(Ordering::Relaxed) { + match self + .fetch_blobs_via_locations(column, row_ids, &mut read_snapshot, &mut identity) + .await + { + Ok(Some(blobs)) => return Ok(blobs), + Ok(None) => { + log::warn!( + "blob_locations is unavailable (503); falling back to the proxy whole-blob path for this batch" + ); + allow_direct_fallback = false; + } + Err(error) => return Err(error), + } + } // A selection spanning requests must use one exact dataset version. // Resolve latest before the first chunk; a checked-out version is exact already. if row_ids.len() > MAX_FETCH_BLOBS_ROW_IDS && read_snapshot.version.is_none() { read_snapshot.version = Some(self.describe_read_snapshot(read_snapshot).await?.version); } let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); - let mut chunks = Vec::new(); + let mut blobs = BlobAccumulator::new(row_ids.len())?; while let Some(ids) = pending.pop() { - match self.fetch_blobs_chunk(column, ids, read_snapshot).await { - Ok(blobs) => chunks.push(blobs), + match self + .fetch_blobs_chunk(column, ids, read_snapshot, identity.as_deref(), &mut blobs) + .await + { + Ok(()) => {} Err(error) if is_fetch_blobs_byte_limit_error(&error) => { // A single-request call may turn into several requests after a // byte-cap error. No bytes from the failed request were used. @@ -449,13 +1263,27 @@ impl RemoteTable { // The whole-byte route cannot serve this blob. The Range route // has no aggregate response limit and preserves null alignment. let mut files = self - .fetch_blob_files_with_snapshot(column, ids, read_snapshot) + .fetch_blob_files_with_snapshot( + column, + ids, + read_snapshot, + allow_direct_fallback, + identity.clone(), + ) .await?; let blob = match files.pop().unwrap() { Some(file) => Some(file.read().await?), None => None, }; - chunks.push(LargeBinaryArray::from(vec![blob.as_deref()])); + let blob = match blob { + Some(bytes) => LargeBinaryArray::new( + OffsetBuffer::new(vec![0, bytes.len() as i64].into()), + Buffer::from(bytes), + None, + ), + None => LargeBinaryArray::new_null(1), + }; + blobs.append(&blob)?; } else { let mid = ids.len() / 2; pending.push(&ids[mid..]); @@ -466,15 +1294,273 @@ impl RemoteTable { } } - if chunks.len() == 1 { - return Ok(chunks.pop().unwrap()); + Ok(blobs.finish()?) + } + + /// Resolve locations once per batch, read large presigned values directly, + /// consume inline bytes in place, and proxy only the remaining rows. + /// + /// `Ok(None)` means the resolver returned 503 after possibly pinning a + /// version and identity; the caller must reuse that pinned state on the + /// proxy path and must not resolve again. + async fn fetch_blobs_via_locations( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result> { + let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); + let mut blobs = BlobAccumulator::new(row_ids.len())?; + while let Some(ids) = pending.pop() { + let context = self.blob_locations_context( + column, + read_snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(read_snapshot.freshness), + ); + let resolved = match context.resolve(ids, true).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if read_snapshot.version.is_none() { + read_snapshot.version = Some(resolved.version); + } + if read_snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, read_snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + let array = self + .fetch_blobs_locations_batch( + column, + ids, + &resolved, + *read_snapshot, + identity.as_deref(), + ) + .await?; + blobs.append(&array)?; } - let chunk_refs: Vec<&dyn Array> = chunks.iter().map(|chunk| chunk as &dyn Array).collect(); - Ok(arrow::compute::concat(&chunk_refs)? - .as_any() - .downcast_ref::() - .expect("concatenating LargeBinary arrays returns LargeBinary") - .clone()) + Ok(Some(blobs.finish()?)) + } + + async fn fetch_blobs_locations_batch( + &self, + column: &str, + row_ids: &[u64], + resolved: &ResolvedBlobLocations, + read_snapshot: ReadSnapshot, + identity: Option<&str>, + ) -> Result { + let mut values: Vec> = vec![None; row_ids.len()]; + let mut nulls = vec![false; row_ids.len()]; + let mut proxy_indices = Vec::new(); + let mut direct = Vec::new(); + for (index, item) in resolved.items.iter().enumerate() { + match item { + None => nulls[index] = true, + Some(BlobLocationItem::Inline { size, data_base64 }) => { + values[index] = Some(decode_inline_data(data_base64, *size)?); + } + Some(BlobLocationItem::Presigned { + source_index, + offset, + size, + }) if *size >= self.client.blob_presign_threshold_bytes => { + direct.push((index, *source_index, *offset, *size)); + } + Some(_) => proxy_indices.push(index), + } + } + + let proxy_array = if proxy_indices.is_empty() { + None + } else { + let proxy_row_ids = proxy_indices + .iter() + .map(|index| row_ids[*index]) + .collect::>(); + Some( + self.fetch_blobs_proxy_array( + column, + &proxy_row_ids, + read_snapshot, + identity.map(str::to_owned), + ) + .await?, + ) + }; + + let direct_futures = direct + .into_iter() + .map(|(index, source_index, offset, size)| { + let source = resolved.sources[source_index].clone(); + let row_id = row_ids[index]; + let identity = identity.map(str::to_owned); + async move { + let proxy = self.blob_range_requester_with_identity( + column, + row_id, + &read_snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + Some(resolved.version), + self.branch.clone(), + None, + identity, + None, + ); + let requester = Arc::new(PresignedBlobRangeRequester::new( + context, + row_id, + size, + self.client.blob_presign_threshold_bytes, + proxy, + &source, + offset, + )); + let response = requester + .request_range(0..size, RangeRequestMode::DataRead, Some(resolved.version)) + .await?; + let BlobRangeResponse { + request_id, + response, + validated: _, + _permit, + } = response; + let bytes = read_blob_body(response, size, request_id).await?; + Ok::<_, Error>((index, bytes)) + } + }); + let direct_values = futures::stream::iter(direct_futures) + .buffered(BLOB_REQUEST_CONCURRENCY) + .try_collect::>() + .await?; + for (index, bytes) in direct_values { + values[index] = Some(bytes); + } + + if let Some(proxy_array) = proxy_array { + for (proxy_offset, index) in proxy_indices.into_iter().enumerate() { + if proxy_array.is_null(proxy_offset) { + nulls[index] = true; + } else { + values[index] = Some(Bytes::copy_from_slice(proxy_array.value(proxy_offset))); + } + } + } + + let total_bytes = values + .iter() + .flatten() + .map(Bytes::len) + .try_fold(0usize, |total, length| total.checked_add(length)); + let mut builder = LargeBinaryBuilder::with_capacity( + row_ids.len(), + total_bytes.ok_or_else(|| Error::InvalidInput { + message: "blob batch length exceeds addressable memory".into(), + })?, + ); + for index in 0..row_ids.len() { + if nulls[index] { + builder.append_null(); + } else { + let value = values[index].take().ok_or_else(|| Error::Http { + source: format!("blob_locations left row {index} without a value").into(), + request_id: "blob-locations".into(), + status_code: None, + })?; + builder.append_value(value); + } + } + Ok(builder.finish()) + } + + async fn fetch_blobs_proxy_array( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: ReadSnapshot, + identity: Option, + ) -> Result { + let mut pending: Vec<&[u64]> = vec![row_ids]; + let mut parts = Vec::new(); + while let Some(ids) = pending.pop() { + match self + .fetch_blobs_array(column, ids, read_snapshot, identity.clone()) + .await + { + Ok(array) => parts.push(array), + Err(error) if is_fetch_blobs_byte_limit_error(&error) && ids.len() > 1 => { + let mid = ids.len() / 2; + pending.push(&ids[mid..]); + pending.push(&ids[..mid]); + } + Err(error) if is_fetch_blobs_byte_limit_error(&error) => { + let mut files = self + .fetch_blob_files_with_snapshot( + column, + ids, + read_snapshot, + false, + identity.clone(), + ) + .await?; + let blob = match files.pop().unwrap() { + Some(file) => Some(file.read().await?), + None => None, + }; + parts.push(match blob { + Some(bytes) => LargeBinaryArray::new( + OffsetBuffer::new(vec![0, bytes.len() as i64].into()), + Buffer::from(bytes), + None, + ), + None => LargeBinaryArray::new_null(1), + }); + } + Err(error) => return Err(error), + } + } + let mut blobs = BlobAccumulator::new(row_ids.len())?; + for part in parts { + blobs.append(&part)?; + } + Ok(blobs.finish()?) + } + + async fn fetch_blobs_array( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: ReadSnapshot, + identity: Option, + ) -> Result { + let mut blobs = BlobAccumulator::new(row_ids.len())?; + self.fetch_blobs_chunk( + column, + row_ids, + read_snapshot, + identity.as_deref(), + &mut blobs, + ) + .await?; + Ok(blobs.finish()?) } async fn fetch_blobs_chunk( @@ -482,7 +1568,9 @@ impl RemoteTable { column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, - ) -> Result { + identity: Option<&str>, + blobs: &mut BlobAccumulator, + ) -> Result<()> { let mut body = serde_json::json!({ "version": read_snapshot.version, "column": column, @@ -494,15 +1582,24 @@ impl RemoteTable { .client .post(&format!("/v1/table/{}/fetch_blobs/", self.identifier)) .json(&body); + let expected_identity = identity.or(self.expected_query_snapshot.as_deref()); + let request = if let Some(identity) = expected_identity { + request.header(QUERY_SNAPSHOT_HEADER, identity) + } else { + request + }; let (request_id, response) = self .send_with_freshness(request, true, read_snapshot.freshness) .await?; + if response.status().is_success() { + check_query_snapshot_response(expected_identity, &response)?; + } let mut stream = match self.read_arrow_response(&request_id, response).await { Ok(stream) => stream, Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), }; - let mut blob_chunks: Vec> = Vec::new(); + let mut rows = 0; while let Some(batch) = stream.try_next().await? { let blob_column = batch.column_by_name(column).ok_or_else(|| Error::Http { source: format!("fetch_blobs response is missing the '{column}' column").into(), @@ -525,28 +1622,19 @@ impl RemoteTable { status_code: None, }); } - blob_chunks.push(arrow::compute::cast(blob_column, &DataType::LargeBinary)?); - } - let blobs = if blob_chunks.is_empty() { - LargeBinaryArray::from(Vec::>::new()) - } else { - let blob_chunk_refs: Vec<&dyn Array> = blob_chunks.iter().map(AsRef::as_ref).collect(); - arrow::compute::concat(&blob_chunk_refs)? + let array = arrow::compute::cast(blob_column, &DataType::LargeBinary)?; + let array = array .as_any() .downcast_ref::() - .ok_or_else(|| Error::Http { - source: "fetch_blobs could not read the concatenated response as LargeBinary" - .into(), - request_id: request_id.clone(), - status_code: None, - })? - .clone() - }; - if blobs.len() != row_ids.len() { + .expect("casting to LargeBinary returns LargeBinary"); + rows += array.len(); + blobs.append(array)?; + } + if rows != row_ids.len() { return Err(Error::Http { source: format!( "fetch_blobs returned {} rows for {} row ids", - blobs.len(), + rows, row_ids.len() ) .into(), @@ -554,32 +1642,391 @@ impl RemoteTable { status_code: None, }); } - Ok(blobs) + Ok(()) } - /// Materialize ranges through version-pinned handles, preserving nulls and order. + /// Materialize ranges using the protocol advertised by a successful describe. pub(super) async fn fetch_blob_ranges_impl( &self, column: &str, requests: &[BlobRangeRequest], + ) -> Result { + if requests.is_empty() { + return Ok(LargeBinaryArray::from(Vec::>::new())); + } + for request in requests { + request + .offset + .checked_add(request.length) + .ok_or_else(|| Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + })?; + } + self.reject_list_blob_path_if_known(column).await?; + if !self.blob_ranges_supported.load(Ordering::Relaxed) { + return self.fetch_blob_ranges_legacy(column, requests).await; + } + let snapshot = self.snapshot_read_state().await; + let mut identity = self.expected_query_snapshot.clone(); + if self.blob_locations_supported.load(Ordering::Relaxed) + && requests + .iter() + .any(|request| request.length >= self.client.blob_presign_threshold_bytes) + { + let mut pinned = snapshot; + match self + .resolve_blob_range_locations(column, requests, &mut pinned, &mut identity) + .await + { + Ok(Some(locations)) => { + return self + .fetch_blob_ranges_mixed(column, requests, pinned, identity, locations) + .await; + } + Ok(None) => { + // The QN advertised direct locations, but a PE lost the + // plan after describe. Reuse any version/identity pinned by + // earlier resolver partitions and retry this operation on + // the proxy path, exactly once. + log::warn!( + "blob_locations is unavailable (503); falling back to the proxy range path for this batch" + ); + return self + .fetch_blob_ranges_proxy(column, requests, pinned, identity) + .await; + } + Err(error) => return Err(error), + } + } + self.fetch_blob_ranges_proxy(column, requests, snapshot, identity) + .await + } + + /// Resolve the rows that carry at least one individually large range. + /// + /// Only these rows need locations; small-only batches never reach this + /// method, so they keep their existing proxy round trips. + async fn resolve_blob_range_locations( + &self, + column: &str, + requests: &[BlobRangeRequest], + snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result>> { + let mut row_ids = requests + .iter() + .filter(|request| request.length >= self.client.blob_presign_threshold_bytes) + .map(|request| request.row_id) + .collect::>(); + row_ids.sort_unstable(); + row_ids.dedup(); + let mut locations = HashMap::with_capacity(row_ids.len()); + for chunk in row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS) { + let context = self.blob_locations_context( + column, + snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(snapshot.freshness), + ); + let resolved = match context.resolve(chunk, false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if snapshot.version.is_none() { + snapshot.version = Some(resolved.version); + } + if snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + for (row_id, item) in chunk.iter().zip(resolved.items.iter()) { + let location = match item { + None => BlobRangeLocation::Null, + Some(BlobLocationItem::Presigned { + source_index, + offset, + size, + }) => { + let source = + resolved + .sources + .get(*source_index) + .cloned() + .ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + })?; + BlobRangeLocation::Presigned { + source, + offset: *offset, + size: *size, + } + } + Some(BlobLocationItem::Inline { .. }) + | Some(BlobLocationItem::Proxy { .. }) => BlobRangeLocation::Proxy, + }; + locations.insert(*row_id, location); + } + } + Ok(Some(locations)) + } + + async fn fetch_blob_ranges_mixed( + &self, + column: &str, + requests: &[BlobRangeRequest], + snapshot: ReadSnapshot, + identity: Option, + locations: HashMap, + ) -> Result { + let threshold = self.client.blob_presign_threshold_bytes; + let mut values: Vec> = vec![None; requests.len()]; + let mut nulls = vec![false; requests.len()]; + let mut proxy_indices = Vec::new(); + let mut proxy_requests = Vec::new(); + let mut direct = Vec::new(); + for (index, request) in requests.iter().enumerate() { + if request.length < threshold { + proxy_indices.push(index); + proxy_requests.push(*request); + continue; + } + match locations.get(&request.row_id) { + Some(BlobRangeLocation::Null) => nulls[index] = true, + Some(BlobRangeLocation::Proxy) => { + proxy_indices.push(index); + proxy_requests.push(*request); + } + Some(BlobRangeLocation::Presigned { + source, + offset, + size, + }) => { + let end = request.offset.checked_add(request.length).ok_or_else(|| { + Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + } + })?; + if end > *size { + return Err(Error::InvalidInput { + message: format!( + "blob range end {end} exceeds blob size {size} for row {}", + request.row_id + ), + }); + } + if request.length == 0 { + values[index] = Some(Bytes::new()); + } else { + direct.push((index, *request, source.clone(), *offset, *size)); + } + } + None => { + return Err(Error::InvalidInput { + message: format!( + "blob range row {} was not resolved for a large range", + request.row_id + ), + }); + } + } + } + + let direct_futures = direct + .into_iter() + .map(|(index, request, source, offset, size)| { + let proxy = self.blob_range_requester_with_identity( + column, + request.row_id, + &snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + snapshot.version, + self.branch.clone(), + None, + identity.clone(), + None, + ); + async move { + let requester = PresignedBlobRangeRequester::new( + context, + request.row_id, + size, + threshold, + proxy, + &source, + offset, + ); + let response = requester + .request_range( + request.offset..request.offset + request.length, + RangeRequestMode::DataRead, + snapshot.version, + ) + .await?; + let BlobRangeResponse { + request_id, + response, + validated: _, + _permit, + } = response; + let bytes = read_blob_body(response, request.length, request_id).await?; + Ok::<_, Error>((index, bytes)) + } + }); + let direct_values = futures::stream::iter(direct_futures) + .buffered(BLOB_REQUEST_CONCURRENCY) + .try_collect::>() + .await?; + for (index, bytes) in direct_values { + values[index] = Some(bytes); + } + + if !proxy_indices.is_empty() { + let proxy_array = self + .fetch_blob_ranges_proxy(column, &proxy_requests, snapshot, identity) + .await?; + for (position, index) in proxy_indices.into_iter().enumerate() { + if proxy_array.is_null(position) { + nulls[index] = true; + } else { + values[index] = Some(Bytes::copy_from_slice(proxy_array.value(position))); + } + } + } + + let total_bytes = values + .iter() + .flatten() + .map(Bytes::len) + .try_fold(0usize, |total, length| total.checked_add(length)); + let mut builder = LargeBinaryBuilder::with_capacity( + requests.len(), + total_bytes.ok_or_else(|| Error::InvalidInput { + message: "blob range batch length exceeds addressable memory".into(), + })?, + ); + for index in 0..requests.len() { + if nulls[index] { + builder.append_null(); + } else { + let value = values[index].take().ok_or_else(|| Error::Http { + source: format!("blob range {index} has no resolved value").into(), + request_id: "blob-locations".into(), + status_code: None, + })?; + builder.append_value(value); + } + } + Ok(builder.finish()) + } + + async fn fetch_blob_ranges_proxy( + &self, + column: &str, + requests: &[BlobRangeRequest], + mut snapshot: ReadSnapshot, + mut identity: Option, + ) -> Result { + let mut blobs = BlobAccumulator::new(requests.len())?; + if requests.is_empty() { + return Ok(blobs.finish()?); + } + let mut index = 0; + let mut consumed = 0; + let mut ranges = Vec::new(); + ranges + .try_reserve_exact(MAX_FETCH_BLOBS_ROW_IDS) + .map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + while index < requests.len() { + ranges.clear(); + let continuation = consumed != 0; + let mut budget = MAX_FETCH_BLOB_RANGE_BYTES; + while index < requests.len() && ranges.len() < MAX_FETCH_BLOBS_ROW_IDS { + let request = requests[index]; + let remaining = request.length - consumed; + if budget == 0 && remaining != 0 { + break; + } + let length = remaining.min(budget); + // The full range was checked above; all subranges fit within it. + ranges.push(BlobRangeRequest::new( + request.row_id, + request.offset + consumed, + length, + )); + consumed += length; + budget -= length; + if consumed == request.length { + index += 1; + consumed = 0; + } else { + break; + } + } + let array = self + .fetch_blob_ranges_chunk(column, &ranges, &mut snapshot, &mut identity) + .await?; + // A null has no bytes to partition. Avoid sending arbitrarily many + // empty fragments for a null with a very large requested length. + if consumed != 0 && array.is_null(array.len() - 1) { + index += 1; + consumed = 0; + } + if continuation { + blobs.append_continuation(&array)?; + } else { + blobs.append(&array)?; + } + } + Ok(blobs.finish()?) + } + + async fn fetch_blob_ranges_legacy( + &self, + column: &str, + requests: &[BlobRangeRequest], ) -> Result { let row_ids = requests .iter() .map(|request| request.row_id) .collect::>(); - let files = self.fetch_blob_files_impl(column, &row_ids).await?; + let files = self + .fetch_blob_files_with_route( + column, + &row_ids, + false, + None, + self.expected_query_snapshot.clone(), + ) + .await?; let mut builder = LargeBinaryBuilder::with_capacity(requests.len(), 0); for (file, request) in files.into_iter().zip(requests) { - let end = - request - .offset - .checked_add(request.length) - .ok_or_else(|| Error::InvalidInput { - message: "blob range offset + length overflows u64".into(), - })?; match file { Some(file) => { - let bytes = file.read_range(request.offset..end).await?; + // Overflow was checked before selecting either protocol. + let bytes = file + .read_range(request.offset..request.offset + request.length) + .await?; builder.append_value(bytes); } None => builder.append_null(), @@ -588,6 +2035,162 @@ impl RemoteTable { Ok(builder.finish()) } + async fn fetch_blob_ranges_chunk( + &self, + column: &str, + ranges: &[BlobRangeRequest], + snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result { + let _permit = self + .client + .blob_request_semaphore + .clone() + .acquire_owned() + .await + .expect("blob request semaphore is never closed"); + let body = serde_json::json!({ + "column": column, + "version": snapshot.version, + "branch": self.branch, + "ranges": ranges, + }); + let request = self + .client + .post(&format!("/v1/table/{}/fetch_blob_ranges/", self.identifier)) + .json(&body); + let request = if let Some(expected) = identity.as_deref() { + request.header(super::QUERY_SNAPSHOT_HEADER, expected) + } else { + request + }; + let (request_id, response) = self + .send_with_freshness(request, false, snapshot.freshness) + .await?; + // The range operation defines 400 as invalid input. Let the established + // checker decode structured/plain server errors before normalizing it. + let response = self + .check_table_response(&request_id, response) + .await + .map_err(|error| { + if let Error::Http { + source, + request_id, + status_code: Some(StatusCode::BAD_REQUEST), + } = error + { + Error::InvalidInput { + message: format!("fetch_blob_ranges (request {request_id}): {source}"), + } + } else { + error + } + })?; + let invalid = |message: String| Error::Http { + source: format!("fetch_blob_ranges: {message}").into(), + request_id: request_id.clone(), + status_code: None, + }; + let version = response.headers().get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version != 0) + .ok_or_else(|| invalid("missing or invalid x-lancedb-version; a server supporting the batched range endpoint is required".into()))?; + if snapshot.version.is_some_and(|expected| expected != version) { + return Err(invalid(format!( + "response version {version} differs from requested version {:?}", + snapshot.version + ))); + } + // Do not decode or accept any payload before establishing/verifying the + // identity. A later partition can never replace the original expectation. + check_query_snapshot_response(identity.as_deref(), &response)?; + if identity.is_none() { + let actual = response.headers().get(super::QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .ok_or_else(|| Error::NotSupported { + message: "Batched Blob ranges require a snapshot identity; upgrade every serving node".into(), + })?; + *identity = Some(actual.to_owned()); + } + snapshot.version = Some(version); + // This endpoint's contract is stream framing. Keep the bounded, fallible + // IPC path from #4979 instead of buffering an Arrow file response. + let content_type = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if !content_type + .split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case(crate::remote::ARROW_STREAM_CONTENT_TYPE) + { + return Err(invalid(format!( + "expected Arrow IPC stream, got '{content_type}'" + ))); + } + let mut stream = super::ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.clone(), + Some(version), + ) + .await?; + let schema = stream.schema(); + if !matches!( + schema + .field_with_name("value") + .map(|field| field.data_type()), + Ok(DataType::LargeBinary) + ) { + return Err(invalid( + "response requires a LargeBinary column named 'value'".into(), + )); + } + let mut blobs = BlobAccumulator::new(ranges.len())?; + let mut rows = 0usize; + let mut bytes = 0u64; + while let Some(batch) = stream.try_next().await? { + let array = batch + .column_by_name("value") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| { + invalid("response requires a LargeBinary column named 'value'".into()) + })?; + let end = rows + .checked_add(array.len()) + .filter(|end| *end <= ranges.len()) + .ok_or_else(|| invalid("response has more rows than requested".into()))?; + let offsets = array.value_offsets(); + bytes = bytes + .checked_add((offsets[array.len()] - offsets[0]) as u64) + .filter(|bytes| *bytes <= MAX_FETCH_BLOB_RANGE_BYTES) + .ok_or_else(|| invalid("response exceeds 64 MiB of range bytes".into()))?; + for (i, range) in ranges[rows..end].iter().enumerate() { + if array.is_valid(i) && array.value_length(i) as u64 != range.length { + return Err(invalid(format!( + "row {} returned {} bytes for requested length {}", + rows + i, + array.value_length(i), + range.length + ))); + } + } + blobs.append(array)?; + rows = end; + } + if rows != ranges.len() { + return Err(invalid(format!( + "returned {rows} rows for {} ranges", + ranges.len() + ))); + } + Ok(blobs.finish()?) + } + /// Open seekable handles for `row_ids`. /// /// Descriptors for the requested rows come from one `_rowid` take query per @@ -599,6 +2202,24 @@ impl RemoteTable { &self, column: &str, row_ids: &[u64], + ) -> Result>> { + self.fetch_blob_files_with_route( + column, + row_ids, + true, + None, + self.expected_query_snapshot.clone(), + ) + .await + } + + async fn fetch_blob_files_with_route( + &self, + column: &str, + row_ids: &[u64], + use_direct: bool, + read_snapshot: Option, + identity: Option, ) -> Result>> { self.reject_list_blob_path_if_known(column).await?; // Empty requests do not require blob-route support. @@ -607,7 +2228,11 @@ impl RemoteTable { } self.ensure_blob_files_supported()?; - let mut read_snapshot = self.snapshot_read_state().await; + let mut read_snapshot = match read_snapshot { + Some(read_snapshot) => read_snapshot, + None => self.snapshot_read_state().await, + }; + let mut identity = identity.or_else(|| self.expected_query_snapshot.clone()); let sizes = match self .take_blob_descriptor_sizes(column, row_ids, &mut read_snapshot) .await @@ -615,25 +2240,93 @@ impl RemoteTable { Ok(sizes) => sizes, Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), }; - let version = read_snapshot.version; + let direct_candidates = + if use_direct && self.blob_locations_supported.load(Ordering::Relaxed) { + let mut candidates = sizes + .iter() + .filter_map(|(row_id, size)| match size { + DescriptorSize::Known { kind, size } + if *size >= self.client.blob_presign_threshold_bytes + && is_direct_blob_kind(*kind) => + { + Some(*row_id) + } + _ => None, + }) + .collect::>(); + candidates.sort_unstable(); + candidates + } else { + Vec::new() + }; + let resolved_handles = if direct_candidates.is_empty() { + HashMap::new() + } else { + match self + .resolve_blob_file_candidates( + column, + &direct_candidates, + &mut read_snapshot, + &mut identity, + ) + .await + { + Ok(Some(handles)) => handles, + Ok(None) => { + log::warn!( + "blob_locations is unavailable (503); keeping this handle batch on the proxy path" + ); + HashMap::new() + } + Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), + } + }; + let version = read_snapshot.version; let mut files = Vec::with_capacity(row_ids.len()); let mut probe_indices = Vec::new(); let mut probe_requesters = Vec::new(); for (index, row_id) in row_ids.iter().enumerate() { + if let Some(handle) = resolved_handles.get(row_id) { + if let DescriptorSize::Known { size, .. } = sizes[row_id] + && size != handle.size + { + return Err(Error::Http { + source: format!( + "blob_locations resolved row {row_id} as {} bytes, descriptor says {size}", + handle.size + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + files.push( + handle.requester.clone().map(|requester| { + RemoteBlobFile::new(requester, handle.size, version).into() + }), + ); + continue; + } match sizes[row_id] { DescriptorSize::Null => files.push(None), - DescriptorSize::Known(size) => { - let requester = self.blob_range_requester(column, *row_id, &read_snapshot); + DescriptorSize::Known { size, .. } => { + let requester = self.blob_range_requester_with_identity( + column, + *row_id, + &read_snapshot, + identity.as_deref(), + ); files.push(Some(RemoteBlobFile::new(requester, size, version).into())); } DescriptorSize::Unresolved => { files.push(None); probe_indices.push(index); - probe_requesters.push(self.blob_range_requester( + probe_requesters.push(self.blob_range_requester_with_identity( column, *row_id, &read_snapshot, + identity.as_deref(), )); } } @@ -648,6 +2341,111 @@ impl RemoteTable { Ok(files) } + /// Resolve direct handles for descriptor rows whose logical size warrants + /// presigning. Each item must agree with the descriptor size. + async fn resolve_blob_file_candidates( + &self, + column: &str, + candidate_row_ids: &[u64], + read_snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result>> { + let mut handles = HashMap::with_capacity(candidate_row_ids.len()); + for chunk in candidate_row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS) { + let context = self.blob_locations_context( + column, + read_snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(read_snapshot.freshness), + ); + let resolved = match context.resolve(chunk, false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if read_snapshot.version.is_none() { + read_snapshot.version = Some(resolved.version); + } + if read_snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, read_snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + for (row_id, item) in chunk.iter().zip(resolved.items.iter()) { + let item = item.as_ref().ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations returned null for non-null descriptor row {row_id}" + ), + })?; + let size = match item { + BlobLocationItem::Presigned { size, .. } + | BlobLocationItem::Inline { size, .. } + | BlobLocationItem::Proxy { size } => *size, + }; + let requester = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + let source = resolved.sources.get(*source_index).ok_or_else(|| { + Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + } + })?; + let proxy = self.blob_range_requester_with_identity( + column, + *row_id, + read_snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + Some(resolved.version), + self.branch.clone(), + None, + identity.clone(), + None, + ); + Some(Arc::new(PresignedBlobRangeRequester::new( + context, + *row_id, + *size, + self.client.blob_presign_threshold_bytes, + proxy, + source, + *offset, + )) as Arc) + } + BlobLocationItem::Inline { .. } | BlobLocationItem::Proxy { .. } => { + Some(self.blob_range_requester_with_identity( + column, + *row_id, + read_snapshot, + identity.as_deref(), + )) + } + }; + handles.insert(*row_id, ResolvedBlobHandle { size, requester }); + } + } + Ok(Some(handles)) + } + pub(super) async fn open_blob_file_impl( &self, descriptor: &BlobDescriptor, @@ -663,15 +2461,26 @@ impl RemoteTable { }, ..Default::default() }; - let requester = self.blob_range_requester_with_source( + let proxy_requester = self.blob_range_requester_with_source( &source.column, source.row_reference, &snapshot, Some(source), ); + let descriptor_kind = BlobKind::try_from(descriptor.kind).unwrap_or(BlobKind::External); + let direct_candidate = self.blob_locations_supported.load(Ordering::Relaxed) + && descriptor.size >= self.client.blob_presign_threshold_bytes + && is_direct_blob_kind(descriptor_kind); + if direct_candidate + && let Some(file) = self + .open_blob_file_from_locations(descriptor, source, snapshot) + .await? + { + return Ok(file); + } let size = if descriptor.kind == 3 && descriptor.size == 0 { - let metadata = requester - .request_range("", RangeRequestMode::MetadataRead, Some(source.version)) + let metadata = proxy_requester + .request_range(0..0, RangeRequestMode::MetadataRead, Some(source.version)) .await?; if metadata.response.status() != StatusCode::OK { return Err(Error::InvalidInput { @@ -690,22 +2499,133 @@ impl RemoteTable { } else { descriptor.size }; - Ok(RemoteBlobFile::new(requester, size, Some(source.version)).into()) + Ok(RemoteBlobFile::new(proxy_requester, size, Some(source.version)).into()) + } + + async fn open_blob_file_from_locations( + &self, + descriptor: &BlobDescriptor, + source: &BlobDescriptorSource, + snapshot: ReadSnapshot, + ) -> Result> { + let context = self.blob_locations_context_for_source(source); + let resolved = match context.resolve(&[source.row_reference], false).await { + Ok(resolved) => resolved, + Err(Error::Http { + status_code: Some(StatusCode::SERVICE_UNAVAILABLE), + .. + }) => { + log::warn!( + "blob_locations is unavailable (503); opening this descriptor on the proxy path" + ); + return Ok(None); + } + Err(error) => return Err(error), + }; + let proxy_requester = self.blob_range_requester_with_source_and_identity( + &source.column, + source.row_reference, + &snapshot, + Some(source), + resolved + .identity + .clone() + .or_else(|| self.expected_query_snapshot.clone()), + ); + let item = + resolved + .items + .into_iter() + .next() + .flatten() + .ok_or_else(|| Error::InvalidInput { + message: "non-null blob descriptor did not resolve to a stored value".into(), + })?; + let size = match &item { + BlobLocationItem::Presigned { size, .. } + | BlobLocationItem::Inline { size, .. } + | BlobLocationItem::Proxy { size } => *size, + }; + if size != descriptor.size { + return Err(Error::InvalidInput { + message: format!( + "blob descriptor size {} differs from resolved size {size}", + descriptor.size + ), + }); + } + let requester: Arc = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + let source_info = + resolved + .sources + .get(source_index) + .ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + })?; + let refresh_context = self.blob_locations_context( + &source.column, + Some(source.version), + source.branch.clone(), + Some(source), + resolved + .identity + .clone() + .or_else(|| self.expected_query_snapshot.clone()), + None, + ); + Arc::new(PresignedBlobRangeRequester::new( + refresh_context, + source.row_reference, + size, + self.client.blob_presign_threshold_bytes, + proxy_requester, + source_info, + offset, + )) + } + BlobLocationItem::Inline { .. } | BlobLocationItem::Proxy { .. } => proxy_requester, + }; + Ok(Some( + RemoteBlobFile::new(requester, size, Some(source.version)).into(), + )) } /// Probe each row once for its size. /// - /// Serves callers that must not issue a query, such as a single blob that - /// the whole-byte route could not return. + /// Serves callers that must not issue a descriptor query, such as a single + /// blob that the whole-byte route could not return. Direct resolution is + /// only used when the caller wants it and the server advertises it. async fn fetch_blob_files_with_snapshot( &self, column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, + prefer_direct: bool, + identity: Option, ) -> Result>> { + if prefer_direct && self.blob_locations_supported.load(Ordering::Relaxed) { + return self + .fetch_blob_files_with_route(column, row_ids, true, Some(read_snapshot), identity) + .await; + } let requesters = row_ids .iter() - .map(|row_id| self.blob_range_requester(column, *row_id, &read_snapshot)) + .map(|row_id| { + self.blob_range_requester_with_identity( + column, + *row_id, + &read_snapshot, + identity.as_deref(), + ) + }) .collect(); match probe_blob_files(requesters).await { Ok(files) => Ok(files), @@ -757,7 +2677,9 @@ impl RemoteTable { return Err(Error::InvalidInput { message: format!( "blob read for column '{column}' requested {} row ids but only {found} exist \ - in the table; pass row ids collected from this table", + in the table; pass row ids collected from this table. If these were row \ + positions, call take_offsets(offsets, with_row_id=True) first and pass the \ + resulting row ids", unique_row_ids.len() ), }); @@ -791,14 +2713,37 @@ impl RemoteTable { .client .post(&format!("/v1/table/{}/query/", self.identifier)) .json(&body); + // The query route opens the requested version and reports the identity of + // the dataset it actually read. It does not validate the request identity, + // so accept descriptors only after comparing the response echo. + let request = if let Some(identity) = &self.expected_query_snapshot { + request.header(QUERY_SNAPSHOT_HEADER, identity) + } else { + request + }; let (request_id, response) = self .send_with_freshness(request, true, read_snapshot.freshness) .await?; + if response.status().is_success() { + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + } let response_version = response .headers() .get(&VERSION_HEADER) .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse().ok()); + if let (Some(expected), Some(actual)) = (read_snapshot.version, response_version) + && expected != actual + { + return Err(Error::Http { + source: format!( + "blob descriptor take read version {actual}, expected pinned version {expected}" + ) + .into(), + request_id, + status_code: None, + }); + } let mut stream = self.read_arrow_response(&request_id, response).await?; let mut sizes = HashMap::with_capacity(row_ids.len()); @@ -851,13 +2796,58 @@ impl RemoteTable { } } - fn blob_range_requester( + fn blob_locations_context( + &self, + column: &str, + version: Option, + branch: Option, + source: Option<&BlobDescriptorSource>, + identity: Option, + freshness: Option, + ) -> BlobLocationsContext { + BlobLocationsContext { + client: self.client.clone(), + identifier: self.identifier.clone(), + table_name: self.name.clone(), + column: column.to_string(), + version, + branch: source.map_or(branch, |source| source.branch.clone()), + source_uri: source.map(|source| source.uri.clone()), + source_commit_micros: source.map(|source| source.committed_at_micros), + row_is_address: source.is_some_and(|source| source.row_is_address), + expected_query_snapshot: identity, + freshness, + } + } + + fn blob_locations_context_for_source( + &self, + source: &BlobDescriptorSource, + ) -> BlobLocationsContext { + self.blob_locations_context( + &source.column, + Some(source.version), + source.branch.clone(), + Some(source), + self.expected_query_snapshot.clone(), + None, + ) + } + + fn blob_range_requester_with_identity( &self, column: &str, row_id: u64, read_snapshot: &ReadSnapshot, + identity: Option<&str>, ) -> Arc { - self.blob_range_requester_with_source(column, row_id, read_snapshot, None) + self.blob_range_requester_with_source_and_identity( + column, + row_id, + read_snapshot, + None, + identity.map(str::to_owned), + ) } fn blob_range_requester_with_source( @@ -866,6 +2856,23 @@ impl RemoteTable { row_id: u64, read_snapshot: &ReadSnapshot, source: Option<&BlobDescriptorSource>, + ) -> Arc { + self.blob_range_requester_with_source_and_identity( + column, + row_id, + read_snapshot, + source, + self.expected_query_snapshot.clone(), + ) + } + + fn blob_range_requester_with_source_and_identity( + &self, + column: &str, + row_id: u64, + read_snapshot: &ReadSnapshot, + source: Option<&BlobDescriptorSource>, + identity: Option, ) -> Arc { let path = format!( "/v1/table/{}/blob/{}/{row_id}/bytes", @@ -878,6 +2885,7 @@ impl RemoteTable { version: read_snapshot.version, branch: source.map_or_else(|| self.branch.clone(), |source| source.branch.clone()), source_uri: source.map(|source| source.uri.clone()), + expected_query_snapshot: identity, source_commit_micros: source.map(|source| source.committed_at_micros), row_is_address: source.is_some_and(|source| source.row_is_address), freshness: Arc::new(std::sync::Mutex::new(read_snapshot.freshness_state)), @@ -892,12 +2900,42 @@ impl RemoteTable { #[derive(Debug, Clone, Copy)] enum DescriptorSize { Null, - Known(u64), + Known { + kind: BlobKind, + size: u64, + }, /// An external blob that recorded no size. Its length is the whole /// object's, which only the server can resolve. Unresolved, } +/// A resolved handle candidate. `requester` is `None` only when the server +/// resolved a non-null descriptor to null, which is a protocol error. +struct ResolvedBlobHandle { + size: u64, + requester: Option>, +} + +/// A row's resolved backing object for a large range request. +enum BlobRangeLocation { + Null, + Presigned { + source: BlobLocationSource, + offset: u64, + size: u64, + }, + Proxy, +} + +/// Blob kinds that M1 may read directly. Inline bytes stay on the proxy route, +/// and External URIs keep their existing authority and lifecycle. +fn is_direct_blob_kind(kind: BlobKind) -> bool { + matches!( + kind, + BlobKind::Dedicated | BlobKind::Packed | BlobKind::Managed | BlobKind::ManagedWithBase + ) +} + /// The `kind` and `size` children of a blob v2 descriptor array. struct BlobDescriptorSizes<'a> { descriptors: &'a StructArray, @@ -924,7 +2962,7 @@ impl<'a> BlobDescriptorSizes<'a> { Ok(if kind == BlobKind::External && size == 0 { DescriptorSize::Unresolved } else { - DescriptorSize::Known(size) + DescriptorSize::Known { kind, size } }) } } @@ -963,9 +3001,10 @@ async fn probe_blob_file(requester: Arc) -> Result { @@ -1055,6 +3094,10 @@ mod tests { use super::*; const PAYLOAD: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz"; + const TEST_SNAPSHOT_IDENTITY: &str = + "v1:0000000000000000000000000000000000000000000000000000000000000000"; + const SNAPSHOT_A: &str = "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const SNAPSHOT_B: &str = "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; fn null_blob_response() -> http::Response> { http::Response::builder() @@ -1272,7 +3315,7 @@ mod tests { row_ids: &[u64], ) -> Result>> { let read_snapshot = self.snapshot_read_state().await; - self.fetch_blob_files_with_snapshot(column, row_ids, read_snapshot) + self.fetch_blob_files_with_snapshot(column, row_ids, read_snapshot, false, None) .await } } @@ -1324,6 +3367,7 @@ mod tests { assert_eq!(body["with_row_id"], serde_json::json!(true)); assert_eq!(body["use_rte"], serde_json::json!(false)); let requested = filter_row_ids(body["filter"].as_str().unwrap()); + let requested_version = body["version"].as_u64(); captured.lock().unwrap().push(TakeMockRequest::Query { row_ids: requested.clone(), version: body["version"].as_u64(), @@ -1355,7 +3399,9 @@ mod tests { writer.finish().unwrap(); drop(writer); let mut response = http::Response::builder().status(200); - if let Some(version) = query_version { + if let Some(version) = requested_version { + response = response.header(VERSION_HEADER, version.to_string()); + } else if let Some(version) = query_version { response = response.header(VERSION_HEADER, version); } return response.body(body).unwrap(); @@ -1497,7 +3543,226 @@ mod tests { let error = table.fetch_blob_ranges("image", &ranges).await.unwrap_err(); assert!(error.to_string().contains(message), "{error}"); // Missing rows and invalid ranges fail without reading any bytes. - assert_eq!(requests.lock().unwrap().len(), 1); + assert!(matches!(error, Error::InvalidInput { .. })); + assert_eq!( + requests.lock().unwrap().len(), + usize::from(!message.contains("overflows")) + ); + } + } + + #[tokio::test] + async fn remote_blob_ranges_keep_producing_query_identity_from_first_request() { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let calls = Arc::new(StdMutex::new(Vec::new())); + let captured = calls.clone(); + let table = RemoteTable::new_mock( + "my_table".into(), + move |request| { + assert_eq!( + request.url().path(), + "/v1/table/my_table/fetch_blob_ranges/" + ); + assert_eq!( + request.headers()[super::super::QUERY_SNAPSHOT_HEADER], + IDENTITY + ); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["version"], 42); + let rows = body["ranges"].as_array().unwrap().len(); + captured.lock().unwrap().push(rows); + let batch = RecordBatch::try_from_iter([( + "value", + Arc::new(LargeBinaryArray::from(vec![Some(b"A".as_slice()); rows])) + as Arc, + )]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "42") + .header(super::super::QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(bytes) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let snapshot = table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap(); + let ranges = snapshot + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(b"A".as_slice()); 1025]) + ); + assert_eq!(*calls.lock().unwrap(), [1024, 1]); + assert!(table.snapshot_read_state().await.version.is_none()); + } + + #[tokio::test] + async fn remote_blob_ranges_cancel_releases_the_only_request_permit() { + use std::sync::atomic::AtomicUsize; + let entered = Arc::new(tokio::sync::Notify::new()); + let started = entered.clone(); + let calls = Arc::new(AtomicUsize::new(0)); + let captured = calls.clone(); + let table = Arc::new(RemoteTable::new_mock_with_version_and_config( + "my_table".into(), + move |request| { + assert!(request.url().path().ends_with("/fetch_blob_ranges/")); + if captured.fetch_add(1, Ordering::SeqCst) == 0 { + started.notify_one(); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header( + super::super::QUERY_SNAPSHOT_HEADER, + format!("v1:{}", "a".repeat(64)), + ) + .body(reqwest::Body::wrap_stream(futures::stream::pending::< + std::result::Result, + >())) + .unwrap() + } else { + http::Response::builder() + .status(400) + .header("x-lancedb-error-code", "invalid_input") + .body(reqwest::Body::from( + r#"{"error":"range exceeds blob size"}"#, + )) + .unwrap() + } + }, + Some(Version::new(1, 13, 0)), + crate::remote::ClientConfig { + blob_request_concurrency: Some(1), + ..Default::default() + }, + )); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let reader_table = table.clone(); + let reader = tokio::spawn(async move { + reader_table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + }); + tokio::time::timeout(Duration::from_secs(5), entered.notified()) + .await + .unwrap(); + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + let error = tokio::time::timeout( + Duration::from_secs(5), + table.fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1)]), + ) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds blob size")); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn remote_blob_ranges_reject_overflow_before_http() { + let (table, requests) = mock_take_blob_table(vec![], Some("7")); + let error = table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err(); + assert!(error.to_string().contains("overflows u64"), "{error}"); + assert!(requests.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn remote_blob_files_reject_unverified_descriptor_identity_before_values() { + const EXPECTED: &str = + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + const OTHER: &str = "v1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + for response_identity in [None, Some(OTHER)] { + let range_requests = Arc::new(AtomicUsize::new(0)); + let captured_ranges = range_requests.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path().to_string(); + if path == "/v1/table/my_table/query/" { + // Row 20 is NULL and row 40 is empty, so an unverified + // result could escape without any payload request. + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], EXPECTED); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(filter_row_ids(body["filter"].as_str().unwrap()), [20, 40]); + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[None, Some((BlobKind::Inline, 0))])) + as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([20, 40])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()) + .unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + let mut response = http::Response::builder() + .status(200) + .header(VERSION_HEADER, "42"); + if let Some(identity) = response_identity { + response = response.header(QUERY_SNAPSHOT_HEADER, identity); + } + return response.body(body).unwrap(); + } + if path.starts_with("/v1/table/my_table/blob/") { + captured_ranges.fetch_add(1, Ordering::SeqCst); + panic!("descriptor verification must fail before any payload read"); + } + panic!("unexpected path: {path}"); + }, + Some(Version::new(0, 5, 0)), + ); + let snapshot = table + .query_snapshot_with_identity(42, EXPECTED) + .await + .unwrap(); + + let error = snapshot + .fetch_blob_files("image", &[20, 40]) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + assert_eq!(range_requests.load(Ordering::SeqCst), 0); } } @@ -1893,9 +4158,8 @@ mod tests { [ ("bytes=0-0".to_string(), None), ("bytes=5-8".to_string(), Some("5".to_string())), - ("bytes=0-3".to_string(), Some("5".to_string())), ( - format!("bytes=10-{}", PAYLOAD.len() - 1), + format!("bytes=0-{}", PAYLOAD.len() - 1), Some("5".to_string()) ), ] @@ -1943,7 +4207,7 @@ mod tests { } #[tokio::test] - async fn remote_blob_file_releases_response_after_each_partial_read() { + async fn remote_blob_file_reuses_prefetched_bytes_across_reads_and_seeks() { let requests = Arc::new(StdMutex::new(Vec::new())); let table = mock_remote_blob_table(requests.clone()); let file = table @@ -1961,7 +4225,41 @@ mod tests { assert_eq!(file.tell().await.unwrap(), 24); assert_eq!( requests.lock().unwrap().as_slice(), - ["bytes=0-0", "bytes=0-3", "bytes=4-6", "bytes=20-23"] + ["bytes=0-0", &format!("bytes=0-{}", PAYLOAD.len() - 1)] + ); + } + + #[tokio::test] + async fn remote_buffer_boundaries_and_disabled_read_ahead() { + let requests = Arc::new(StdMutex::new(Vec::new())); + let table = mock_remote_blob_table(requests.clone()); + let file = table + .probe_files("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + file.set_buffer_size(4).await.unwrap(); + assert_eq!(file.read_up_to(3).await.unwrap(), &PAYLOAD[..3]); + assert_eq!(file.read_up_to(3).await.unwrap(), &PAYLOAD[3..6]); + file.seek(5).await.unwrap(); + assert_eq!(file.read_up_to(2).await.unwrap(), &PAYLOAD[5..7]); + assert_eq!(file.read_range(5..6).await.unwrap(), &PAYLOAD[5..6]); + assert_eq!(file.tell().await.unwrap(), 7); + file.set_buffer_size(0).await.unwrap(); + assert_eq!(file.read_up_to(1).await.unwrap(), &PAYLOAD[7..8]); + assert_eq!(file.read_up_to(1).await.unwrap(), &PAYLOAD[8..9]); + assert_eq!( + requests.lock().unwrap().as_slice(), + [ + "bytes=0-0", + "bytes=0-3", + "bytes=4-7", + "bytes=5-5", + "bytes=7-7", + "bytes=8-8" + ] ); } @@ -2198,6 +4496,7 @@ mod tests { .flatten() .unwrap(); + file.set_buffer_size(0).await.unwrap(); let error = file.read_up_to(10).await.unwrap_err(); assert!( error.to_string().contains("returned 5 bytes, expected 10"), @@ -2238,11 +4537,11 @@ mod tests { impl BlobRangeRequester for CountingProbeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { - assert_eq!(range_header, "bytes=0-0"); + assert_eq!(range, 0..1); let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1; self.max_in_flight.fetch_max(now, Ordering::SeqCst); // Earlier probes sleep longer, so later probes finish first and the @@ -2324,6 +4623,7 @@ mod tests { file.read_up_to(1).await.unwrap_err(), file.seek(0).await.unwrap_err(), file.tell().await.unwrap_err(), + file.set_buffer_size(0).await.unwrap_err(), ] { assert!(error.to_string().contains("already closed"), "got: {error}"); } @@ -2419,7 +4719,7 @@ mod tests { impl BlobRangeRequester for CountingRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { @@ -2427,13 +4727,8 @@ mod tests { self.max_in_flight.fetch_max(now, Ordering::SeqCst); tokio::time::sleep(Duration::from_millis(5)).await; self.in_flight.fetch_sub(1, Ordering::SeqCst); - let (start, end) = range_header - .strip_prefix("bytes=") - .unwrap() - .split_once('-') - .unwrap(); - let start = start.parse::().unwrap(); - let end = end.parse::().unwrap(); + let start = range.start as usize; + let end = (range.end - 1) as usize; let response = http::Response::builder() .status(StatusCode::PARTIAL_CONTENT) .header( @@ -2530,31 +4825,144 @@ mod tests { assert!(error.to_string().contains("206"), "got: {error}"); } + #[tokio::test] + async fn impossible_range_capacity_returns_an_error() { + let size = isize::MAX as u64 + 1; + let table = RemoteTable::new_mock( + "videos".to_string(), + move |request| { + let range = request + .headers() + .get(header::RANGE) + .unwrap() + .to_str() + .unwrap(); + let end = if range == "bytes=0-0" { 0 } else { size - 1 }; + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, format!("bytes 0-{end}/{size}")) + .header(VERSION_HEADER, "5") + .body(vec![1]) + .unwrap() + }, + Some(Version::new(0, 5, 0)), + ); + let file = table + .probe_files("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + let error = file.read().await.unwrap_err(); + assert!( + error.to_string().contains("cannot allocate blob range"), + "{error}" + ); + assert_eq!(file.tell().await.unwrap(), 0); + } + + #[derive(Debug)] + struct TrackedRangeBody { + bytes: Vec, + dropped: Arc, + } + + impl AsRef<[u8]> for TrackedRangeBody { + fn as_ref(&self) -> &[u8] { + &self.bytes + } + } + + impl Drop for TrackedRangeBody { + fn drop(&mut self) { + self.dropped.store(true, Ordering::Release); + } + } + + #[tokio::test] + async fn close_releases_existing_cache_after_in_flight_read_ends() { + for cancel in [false, true] { + let release = Arc::new(tokio::sync::Barrier::new(2)); + let started = Arc::new(tokio::sync::Notify::new()); + let dropped = Arc::new(AtomicBool::new(false)); + let file = Arc::new(RemoteBlobFile::new( + Arc::new(BlockingRangeRequester { + release: release.clone(), + started: started.clone(), + block_start: 4, + tracked: Some(dropped.clone()), + }), + PAYLOAD.len() as u64, + Some(5), + )); + file.set_buffer_size(4).await.unwrap(); + assert_eq!(file.read_up_to(1).await.unwrap().as_ref(), &PAYLOAD[..1]); + file.seek(3).await.unwrap(); + assert!( + !dropped.load(Ordering::Acquire), + "warm cache was not retained" + ); + let reader = { + let file = file.clone(); + tokio::spawn(async move { file.read_up_to(2).await }) + }; + started.notified().await; + tokio::time::timeout(Duration::from_millis(50), file.close()) + .await + .expect("close waited for I/O") + .unwrap(); + if cancel { + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + } else { + release.wait().await; + let error = reader.await.unwrap().unwrap_err(); + assert!(error.to_string().contains("already closed"), "{error}"); + } + assert!( + dropped.load(Ordering::Acquire), + "closed handle retained its old window (cancel={cancel})" + ); + } + } + #[derive(Debug)] struct BlockingRangeRequester { release: Arc, started: Arc, + block_start: usize, + tracked: Option>, } #[async_trait::async_trait] impl BlobRangeRequester for BlockingRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { - if range_header == "bytes=0-3" { + let start = range.start as usize; + let end = (range.end - 1) as usize; + if start == self.block_start { self.started.notify_one(); self.release.wait().await; } + let bytes = match &self.tracked { + Some(dropped) if start == 0 => Bytes::from_owner(TrackedRangeBody { + bytes: PAYLOAD[start..=end].to_vec(), + dropped: dropped.clone(), + }), + _ => Bytes::copy_from_slice(&PAYLOAD[start..=end]), + }; let response = http::Response::builder() .status(StatusCode::PARTIAL_CONTENT) .header( header::CONTENT_RANGE, - format!("bytes 0-{}/{}", PAYLOAD.len() - 1, PAYLOAD.len()), + format!("bytes {start}-{end}/{}", PAYLOAD.len()), ) - .body(PAYLOAD.to_vec()) + .body(bytes) .unwrap(); Ok(("hung".to_string(), Response::from(response)).into()) } @@ -2567,6 +4975,8 @@ mod tests { let requester: Arc = Arc::new(BlockingRangeRequester { release: release.clone(), started: started.clone(), + block_start: 0, + tracked: None, }); let file = Arc::new(RemoteBlobFile::new( requester, @@ -2597,4 +5007,1498 @@ mod tests { .contains("already closed") ); } + + fn blob_ipc_stream(values: &[Option<&[u8]>], column: &str) -> Vec { + let array = LargeBinaryArray::from(values.to_vec()); + let batch = + RecordBatch::try_from_iter([(column, Arc::new(array) as Arc)]).unwrap(); + let mut bytes = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + bytes + } + + fn blob_locations_json(body: serde_json::Value, version: u64) -> http::Response> { + http::Response::builder() + .status(200) + .header(VERSION_HEADER, version.to_string()) + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body(body.to_string().into_bytes()) + .unwrap() + } + + fn direct_blob_file_table( + kind: BlobKind, + size: u64, + object_handler: F, + ) -> RemoteTable + where + F: Fn(reqwest::Request) -> http::Response> + Send + Sync + 'static, + { + RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return object_handler(request); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some((kind, size))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([10])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10])); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(body["include_inline_data"], serde_json::json!(false)); + return blob_locations_json( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + "expires_at_unix_secs": 4102444800u64, + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": size, + }], + }), + 7, + ); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!( + request + .url() + .query_pairs() + .find(|(name, _)| name == "version") + .map(|(_, value)| value.into_owned()), + Some("7".to_string()) + ); + let response = range_response(&request, PAYLOAD); + let content_range = response.headers()[header::CONTENT_RANGE].clone(); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, content_range) + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .header(VERSION_HEADER, "7") + .body(response.into_body()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ) + } + + #[tokio::test] + async fn describe_seeds_blob_locations_capability() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + |_| { + http::Response::builder() + .status(200) + .header("x-lancedb-blob-locations", "1") + .body(r#"{"version":1,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + table.describe().await.unwrap(); + assert!( + table + .blob_locations_supported + .load(std::sync::atomic::Ordering::Relaxed) + ); + } + + #[tokio::test] + async fn direct_blob_file_translates_physical_offsets_and_preserves_nulls() { + let object_requests = Arc::new(StdMutex::new(Vec::new())); + let captured = object_requests.clone(); + let table = + direct_blob_file_table(BlobKind::Packed, PAYLOAD.len() as u64, move |request| { + assert_eq!(request.method(), reqwest::Method::GET); + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=106-110" + ); + assert!(request.headers().get("authorization").is_none()); + assert!(request.headers().get("x-api-key").is_none()); + captured.lock().unwrap().push(request.url().to_string()); + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 106-110/500") + .body(PAYLOAD[6..11].to_vec()) + .unwrap() + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!( + file.read_range(6..11).await.unwrap().as_ref(), + &PAYLOAD[6..11] + ); + assert_eq!(object_requests.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn direct_blob_file_small_ranges_stay_on_the_proxy() { + let table = direct_blob_file_table(BlobKind::Managed, PAYLOAD.len() as u64, |_| { + panic!("small range must not read from object storage") + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!( + file.read_range(6..11).await.unwrap().as_ref(), + &PAYLOAD[6..11] + ); + } + + #[tokio::test] + async fn direct_blob_file_rejects_mismatched_content_range() { + let table = direct_blob_file_table(BlobKind::Packed, PAYLOAD.len() as u64, |_| { + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-104/500") + .body(PAYLOAD[..5].to_vec()) + .unwrap() + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + let error = file.read_range(6..11).await.unwrap_err(); + assert!(error.to_string().contains("Content-Range"), "{error}"); + } + + #[tokio::test] + async fn direct_blob_file_refreshes_expired_url_once() { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let locations = Arc::new(AtomicUsize::new(0)); + let captured_locations = locations.clone(); + let object = Arc::new(AtomicUsize::new(0)); + let captured_object = object.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + let call = captured_object.fetch_add(1, Ordering::SeqCst) + 1; + if request + .url() + .query() + .is_some_and(|query| query.contains("sig=old")) + { + return http::Response::builder() + .status(StatusCode::FORBIDDEN) + .body(Vec::new()) + .unwrap(); + } + assert_eq!(call, 2); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-104/500") + .body(PAYLOAD[..5].to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some(( + BlobKind::Packed, + PAYLOAD.len() as u64, + ))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([10])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let call = captured_locations.fetch_add(1, Ordering::SeqCst) + 1; + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + let sig = if call == 1 { "old" } else { "new" }; + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": format!("https://objects.example/sidecar.blob?sig={sig}"), + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!(file.read_range(0..5).await.unwrap().as_ref(), &PAYLOAD[..5]); + assert_eq!(locations.load(Ordering::SeqCst), 2); + assert_eq!(object.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn fetch_blobs_reads_large_presigned_inline_and_proxy_rows_in_order() { + const IDENTITY: &str = + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let proxied = Arc::new(StdMutex::new(Vec::new())); + let captured_proxied = proxied.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=100-135" + ); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-135/500") + .body(PAYLOAD.to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10, 20, 30, 40])); + assert_eq!(body["include_inline_data"], serde_json::json!(true)); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [ + { "kind": "presigned", "source_index": 0, "offset": 100, "size": PAYLOAD.len() }, + { "kind": "inline", "size": 4, "data_base64": "AQIDBA==" }, + { "kind": "proxy", "size": PAYLOAD.len() }, + null + ], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([30])); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + captured_proxied.lock().unwrap().push(30); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table + .fetch_blobs_impl("image", &[10, 20, 30, 40]) + .await + .unwrap(); + assert_eq!( + blobs, + LargeBinaryArray::from(vec![ + Some(PAYLOAD), + Some(b"\x01\x02\x03\x04".as_slice()), + Some(PAYLOAD), + None, + ]) + ); + assert_eq!(*proxied.lock().unwrap(), [30]); + } + + #[tokio::test] + async fn fetch_blobs_keeps_small_presigned_values_on_the_proxy() { + let proxied = Arc::new(StdMutex::new(Vec::new())); + let captured_proxied = proxied.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("small presigned value must not use object storage"); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + captured_proxied.lock().unwrap().push(10); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 100; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + assert_eq!(*proxied.lock().unwrap(), [10]); + } + + #[tokio::test] + async fn fetch_blob_ranges_routes_large_ranges_direct_and_small_ranges_proxy() { + const IDENTITY: &str = + "v1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=100-109" + ); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-109/500") + .body(PAYLOAD[..10].to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10, 30, 40])); + assert_eq!(body["include_inline_data"], serde_json::json!(false)); + assert_eq!(body["version"], serde_json::Value::Null); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [ + { "kind": "presigned", "source_index": 0, "offset": 100, "size": PAYLOAD.len() }, + { "kind": "proxy", "size": PAYLOAD.len() }, + null + ], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blob_ranges/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + assert_eq!( + body["ranges"], + serde_json::json!([ + { "row_id": 20, "offset": 0, "length": 9 }, + { "row_id": 30, "offset": 0, "length": 12 }, + ]) + ); + let body = + blob_ipc_stream(&[Some(&PAYLOAD[..9]), Some(&PAYLOAD[..12])], "value"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 10), + BlobRangeRequest::new(20, 0, 9), + BlobRangeRequest::new(30, 0, 12), + BlobRangeRequest::new(40, 0, 10), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![ + Some(&PAYLOAD[..10]), + Some(&PAYLOAD[..9]), + Some(&PAYLOAD[..12]), + None, + ]) + ); + } + + #[tokio::test] + async fn fetch_blob_ranges_falls_back_to_proxy_when_locations_lose_their_plan() { + const IDENTITY: &str = + "v1:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blob_ranges/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!( + body["ranges"], + serde_json::json!([ + { "row_id": 10, "offset": 0, "length": 10 }, + { "row_id": 20, "offset": 0, "length": 1 }, + ]) + ); + let body = + blob_ipc_stream(&[Some(&PAYLOAD[..10]), Some(&PAYLOAD[..1])], "value"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 10), + BlobRangeRequest::new(20, 0, 1), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(&PAYLOAD[..10]), Some(&PAYLOAD[..1])]) + ); + } + + #[tokio::test] + async fn fetch_blob_ranges_small_only_batches_never_resolve_locations() { + const IDENTITY: &str = + "v1:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + assert_ne!(path, "/v1/table/my_table/blob_locations/"); + assert_eq!(path, "/v1/table/my_table/fetch_blob_ranges/"); + let body = blob_ipc_stream(&[Some(&PAYLOAD[..1]), Some(&PAYLOAD[1..2])], "value"); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 1), + BlobRangeRequest::new(20, 1, 1), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(&PAYLOAD[..1]), Some(&PAYLOAD[1..2])]) + ); + } + + #[tokio::test] + async fn fetch_blobs_falls_back_to_proxy_when_locations_lose_their_plan() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + assert_eq!(path, "/v1/table/my_table/fetch_blobs/"); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .body(body) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + } + + #[tokio::test] + async fn blob_file_resolver_503_after_pinning_keeps_version_and_identity_on_proxy() { + const IDENTITY: &str = + "v1:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let requested = filter_row_ids(body["filter"].as_str().unwrap()); + let rows = requested + .iter() + .map(|row_id| (*row_id, Some((BlobKind::Packed, PAYLOAD.len() as u64)))) + .collect::>(); + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors( + &rows.iter().map(|(_, row)| *row).collect::>(), + )) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values( + rows.iter().map(|(row_id, _)| *row_id), + )) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let requested = body["row_ids"].as_array().unwrap().len(); + if requested != MAX_FETCH_BLOBS_ROW_IDS { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + let items = (0..requested) + .map(|_| { + serde_json::json!({ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }) + }) + .collect::>(); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": items, + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/0/bytes" { + let parameters = request + .url() + .query_pairs() + .into_owned() + .collect::>(); + assert_eq!(parameters["version"], "7"); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + let response = range_response(&request, PAYLOAD); + let content_range = response.headers()[header::CONTENT_RANGE].clone(); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, content_range) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .header(VERSION_HEADER, "7") + .body(response.into_body()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let row_ids = (0..MAX_FETCH_BLOBS_ROW_IDS as u64 + 1).collect::>(); + let files = table + .fetch_blob_files_impl("image", &row_ids) + .await + .unwrap(); + assert_eq!(files.len(), row_ids.len()); + let file = files[0].as_ref().unwrap(); + assert_eq!(file.read_range(0..1).await.unwrap().as_ref(), &PAYLOAD[..1]); + } + + #[tokio::test] + async fn oversized_whole_blob_fallback_after_resolver_503_does_not_resolve_again() { + let locations = Arc::new(AtomicUsize::new(0)); + let captured_locations = locations.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("proxy fallback must not use object storage"); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + captured_locations.fetch_add(1, Ordering::SeqCst); + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/describe/" { + return http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + return http::Response::builder() + .status(StatusCode::BAD_REQUEST) + .body( + "fetch_blobs accepts at most 64 MiB of total blob bytes per request" + .as_bytes() + .to_vec(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + return range_response(&request, PAYLOAD); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + assert_eq!(locations.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn object_store_503_does_not_masquerade_as_resolver_unavailable() { + let proxy_calls = Arc::new(AtomicUsize::new(0)); + let captured_proxy = proxy_calls.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + captured_proxy.fetch_add(1, Ordering::SeqCst); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let error = table.fetch_blobs_impl("image", &[10]).await.unwrap_err(); + assert_eq!(error.status_code(), Some(StatusCode::SERVICE_UNAVAILABLE)); + assert_eq!(proxy_calls.load(Ordering::SeqCst), 0); + } + + fn location_response( + identity: Option<&str>, + item: serde_json::Value, + ) -> http::Response> { + location_response_count(identity, item, 1) + } + + fn location_response_count( + identity: Option<&str>, + item: serde_json::Value, + count: usize, + ) -> http::Response> { + let mut response = http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7"); + if let Some(identity) = identity { + response = response.header(QUERY_SNAPSHOT_HEADER, identity); + } + response + .body( + serde_json::json!({ + "sources": [{"url": "https://objects.example/object"}], + "items": vec![item; count], + }) + .to_string() + .into_bytes(), + ) + .unwrap() + } + + fn descriptor_take_response(version: u8, row_id: u64) -> http::Response> { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some((BlobKind::Packed, 1))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([row_id])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + http::Response::builder() + .status(200) + .header(VERSION_HEADER, version.to_string()) + .body(body) + .unwrap() + } + + #[tokio::test] + async fn resolver_rejects_a_response_without_a_snapshot_identity() { + let object_calls = Arc::new(AtomicUsize::new(0)); + let captured_object = object_calls.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + captured_object.fetch_add(1, Ordering::SeqCst); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .body(b"A".to_vec()) + .unwrap(); + } + if request.url().path() == "/v1/table/my_table/blob_locations/" { + return location_response( + None, + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + + let error = table + .fetch_blob_ranges_impl("image", &[BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap_err(); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + assert_eq!(object_calls.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn resolver_rejects_a_different_identity_in_a_later_partition() { + let resolves = Arc::new(AtomicUsize::new(0)); + let captured_resolves = resolves.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("no object read should happen after an identity mismatch"); + } + if request.url().path() == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let count = body["row_ids"].as_array().unwrap().len(); + let call = captured_resolves.fetch_add(1, Ordering::SeqCst); + let identity = if call == 0 { SNAPSHOT_A } else { SNAPSHOT_B }; + return location_response_count( + Some(identity), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + count, + ); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + let requests = (0..=MAX_FETCH_BLOBS_ROW_IDS as u64) + .map(|row_id| BlobRangeRequest::new(row_id, 0, 1)) + .collect::>(); + let error = table + .fetch_blob_ranges_impl("image", &requests) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + fn refresh_503_table() -> RemoteTable { + let resolves = Arc::new(AtomicUsize::new(0)); + let mut table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::FORBIDDEN) + .body(Vec::new()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + if resolves.fetch_add(1, Ordering::SeqCst) == 0 { + return location_response( + Some(SNAPSHOT_A), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, SNAPSHOT_B) + .body(b"B".to_vec()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + table + } + + #[tokio::test] + async fn whole_read_proxy_fallback_after_refresh_503_keeps_resolver_identity() { + let error = refresh_503_table() + .fetch_blobs_impl("image", &[10]) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn range_read_proxy_fallback_after_refresh_503_keeps_resolver_identity() { + let error = refresh_503_table() + .fetch_blob_ranges_impl("image", &[BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn oversized_proxy_fallback_keeps_resolver_identity() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/describe/" { + return http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::BAD_REQUEST) + .body( + b"fetch_blobs accepts at most 64 MiB of total blob bytes per request" + .to_vec(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, SNAPSHOT_B) + .body(b"B".to_vec()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let error = table + .fetch_blobs_proxy_array("image", &[10], snapshot, Some(SNAPSHOT_A.into())) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn direct_open_keeps_the_supplied_snapshot_when_capability_appears() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().path() == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + return descriptor_take_response(8, 20); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let error = table + .fetch_blob_files_with_snapshot("image", &[20], snapshot, true, Some(SNAPSHOT_A.into())) + .await + .unwrap_err(); + assert!( + error.to_string().contains("expected pinned version 7"), + "{error}" + ); + } + + #[tokio::test] + async fn direct_open_succeeds_at_the_supplied_snapshot() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .body(b"A".to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + return descriptor_take_response(7, 20); + } + if path == "/v1/table/my_table/blob_locations/" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return location_response( + Some(SNAPSHOT_A), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let mut files = table + .fetch_blob_files_with_snapshot("image", &[20], snapshot, true, Some(SNAPSHOT_A.into())) + .await + .unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!(file.read_range(0..1).await.unwrap().as_ref(), b"A"); + } + + struct RefreshHarness { + table: RemoteTable, + resolves: Arc, + objects: Arc, + } + + fn refresh_harness( + first_expires: Option, + second_expires: Option, + second_identity: &'static str, + second_location_status: Option, + fail_second_object: bool, + ) -> RefreshHarness { + let resolves = Arc::new(AtomicUsize::new(0)); + let objects = Arc::new(AtomicUsize::new(0)); + let captured_resolves = resolves.clone(); + let captured_objects = objects.clone(); + let mut table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + captured_objects.fetch_add(1, Ordering::SeqCst); + let old = request + .url() + .query() + .is_some_and(|query| query.contains("sig=old")); + if old || fail_second_object { + return http::Response::builder() + .status(StatusCode::FORBIDDEN) + .body(Vec::new()) + .unwrap(); + } + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .body(b"A".to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + let call = captured_resolves.fetch_add(1, Ordering::SeqCst) + 1; + if call == 2 + && let Some(status) = second_location_status + { + return http::Response::builder() + .status(status) + .body(Vec::new()) + .unwrap(); + } + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!( + body["source_uri"], + serde_json::json!("s3://bucket/table.lance") + ); + assert_eq!(body["source_commit_micros"], serde_json::json!(1234)); + let identity = if call == 1 { + SNAPSHOT_A + } else { + second_identity + }; + let expires = if call == 1 { + first_expires + } else { + second_expires + }; + let mut source = serde_json::json!({"url": format!("https://objects.example/object?sig={sig}", sig = if call == 1 { "old" } else { "new" })}); + if let Some(expires) = expires { + source["expires_at_unix_secs"] = expires.into(); + } + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, identity) + .body( + serde_json::json!({ + "sources": [source], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 0, + "size": 1, + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + RefreshHarness { + table, + resolves, + objects, + } + } + + fn descriptor_for_refresh_harness() -> BlobDescriptor { + BlobDescriptor { + kind: BlobKind::Dedicated as u8, + position: 0, + size: 1, + blob_id: 0, + blob_uri: String::new(), + source: BlobDescriptorSource { + uri: "s3://bucket/table.lance".into(), + version: 7, + committed_at_micros: 1234, + branch: None, + column: "image".into(), + row_reference: 10, + row_is_address: false, + }, + } + } + + async fn read_one_byte(harness: &RefreshHarness) -> Result<()> { + let file = harness + .table + .open_blob_file(&descriptor_for_refresh_harness()) + .await?; + file.read_range(0..1).await?; + Ok(()) + } + + #[tokio::test] + async fn direct_blob_file_refreshes_before_advertised_expiry() { + let now = unix_now_secs(); + let harness = refresh_harness(Some(now + 10), Some(now + 3600), SNAPSHOT_A, None, false); + read_one_byte(&harness).await.unwrap(); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn direct_blob_file_refreshes_when_provider_expiry_precedes_url_ttl() { + let now = unix_now_secs(); + let harness = refresh_harness(Some(now + 3600), Some(now + 3600), SNAPSHOT_A, None, false); + read_one_byte(&harness).await.unwrap(); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn direct_blob_file_refresh_is_single_shot() { + let now = unix_now_secs(); + let harness = refresh_harness(Some(now + 3600), Some(now + 3600), SNAPSHOT_A, None, true); + let error = read_one_byte(&harness).await.unwrap_err(); + assert!( + error.to_string().contains("expired after refresh"), + "{error}" + ); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn open_blob_file_refresh_preserves_the_resolver_identity() { + let now = unix_now_secs(); + let harness = refresh_harness(Some(now + 3600), Some(now + 3600), SNAPSHOT_B, None, false); + let error = read_one_byte(&harness).await.unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn open_blob_file_refresh_propagates_auth_rejection() { + let now = unix_now_secs(); + let harness = refresh_harness( + Some(now + 3600), + Some(now + 3600), + SNAPSHOT_A, + Some(StatusCode::FORBIDDEN), + false, + ); + let error = read_one_byte(&harness).await.unwrap_err(); + assert!(error.to_string().contains("403"), "{error}"); + assert_eq!(harness.resolves.load(Ordering::SeqCst), 2); + assert_eq!(harness.objects.load(Ordering::SeqCst), 1); + } } diff --git a/rust/lancedb/src/remote/table/blobs/aggregate.rs b/rust/lancedb/src/remote/table/blobs/aggregate.rs new file mode 100644 index 000000000..68bc20c88 --- /dev/null +++ b/rust/lancedb/src/remote/table/blobs/aggregate.rs @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Flatten response batches once, releasing each source buffer as it is copied. + +use std::collections::VecDeque; + +use arrow_array::{Array, LargeBinaryArray}; +use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer}; +use arrow_schema::ArrowError; + +fn allocation_error(error: impl std::fmt::Display) -> ArrowError { + ArrowError::ComputeError(format!("cannot allocate blob result: {error}")) +} + +pub(super) struct BlobAccumulator { + offsets: Vec, + validity: Vec, + values: VecDeque, + bytes: i64, + has_nulls: bool, +} + +impl BlobAccumulator { + pub(super) fn new(rows: usize) -> Result { + let capacity = rows + .checked_add(1) + .ok_or_else(|| allocation_error("row count overflow"))?; + let mut offsets = Vec::new(); + offsets + .try_reserve_exact(capacity) + .map_err(allocation_error)?; + offsets.push(0); + let mut validity = Vec::new(); + let validity_bytes = rows / 8 + usize::from(!rows.is_multiple_of(8)); + validity + .try_reserve_exact(validity_bytes) + .map_err(allocation_error)?; + Ok(Self { + offsets, + validity, + values: VecDeque::new(), + bytes: 0, + has_nulls: false, + }) + } + + pub(super) fn append(&mut self, array: &LargeBinaryArray) -> Result<(), ArrowError> { + self.append_inner(array, false) + } + + /// The first value continues the preceding response's final logical range. + pub(super) fn append_continuation( + &mut self, + array: &LargeBinaryArray, + ) -> Result<(), ArrowError> { + self.append_inner(array, true) + } + + fn append_inner( + &mut self, + array: &LargeBinaryArray, + continuation: bool, + ) -> Result<(), ArrowError> { + let rows = self.offsets.len() - 1; + if continuation + && (rows == 0 + || array.is_empty() + || (self.validity[(rows - 1) / 8] & (1 << ((rows - 1) % 8)) != 0) + != array.is_valid(0)) + { + return Err(ArrowError::ComputeError( + "inconsistent nulls in split blob range".into(), + )); + } + let offsets = array.value_offsets(); + let start = offsets[0]; + let length = offsets[array.len()] - start; + let total = self.bytes.checked_add(length).ok_or_else(|| { + ArrowError::ComputeError("blob result exceeds i64 byte offsets".into()) + })?; + let skip = usize::from(continuation); + self.offsets + .try_reserve(array.len() - skip) + .map_err(allocation_error)?; + let new_rows = rows + .checked_add(array.len() - skip) + .ok_or_else(|| allocation_error("row count overflow"))?; + let validity_bytes = new_rows / 8 + usize::from(new_rows % 8 != 0); + self.validity + .try_reserve(validity_bytes - self.validity.len()) + .map_err(allocation_error)?; + self.validity.resize(validity_bytes, 0); + if length != 0 { + self.values.try_reserve(1).map_err(allocation_error)?; + self.values.push_back( + array + .values() + .slice_with_length(start as usize, length as usize), + ); + } + if continuation { + *self.offsets.last_mut().unwrap() = self.bytes + (offsets[1] - start); + } + self.offsets.extend( + offsets[1 + skip..] + .iter() + .map(|offset| self.bytes + (*offset - start)), + ); + for i in skip..array.len() { + let row = rows + i - skip; + if array.is_valid(i) { + self.validity[row / 8] |= 1 << (row % 8); + } else { + self.has_nulls = true; + } + } + self.bytes = total; + Ok(()) + } + + pub(super) fn finish(mut self) -> Result { + let values = match self.values.len() { + 0 => Buffer::default(), + 1 => self.values.pop_front().unwrap(), + _ => { + let length = usize::try_from(self.bytes).map_err(allocation_error)?; + let mut values = Vec::new(); + values.try_reserve_exact(length).map_err(allocation_error)?; + // Drop each source allocation immediately after copying its bytes. + while let Some(chunk) = self.values.pop_front() { + values.extend_from_slice(&chunk); + } + Buffer::from_vec(values) + } + }; + let rows = self.offsets.len() - 1; + let nulls = self + .has_nulls + .then(|| NullBuffer::new(BooleanBuffer::new(Buffer::from_vec(self.validity), 0, rows))); + Ok(LargeBinaryArray::new( + OffsetBuffer::new(self.offsets.into()), + values, + nulls, + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_buffer_is_not_copied() { + let array = LargeBinaryArray::from(vec![Some(b"alpha".as_slice()), None, Some(b"")]); + let mut result = BlobAccumulator::new(3).unwrap(); + result.append(&array).unwrap(); + let output = result.finish().unwrap(); + assert_eq!(output.values().as_ptr(), array.values().as_ptr()); + assert_eq!(output, array); + } + + #[test] + fn slices_batches_nulls_and_empty_values_keep_order() { + let array = LargeBinaryArray::from(vec![ + Some(b"unused".as_slice()), + Some(b"alpha"), + None, + Some(b""), + Some(b"beta"), + ]); + let mut result = BlobAccumulator::new(6).unwrap(); + result.append(&array.slice(1, 3)).unwrap(); + result.append(&array.slice(4, 1)).unwrap(); + result.append(&array.slice(2, 2)).unwrap(); + assert_eq!( + result.finish().unwrap(), + LargeBinaryArray::from(vec![ + Some(b"alpha".as_slice()), + None, + Some(b""), + Some(b"beta"), + None, + Some(b"") + ]) + ); + assert_eq!(BlobAccumulator::new(0).unwrap().finish().unwrap().len(), 0); + } + + #[test] + fn impossible_capacity_is_an_error() { + assert!(BlobAccumulator::new(usize::MAX).is_err()); + assert!(BlobAccumulator::new(usize::MAX / 2).is_err()); + } +} diff --git a/rust/lancedb/src/remote/table/cleanup.rs b/rust/lancedb/src/remote/table/cleanup.rs new file mode 100644 index 000000000..f8d4535d3 --- /dev/null +++ b/rust/lancedb/src/remote/table/cleanup.rs @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! SQL VACUUM submission; never replay an ambiguous acceptance response. + +use crate::{Error, Result, table::CleanupOptions}; +use arrow_array::{Array, RecordBatch, StringArray}; + +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &CleanupOptions, +) -> Result { + let mut settings = Vec::new(); + if let Some(branch) = branch { + if branch.trim().is_empty() { + return Err(Error::InvalidInput { + message: "cleanup branch must not be empty".into(), + }); + } + settings.push(format!("branch = {}", super::quote_sql_string(branch))); + } + if let Some(age) = options.min_age_seconds { + if i64::try_from(age) + .ok() + .and_then(chrono::Duration::try_seconds) + .and_then(|duration| chrono::Utc::now().checked_sub_signed(duration)) + .is_none() + { + return Err(Error::InvalidInput { + message: "min_age_seconds is out of range".into(), + }); + } + settings.push(format!("min_age_seconds = {age}")); + } + let mut sql = format!("VACUUM {}", super::quote_sql_identifier(table)); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + Ok(sql) +} + +pub(super) fn plan(batches: &[RecordBatch]) -> Result { + let invalid = || { + Error::Runtime { message: "EXPLAIN VACUUM did not return a valid versioned preview; a compatible EXPLAIN (FORMAT JSON) VACUUM server is required. No execution fallback was attempted".into() } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let kind = batch + .column_by_name("plan_type") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + let payload = batch + .column_by_name("plan") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if kind.is_null(0) || kind.value(0) != "logical_plan" || payload.is_null(0) { + return Err(invalid()); + } + serde_json::from_str(payload.value(0)).map_err(|_| invalid()) +} + +pub(super) fn map_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<&Error> { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let message = message.to_ascii_lowercase(); + (*grpc_code == tonic::Code::Unimplemented as i32 + || (*grpc_code == tonic::Code::Internal as i32 + && message.contains("invalid explain format") + && message.contains("json")) + || (*grpc_code == tonic::Code::InvalidArgument as i32 + && (message.contains("parsererror") + || message.contains("unknown vacuum option") + || message.contains("vacuum is not supported by this deployment")))) + .then_some(error) + } + Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported), + _ => None, + } + } + if let Some(source) = unsupported(&error) { + let diagnostic = if matches!(error, Error::Sql { .. }) { + error.to_string() + } else { + format!("{error}; {source}") + }; + Error::NotSupported { + message: format!( + "Manual cleanup requires a compatible SQL VACUUM server; upgrade the server. No options were removed and no REST fallback was attempted. Server diagnostic: {diagnostic}" + ), + } + } else { + error + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[test] + fn wrapped_cleanup_compatibility_keeps_job_and_request_identity() { + let sql = Error::Sql { + message: "ParserError: found VACUUM".into(), + request_id: "cleanup-request".into(), + grpc_code: tonic::Code::InvalidArgument as i32, + metadata: Default::default(), + }; + let error = Error::JobFailed { + job_id: Some("query-job".into()), + failure: Box::new(crate::error::JobFailure { + phase: Some("planning".into()), + message: Some("statement failed".into()), + source: Some(Arc::new(sql)), + ..Default::default() + }), + }; + let mapped = map_error(error); + assert!(matches!(mapped, Error::NotSupported { .. })); + let diagnostic = mapped.to_string(); + assert!(diagnostic.contains("query-job")); + assert!(diagnostic.contains("cleanup-request")); + } + + #[test] + fn cleanup_statement_preserves_inheritance_zero_and_quoting() { + assert_eq!( + statement("events", None, &CleanupOptions::new()).unwrap(), + "VACUUM \"events\"" + ); + assert_eq!( + statement( + "a\"b", + Some("o'brien"), + &CleanupOptions::new().min_age_seconds(0) + ) + .unwrap(), + "VACUUM \"a\"\"b\" WITH (branch = 'o''brien', min_age_seconds = 0)" + ); + assert!(statement("t", None, &CleanupOptions::new().min_age_seconds(u64::MAX)).is_err()); + } + + #[test] + fn cleanup_compatibility_preserves_permissions_and_transport_errors() { + for (code, diagnostic, expected) in [ + ( + tonic::Code::InvalidArgument, + "ParserError: found VACUUM", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown VACUUM option future", + true, + ), + (tonic::Code::PermissionDenied, "ParserError: denied", false), + (tonic::Code::Unavailable, "transport unavailable", false), + ( + tonic::Code::InvalidArgument, + "min_age_seconds is out of range", + false, + ), + ] { + let error = Error::Sql { + message: diagnostic.into(), + request_id: "cleanup-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }; + let mapped = map_error(error); + assert_eq!(matches!(mapped, Error::NotSupported { .. }), expected); + assert!(mapped.to_string().contains("cleanup-request")); + } + } +} diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index ebae823e1..f091a0bb1 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -17,7 +17,7 @@ use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, }; -use futures::{SinkExt, StreamExt}; +use futures::StreamExt; use http::header::CONTENT_TYPE; use lance::io::exec::utils::InstrumentedRecordBatchStreamAdapter; @@ -268,6 +268,17 @@ impl RemoteWriteExec { error_tx: tokio::sync::oneshot::Sender, tracker: Option>, ) -> DataFusionResult { + let data: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new( + data.schema(), + data.flat_map(|batch| match batch { + Ok(batch) => futures::stream::iter( + crate::remote::util::split_batch(batch, crate::remote::util::IPC_BATCH_BYTES) + .map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }), + )); let options = arrow_ipc::writer::IpcWriteOptions::default() .try_with_compression(Some(CompressionType::LZ4_FRAME))?; let writer = arrow_ipc::writer::StreamWriter::try_new_with_options( @@ -347,55 +358,55 @@ impl PartRequestCtx<'_, S> { /// whenever the current one reaches `max_bytes` (Arrow IPC, compressed) or /// has been uploading for `max_duration`, whichever comes first. /// - /// Each part is a separate `/insert?upload_id=...&upload_part_id=...` request - /// whose body is still streamed through a bounded channel, so peak memory - /// stays at a couple of batches regardless of `max_bytes`. The server stages - /// every part under the shared `upload_id` and merges them atomically when - /// the caller completes the multipart write. An empty partition stages - /// nothing: the multipart write always has at least one non-empty partition - /// to commit. + /// Each part has a fixed IPC body and transaction ID. A retry replaces the + /// same staged transaction instead of adding another part. Only the final + /// complete request makes staged rows visible. Parts are prepared on demand; + /// the target does not bound memory retained by input or ancestor buffers. /// - /// The byte budget targets a good on-disk fragment size; the duration budget - /// bounds request time so a slow or throttled upload does not keep a request - /// open past the client read timeout (which also covers the request body). + /// The duration budget limits payload preparation time; HTTP timeouts are + /// handled by retrying the prepared payload. async fn send_multipart_chunked( &self, max_bytes: u64, max_duration: Option, - mut input: SendableRecordBatchStream, + input: SendableRecordBatchStream, tracker: Option>, ) -> DataFusionResult<()> { let schema = input.schema(); + let max_batch_bytes = (max_bytes as usize).clamp(1, crate::remote::util::IPC_BATCH_BYTES); + let stream = input.flat_map(move |batch| match batch { + Ok(batch) => futures::stream::iter( + crate::remote::util::split_batch(batch, max_batch_bytes) + .map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }); + let mut input: SendableRecordBatchStream = + Box::pin(RecordBatchStreamAdapter::new(schema.clone(), stream)); - // A part always starts from a batch we already hold: the first batch of - // the partition, or the look-ahead batch from the previous part. This - // keeps empty partitions from staging a part and stops a size cut that - // lands exactly on the end of input from emitting a trailing empty part. - let mut first = match input.next().await { - Some(batch) => batch?, - None => return Ok(()), - }; - + let mut pending = std::collections::VecDeque::new(); loop { - let input_ended = self + let first = match pending.pop_front() { + Some(batch) => batch, + None => match input.next().await { + Some(batch) => batch?, + None => break, + }, + }; + if self .send_one_part( - &schema, max_bytes, max_duration, first, &mut input, + &mut pending, &tracker, ) - .await?; - - if input_ended { + .await? + { break; } - - first = match input.next().await { - Some(batch) => batch?, - None => break, - }; } Ok(()) @@ -431,143 +442,139 @@ impl PartRequestCtx<'_, S> { &self, request: reqwest::RequestBuilder, freshness_request: Option, - ) -> DataFusionResult<()> { - let (request_id, response) = self - .client - .send(request) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; + ) -> crate::Result<()> { + let (request_id, response) = self.client.send(request).await?; let response = RemoteTable::::handle_table_not_found(self.table_name, response, &request_id) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let response = self - .client - .check_response(&request_id, response) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; + .await?; + let response = self.client.check_response(&request_id, response).await?; self.freshness .observe(freshness_request, response.headers()); - response.bytes().await.map_err(|e| { - DataFusionError::External(Box::new(Error::Http { - source: Box::new(e), - request_id: request_id.clone(), - status_code: None, - })) + response.bytes().await.map_err(|e| Error::Http { + source: Box::new(e), + request_id: request_id.clone(), + status_code: None, })?; Ok(()) } - /// Stream one part, starting from `first` and pulling from `input` until the - /// part reaches `max_bytes`, has been uploading for `max_duration`, or the - /// input ends. The body is streamed through a bounded channel concurrently - /// with the request, so peak memory stays at a couple of batches. Wire bytes - /// are recorded on `tracker` as each chunk is produced, so progress advances - /// smoothly rather than jumping once per completed part. Returns whether the - /// input was exhausted while filling this part. + /// Encode each part before sending so a lost staging response can be retried + /// with exactly the same transaction ID and bytes. async fn send_one_part( &self, - schema: &arrow_schema::SchemaRef, max_bytes: u64, max_duration: Option, first: RecordBatch, input: &mut SendableRecordBatchStream, + queued: &mut std::collections::VecDeque, tracker: &Option>, ) -> DataFusionResult { - let (mut chunk_tx, chunk_rx) = - futures::channel::mpsc::channel::, std::io::Error>>(2); - let body = reqwest::Body::wrap_stream(chunk_rx); - - let part_id = uuid::Uuid::new_v4().to_string(); - let (request, freshness_request) = self.build_part_request(&part_id, body); - - // Measured from just before the request is sent, matching the window the - // client read timeout applies to the upload. + let schema = input.schema(); + let options = arrow_ipc::writer::IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME))?; + let mut writer = arrow_ipc::writer::StreamWriter::try_new_with_options( + Vec::new(), + &schema, + options.clone(), + )?; let started = Instant::now(); - let tracker = tracker.clone(); - // Unlike `stream_as_http_body`, this producer also cuts the part at the - // byte/time budget and reports back whether the input ended, so it drives - // its own bounded mpsc channel joined with the request instead of reusing - // that helper. - let producer = async move { - let options = arrow_ipc::writer::IpcWriteOptions::default() - .try_with_compression(Some(CompressionType::LZ4_FRAME)) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let mut writer = - arrow_ipc::writer::StreamWriter::try_new_with_options(Vec::new(), schema, options) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - - let mut part_bytes: u64 = 0; - let mut input_ended = false; - let mut pending = Some(first); - loop { - let batch = match pending.take() { - Some(batch) => batch, - None => match input.next().await { - Some(Ok(batch)) => batch, - Some(Err(e)) => { - // Abort the body so the server does not treat the - // truncated stream as a successful write; the - // original error is surfaced to the caller. - let _ = chunk_tx - .send(Err(std::io::Error::other("input stream error"))) - .await; - return Err(e); - } - None => { - input_ended = true; - break; - } - }, - }; - writer - .write(&batch) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let chunk = std::mem::take(writer.get_mut()); - let chunk_len = chunk.len(); - part_bytes += chunk_len as u64; - if chunk_tx.send(Ok(chunk)).await.is_err() { - // The request finished or failed; stop producing. + let mut pending = Some(first); + let mut has_batch = false; + let mut part_rows = 0; + let mut input_ended = false; + loop { + let batch = match pending.take().or_else(|| queued.pop_front()) { + Some(batch) => batch, + None => match input.next().await { + Some(batch) => batch?, + None => { + input_ended = true; + break; + } + }, + }; + let before = writer.get_ref().len(); + writer.write(&batch)?; + // Reserve the EOS marker. A rejected batch starts a fresh stream, + // so its dictionary messages are encoded again with fresh state. + if (writer.get_ref().len() as u64).saturating_add(8) > max_bytes { + if has_batch { + writer.get_mut().truncate(before); + queued.push_front(batch); break; } - if let Some(ref t) = tracker { - t.record_bytes(chunk_len); - } - if part_bytes >= max_bytes - || max_duration.is_some_and(|limit| started.elapsed() >= limit) - { - break; + if batch.num_rows() > 1 { + let middle = batch.num_rows() / 2; + queued.push_front(crate::remote::util::compact_batch_dictionaries( + batch.slice(middle, batch.num_rows() - middle), + )?); + pending = Some(crate::remote::util::compact_batch_dictionaries( + batch.slice(0, middle), + )?); + writer = arrow_ipc::writer::StreamWriter::try_new_with_options( + Vec::new(), + &schema, + options.clone(), + )?; + continue; } + // A single row and its schema cannot be split further. } - - writer - .finish() - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let tail = std::mem::take(writer.get_mut()); - if !tail.is_empty() { - let tail_len = tail.len(); - if chunk_tx.send(Ok(tail)).await.is_ok() - && let Some(ref t) = tracker - { - t.record_bytes(tail_len); - } + has_batch = true; + part_rows += batch.num_rows(); + if writer.get_ref().len() as u64 >= max_bytes + || max_duration.is_some_and(|limit| started.elapsed() >= limit) + { + break; } - Ok::(input_ended) - }; + } + writer.finish()?; + let body = bytes::Bytes::from(writer.into_inner()?); + let part_id = uuid::Uuid::new_v4().to_string(); + let mut retries = + crate::remote::retry::RetryCounter::new(&self.client.retry_config, part_id.clone()); + loop { + let (request, freshness) = self.build_part_request(&part_id, body.clone().into()); + match self.send_part_request(request, freshness).await { + Ok(()) => { + if let Some(tracker) = tracker { + tracker.record_acknowledged_part(part_rows, body.len()); + } + return Ok(input_ended); + } + Err(err) if retryable_part_error(&err, &self.client.retry_config.statuses) => { + let cause = err.to_string(); + retries + .increment_from_error(err) + .map_err(|err| DataFusionError::External(Box::new(err)))?; + log::warn!( + "Retrying multipart upload {} part {} after {}; reusing the same payload", + self.upload_id, + part_id, + cause + ); + tokio::time::sleep(retries.next_sleep_time()).await; + } + Err(err) => return Err(DataFusionError::External(Box::new(err))), + } + } + } +} - let send = self.send_part_request(request, freshness_request); - - // `join!` rather than `tokio::spawn`: the producer borrows `input` (and - // `schema`), so it cannot satisfy the `'static` bound a spawned task - // needs. Running both futures on this task lets them make progress - // concurrently without that constraint. - let (producer_result, send_result) = futures::join!(producer, send); - // Prefer the producer error (e.g. NaN rejection) over any HTTP error it - // induced. - let input_ended = producer_result?; - send_result?; - - Ok(input_ended) +fn retryable_part_error(err: &Error, statuses: &[reqwest::StatusCode]) -> bool { + match err { + Error::Http { + status_code: Some(status), + .. + } => statuses.contains(status), + Error::Http { source, .. } => source.downcast_ref::().is_some_and(|err| { + err.is_connect() + || err.is_timeout() + || err.is_body() + || err.is_decode() + || err.is_request() + }), + _ => false, } } @@ -697,13 +704,10 @@ impl ExecutionPlan for RemoteWriteExec { let max_request_duration = self.max_request_duration; let stream = futures::stream::once(async move { - // Multipart writes with a byte budget split the partition into - // several bounded, still-streamed requests so no single request - // stays open long enough to hit the client read timeout. This path - // is insert-only (guarded above). - if let (Some(upload_id), Some(max_bytes)) = - (upload_id.as_deref(), max_bytes_per_request) - { + // Multipart payloads remain replayable even when byte-based cuts + // are disabled. Single-request writes never replay ambiguous errors. + if let Some(upload_id) = upload_id.as_deref() { + let max_bytes = max_bytes_per_request.unwrap_or(u64::MAX); let overwrite = matches!(op, WriteOp::Insert { overwrite: true }); let ctx = PartRequestCtx { client: &client, @@ -1220,7 +1224,7 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - // A 1-byte budget forces every batch into its own part. + // A 1-byte budget forces every row into its own part. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1237,7 +1241,103 @@ mod tests { let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); while stream.next().await.transpose().unwrap().is_some() {} - assert_eq!(insert_count.load(Ordering::SeqCst), 3); + assert_eq!(insert_count.load(Ordering::SeqCst), 6); + } + + #[tokio::test] + async fn test_multipart_respects_disabled_status_retries() { + use futures::StreamExt; + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let mut client = crate::remote::client::test_utils::client_with_handler(move |_| { + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(503) + .body("unavailable") + .unwrap() + }); + client.retry_config.statuses.clear(); + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let input = input_plan_from_batches(batch.schema(), vec![batch]).await; + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(64 * 1024 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + assert!(stream.next().await.unwrap().is_err()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_multipart_splits_one_batch_within_encoded_byte_budget() { + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + let mut bytes = vec![0; 128 * 1024]; + SmallRng::seed_from_u64(7).fill_bytes(&mut bytes); + let values = + arrow_array::LargeBinaryArray::from_iter_values(bytes.as_chunks::<1024>().0.iter()); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + false, + )])); + let input = input_plan_from_batches( + schema.clone(), + vec![arrow_array::RecordBatch::try_new(schema, vec![Arc::new(values)]).unwrap()], + ) + .await; + let decoded = Arc::new(Mutex::new(Vec::new())); + let observed = decoded.clone(); + let requests = Arc::new(AtomicUsize::new(0)); + let count = requests.clone(); + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + assert!( + body.len() <= 16 * 1024, + "encoded part exceeded its budget: {}", + body.len() + ); + let reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + let mut decoded = observed.lock().unwrap(); + for batch in reader { + let batch = batch.unwrap(); + let values = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + for value in values.iter() { + decoded.extend_from_slice(value.unwrap()); + } + } + count.fetch_add(1, Ordering::SeqCst); + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert!(requests.load(Ordering::SeqCst) > 1); + assert_eq!(*decoded.lock().unwrap(), bytes); } #[tokio::test] @@ -1376,7 +1476,7 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - // A 1-byte budget forces every batch into its own part. + // A 1-byte budget forces every row into its own part. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1394,13 +1494,13 @@ mod tests { while stream.next().await.transpose().unwrap().is_some() {} let ids = part_ids.lock().unwrap().clone(); - assert_eq!(ids.len(), 3, "expected one part id per part: {ids:?}"); + assert_eq!(ids.len(), 6, "expected one part id per part: {ids:?}"); assert!( ids.iter().all(|id| !id.is_empty()), "part ids must be non-empty: {ids:?}" ); let unique: HashSet<&String> = ids.iter().collect(); - assert_eq!(unique.len(), 3, "part ids must be distinct: {ids:?}"); + assert_eq!(unique.len(), 6, "part ids must be distinct: {ids:?}"); } #[tokio::test] @@ -1446,8 +1546,8 @@ mod tests { while stream.next().await.transpose().unwrap().is_some() {} } - // 2 parts from partition 0 + 1 part from partition 1. - assert_eq!(insert_count.load(Ordering::SeqCst), 3); + // 4 single-row parts from partition 0 + 2 from partition 1. + assert_eq!(insert_count.load(Ordering::SeqCst), 6); } #[tokio::test] @@ -1551,7 +1651,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_records_progress_within_a_part() { + async fn test_multipart_records_acknowledged_rows_and_bytes() { use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; use futures::StreamExt; @@ -1570,16 +1670,18 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - let observed = Arc::new(Mutex::new(Vec::::new())); + let observed = Arc::new(Mutex::new(Vec::<(usize, usize)>::new())); let observed_cb = observed.clone(); let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { - observed_cb.lock().unwrap().push(p.output_bytes()); + observed_cb + .lock() + .unwrap() + .push((p.output_rows(), p.output_bytes())); })); let tracker = Arc::new(WriteProgressTracker::new(callback, None)); - // A large byte budget keeps all three batches in one part; smooth - // progress therefore requires bytes to be reported per chunk rather than - // once when the part completes. + tracker.use_acknowledged_parts(); + // Count rows from all encoded batches once when the part is acknowledged. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1602,17 +1704,469 @@ mod tests { "batches should all land in a single part" ); let observed = observed.lock().unwrap(); + assert_eq!(observed.last().unwrap().0, 6); assert!( - observed.len() > 1, - "expected multiple incremental progress updates within the part: {observed:?}" + observed.len() == 1, + "expected one progress update per acknowledged part: {observed:?}" ); assert!( observed.windows(2).all(|w| w[1] >= w[0]), "progress bytes should be monotonic: {observed:?}" ); assert!( - *observed.last().unwrap() > 0, + observed.last().unwrap().1 > 0, "final progress should report bytes: {observed:?}" ); } + #[tokio::test] + async fn test_multipart_nested_dictionary_values_and_retries() { + use arrow_array::{ + Array, ArrayRef, BinaryArray, DictionaryArray, ListArray, RecordBatch, StructArray, + UInt8Array, types::UInt8Type, + }; + use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; + use arrow_cast::cast; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + use std::collections::HashMap; + + let mut bytes = vec![0; 128 * 1024]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let mut batches = Vec::new(); + for shift in [0, 1] { + let values = BinaryArray::from_iter( + std::iter::once(None) + .chain(bytes.as_chunks::<1024>().0.iter().skip(shift).map(Some)), + ); + let keys = UInt8Array::from(vec![ + Some(120), + Some(1), + None, + Some(1), + Some(2), + Some(0), + Some(3), + Some(4), + ]); + let dict = Arc::new(DictionaryArray::::new(keys, Arc::new(values))); + let field = Arc::new( + Field::new("category", dict.data_type().clone(), true) + .with_metadata(HashMap::from([("field-meta".into(), "retained".into())])), + ); + let entries = StructArray::new(vec![field].into(), vec![dict], None); + let list = ListArray::new( + Arc::new(Field::new_list_field(entries.data_type().clone(), false)), + OffsetBuffer::new(ScalarBuffer::from(vec![0, 1, 3, 5, 6, 6, 8])), + Arc::new(entries), + Some(NullBuffer::from(vec![true, true, true, true, false, true])), + ); + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![Field::new("categories", list.data_type().clone(), true)], + HashMap::from([("schema-meta".into(), "retained".into())]), + )); + // The discarded first row references a large, otherwise unused value. + batches.push( + RecordBatch::try_new(schema, vec![Arc::new(list)]) + .unwrap() + .slice(1, 5), + ); + } + let schema = batches[0].schema(); + let plain_type = DataType::List(Arc::new(Field::new_list_field( + DataType::Struct( + vec![ + Field::new("category", DataType::Binary, true) + .with_metadata(HashMap::from([("field-meta".into(), "retained".into())])), + ] + .into(), + ), + false, + ))); + let expected: Vec = batches + .iter() + .map(|b| cast(b.column(0), &plain_type).unwrap()) + .collect(); + let expected = + arrow_select::concat::concat(&expected.iter().map(|a| a.as_ref()).collect::>()) + .unwrap(); + let input = input_plan_from_batches(schema.clone(), batches).await; + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = requests.clone(); + let mut client = crate::remote::client::test_utils::client_with_handler(move |request| { + let query: HashMap<_, _> = request.url().query_pairs().into_owned().collect(); + assert_eq!(query["upload_id"], "upload-1"); + let body = request.body().unwrap().as_bytes().unwrap().to_vec(); + let mut requests = observed.lock().unwrap(); + requests.push((query["upload_part_id"].clone(), body)); + http::Response::builder() + .status(if requests.len() == 1 { 503 } else { 200 }) + .body("{}") + .unwrap() + }); + client.retry_config.backoff_factor = 0.0; + client.retry_config.backoff_jitter = 0.0; + use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; + let acknowledged = Arc::new(AtomicUsize::new(0)); + let acknowledged_c = acknowledged.clone(); + let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { + acknowledged_c.store(p.output_bytes(), Ordering::SeqCst); + })); + let tracker = Arc::new(WriteProgressTracker::new(callback, None)); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + Some(tracker), + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + let requests = requests.lock().unwrap(); + assert!(requests.len() >= 2); + assert_eq!( + requests[0], requests[1], + "retry must reuse part id and encoded bytes" + ); + let mut decoded = Vec::new(); + for (_, body) in &requests[1..] { + assert!(body.len() <= 16 * 1024, "part size: {}", body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + for batch in reader { + decoded.push(cast(batch.unwrap().column(0), &plain_type).unwrap()); + } + } + let actual = + arrow_select::concat::concat(&decoded.iter().map(|a| a.as_ref()).collect::>()) + .unwrap(); + assert_eq!(actual.as_ref(), expected.as_ref()); + let total: usize = requests[1..].iter().map(|(_, b)| b.len()).sum(); + assert_eq!(acknowledged.load(Ordering::SeqCst), total); + assert!( + total < 16 * 1024, + "unused dictionary values leaked: {total}" + ); + } + + #[rstest::rstest] + #[case(false, "linear", 1024)] + #[case(true, "linear", 1024)] + #[case(false, "linear", 1000)] + #[case(true, "linear", 1000)] + #[case(false, "nested", 1024)] + #[case(true, "nested", 1024)] + #[case(false, "sharing", 1024)] + #[case(true, "sharing", 1024)] + #[case(false, "empty", 1024)] + #[case(true, "empty", 1024)] + #[tokio::test] + async fn test_multipart_list_view_dictionary_ranges( + #[case] large: bool, + #[case] layout: &str, + #[case] value_bytes: usize, + ) { + if large { + check_list_view_dictionary_ranges::(layout, value_bytes).await; + } else { + check_list_view_dictionary_ranges::(layout, value_bytes).await; + } + } + + async fn check_list_view_dictionary_ranges( + layout: &str, + value_bytes: usize, + ) { + use arrow_array::{ + Array, ArrayRef, DictionaryArray, GenericListViewArray, Int32Array, ListArray, + RecordBatch, StringArray, StructArray, cast::AsArray, types::Int32Type, + }; + use arrow_buffer::{NullBuffer, OffsetBuffer}; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + use std::collections::HashMap; + + let mut bytes = vec![0; 128 * value_bytes]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(value_bytes) + .map(|c| c.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let mut expected = Vec::new(); + let mut batches = Vec::new(); + let nested = layout != "linear"; + for reverse in [false, true] + .into_iter() + .take(if layout == "nested" { 2 } else { 1 }) + { + let values: Vec<_> = if reverse { + strings.iter().rev().cloned().collect() + } else { + strings.clone() + }; + let keys: Vec = (0..128) + .map(|i| if layout == "sharing" { i % 2 } else { i }) + .collect(); + // A sliced child has its own nonzero physical offset. + let dict = DictionaryArray::::new( + Int32Array::from_iter_values(std::iter::once(127).chain(keys.iter().copied())), + Arc::new(StringArray::from(values.clone())), + ) + .slice(1, 128); + let mut offsets = Vec::new(); + let mut sizes = Vec::new(); + let mut valid = Vec::new(); + let start = usize::from(layout == "nested"); + for row in 0..128 + start { + let (offset, size, is_valid) = match layout { + "empty" if row % 2 == 0 => (80, 48, false), + "empty" => (128, 0, true), + "nested" if row % 17 == 0 => (80, 48, false), + "nested" if row % 13 == 0 => (128, 0, true), + "nested" => (4 + (row * 7) % 64, 3, true), + "sharing" => (4 + (row % 2) * 4, 64, true), + _ => (row, 1, true), + }; + offsets.push(O::from_usize(offset).unwrap()); + sizes.push(O::from_usize(size).unwrap()); + valid.push(is_valid); + if row >= start { + expected.push(is_valid.then(|| { + (offset..offset + size) + .map(|i| values[keys[i] as usize].clone()) + .collect::>() + })); + } + } + let item = Arc::new( + Field::new("category", dict.data_type().clone(), false) + .with_metadata(HashMap::from([("item-meta".into(), "retained".into())])), + ); + let views = GenericListViewArray::::new( + item, + offsets.into(), + sizes.into(), + Arc::new(dict), + Some(NullBuffer::from(valid)), + ); + let view_count = views.len(); + let column: ArrayRef = if nested { + let field = Arc::new(Field::new("views", views.data_type().clone(), true)); + let entries = StructArray::new(vec![field].into(), vec![Arc::new(views)], None); + Arc::new(ListArray::new( + Arc::new(Field::new_list_field(entries.data_type().clone(), false)), + OffsetBuffer::from_lengths(std::iter::repeat_n(1, view_count)), + Arc::new(entries), + None, + )) + } else { + Arc::new(views) + }; + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![Field::new("categories", column.data_type().clone(), true)], + HashMap::from([("schema-meta".into(), "retained".into())]), + )); + batches.push( + RecordBatch::try_new(schema, vec![column]) + .unwrap() + .slice(start, 128), + ); + } + let schema = batches[0].schema(); + let logical_bytes: usize = expected.iter().flatten().flatten().map(String::len).sum(); + let input = input_plan_from_batches(schema.clone(), batches).await; + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let decoded = Arc::new(Mutex::new(Vec::new())); + let decoded_c = decoded.clone(); + let sharing = layout == "sharing"; + let empty = layout == "empty"; + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + observed.lock().unwrap().push(body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + for batch in reader { + let batch = batch.unwrap(); + for row in 0..batch.num_rows() { + let column = if nested { + batch + .column(0) + .as_list::() + .value(row) + .as_struct() + .column(0) + .slice(0, 1) + } else { + batch.column(0).slice(row, 1) + }; + let views = column + .as_any() + .downcast_ref::>() + .unwrap(); + if empty { + assert_eq!(views.values().len(), 0, "null/empty views retain no child"); + } + if sharing { + assert_eq!( + views.values().len(), + 68, + "overlapping ranges must share their child" + ); + } + decoded_c.lock().unwrap().push(if views.is_null(0) { + None + } else { + let value = arrow_cast::cast(&views.value(0), &DataType::Utf8).unwrap(); + Some( + value + .as_string::() + .iter() + .map(|v| v.unwrap().to_owned()) + .collect::>(), + ) + }); + } + } + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert_eq!(*decoded.lock().unwrap(), expected); + let lengths = lengths.lock().unwrap(); + let total: usize = lengths.iter().sum(); + eprintln!( + "ListView IPC: large={}, layout={layout}, value_bytes={value_bytes}, parts={}, first={}, total={total}", + O::IS_LARGE, + lengths.len(), + lengths[0] + ); + // Every selected row in these cases fits the target, including IPC framing. + assert!( + lengths.iter().all(|n| *n <= 16 * 1024), + "oversized parts: {lengths:?}" + ); + assert!( + total <= (2 * logical_bytes).max(16 * 1024), + "dictionary upload amplified: {total}" + ); + if sharing { + assert_eq!(lengths.len(), 1); + } + } + + #[rstest::rstest] + #[case(1024, false)] + // Dictionary data fits the target; IPC framing forces the sender to split again. + #[case(1000, false)] + #[case(1024, true)] + #[case(20 * 1024, false)] + #[tokio::test] + async fn test_multipart_dictionary_payload_is_not_repeated_per_row( + #[case] value_bytes: usize, + #[case] use_views: bool, + ) { + use arrow_array::{ + Array, ArrayRef, DictionaryArray, Int32Array, RecordBatch, StringArray, + StringViewArray, types::Int32Type, + }; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + + let mut bytes = vec![0; 128 * value_bytes]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(value_bytes) + .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let values: ArrayRef = if use_views { + Arc::new(StringViewArray::from_iter_values(&strings)) + } else { + Arc::new(StringArray::from(strings.clone())) + }; + let array = + DictionaryArray::::try_new(Int32Array::from_iter_values(0..128), values) + .unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "category", + array.data_type().clone(), + false, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap(); + let input = input_plan_from_batches(schema.clone(), vec![batch]).await; + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let decoded = Arc::new(Mutex::new(Vec::new())); + let decoded_c = decoded.clone(); + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + observed.lock().unwrap().push(body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + let mut rows = 0; + for batch in reader { + let batch = batch.unwrap(); + rows += batch.num_rows(); + let values = arrow_cast::cast(batch.column(0), &DataType::Utf8).unwrap(); + let values = values.as_any().downcast_ref::().unwrap(); + decoded_c + .lock() + .unwrap() + .extend(values.iter().map(|v| v.unwrap().to_owned())); + } + assert!( + body.len() <= 16 * 1024 || rows == 1, + "oversized divisible part: {} bytes, {rows} rows", + body.len() + ); + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert_eq!(*decoded.lock().unwrap(), strings); + let lengths = lengths.lock().unwrap(); + let total: usize = lengths.iter().sum(); + eprintln!( + "dictionary IPC: value_bytes={value_bytes}, views={use_views}, parts={}, first={}, total={total}", + lengths.len(), + lengths[0] + ); + assert!( + total <= 2 * bytes.len(), + "dictionary upload amplified: parts={}, first={}, total={total}", + lengths.len(), + lengths[0] + ); + } } diff --git a/rust/lancedb/src/remote/table/ipc_stream.rs b/rust/lancedb/src/remote/table/ipc_stream.rs new file mode 100644 index 000000000..08b3b1dea --- /dev/null +++ b/rust/lancedb/src/remote/table/ipc_stream.rs @@ -0,0 +1,836 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Incremental decoding of response bodies that use Arrow IPC stream framing. + +mod framing; + +use framing::{FramingError, IpcFraming}; + +use arrow_array::RecordBatch; +use arrow_buffer::Buffer; +use arrow_ipc::reader::StreamDecoder; +use bytes::Bytes; +use datafusion_common::DataFusionError; +use datafusion_physical_plan::SendableRecordBatchStream; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use futures::{Stream, StreamExt, TryStreamExt}; + +use crate::error::{BoxError, Error, Result}; + +/// Decode an Arrow IPC stream from a response body as its chunks arrive. +/// +/// Only the current chunk and the decoder's state are held, so memory is bounded +/// by the size of a batch rather than the size of the result. This waits for the +/// first batch, or for the end of an empty result, so a body that fails before +/// any data arrives fails the request itself. +/// +/// A complete body ends with the end-of-stream marker; the server aborts the body +/// without it when the query fails after sending headers. A body that ends early, +/// even between messages, is reported as [`Error::ResponseInterrupted`] and never +/// as a short result. +pub(super) async fn read_ipc_stream( + chunks: impl Stream> + Send + 'static, + request_id: String, + table_version: Option, +) -> Result +where + E: Into + 'static, +{ + let mut body = IpcStreamBody { + framing: IpcFraming::new(chunks.map_err(Into::into).boxed()), + chunk: Buffer::default(), + decoder: StreamDecoder::new(), + finished: false, + request_id, + table_version, + batches: 0, + rows: 0, + }; + let first = body.next_batch().await?; + // The schema is the first message, so only a body holding nothing but the + // end-of-stream marker can complete without one. + let schema = body.decoder.schema().ok_or_else(|| Error::Http { + source: "Arrow IPC stream ended without a schema".into(), + request_id: body.request_id.clone(), + status_code: None, + })?; + let rest = futures::stream::try_unfold(body, |mut body| async move { + Ok(body.next_batch().await?.map(|batch| (batch, body))) + }); + let batches = futures::stream::iter(first.map(Ok)) + .chain(rest) + .map_err(|error: Error| DataFusionError::External(Box::new(error))); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, batches))) +} + +struct IpcStreamBody { + framing: IpcFraming, + /// The part of the current chunk that has not been decoded yet. + chunk: Buffer, + decoder: StreamDecoder, + /// Set once the body has ended with the end-of-stream marker. + finished: bool, + request_id: String, + table_version: Option, + batches: u64, + rows: u64, +} + +impl IpcStreamBody { + /// Decode until the next batch is complete. Returns `None` once the body + /// has ended with the end-of-stream marker. + async fn next_batch(&mut self) -> Result> { + while !self.finished { + if self.chunk.is_empty() { + match self.framing.next_buffer().await { + Ok(Some(chunk)) => self.chunk = chunk, + Err(FramingError::Interrupted(error)) => return Err(self.interrupted(error)), + Err(FramingError::Arrow(error)) => return Err(error.into()), + Ok(None) if read_end_of_stream(&mut self.decoder) => self.finished = true, + Ok(None) => { + return Err(self.interrupted( + "the response ended before the Arrow end-of-stream marker".into(), + )); + } + } + continue; + } + // Decoding stops after each batch, keeping the rest of the chunk. + if let Some(batch) = self.decoder.decode(&mut self.chunk)? { + self.batches += 1; + self.rows += batch.num_rows() as u64; + return Ok(Some(batch)); + } + } + Ok(None) + } + + fn interrupted(&self, source: BoxError) -> Error { + Error::ResponseInterrupted { + request_id: self.request_id.clone(), + batches: self.batches, + rows: self.rows, + table_version: self.table_version, + source: source.into(), + } + } +} + +/// Whether the decoder has read the end-of-stream marker. +/// +/// [`StreamDecoder::finish`] also accepts input that stops between messages, +/// because the Arrow format lets a writer end a stream by closing it. A decoder +/// that has read the marker rejects any further input, which is the only way +/// its API tells the two apart. +fn read_end_of_stream(decoder: &mut StreamDecoder) -> bool { + decoder.finish().is_ok() && decoder.decode(&mut Buffer::from_slice_ref([0u8])).is_err() +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use arrow_array::builder::StringDictionaryBuilder; + use arrow_array::types::Int8Type; + use arrow_array::{ArrayRef, Int32Array, StringArray}; + use arrow_ipc::CompressionType; + use arrow_ipc::writer::{DictionaryHandling, FileWriter, IpcWriteOptions, StreamWriter}; + use arrow_schema::{DataType, Field, Schema, SchemaRef}; + use lance::arrow::json::JsonSchema; + use rstest::rstest; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + use tokio::sync::mpsc; + + use super::*; + use crate::query::{ExecutableQuery, QueryExecutionOptions}; + use crate::remote::client::{ClientConfig, RetryConfig}; + use crate::remote::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE}; + use crate::{Table, connect}; + + /// Three batches of two rows under a schema with metadata. The second batch's + /// dictionary extends the first one's, which writers can send as a delta, and + /// the third replaces it. + fn batches() -> Vec { + let schema = Arc::new(Schema::new_with_metadata( + vec![ + Field::new("id", DataType::Int32, false), + Field::new_dictionary("label", DataType::Int8, DataType::Utf8, false), + ], + HashMap::from([("origin".to_string(), "test".to_string())]), + )); + let labels: [(&[&str], [&str; 2]); 3] = [ + (&["a", "b"], ["a", "b"]), + (&["a", "b", "c"], ["c", "a"]), + (&["d"], ["d", "d"]), + ]; + labels + .into_iter() + .enumerate() + .map(|(i, (dictionary, values))| { + let dictionary = StringArray::from(dictionary.to_vec()); + let mut label = + StringDictionaryBuilder::::new_with_dictionary(2, &dictionary) + .unwrap(); + values + .into_iter() + .for_each(|value| label.append_value(value)); + let id = Int32Array::from(vec![2 * i as i32, 2 * i as i32 + 1]); + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(id) as ArrayRef, Arc::new(label.finish())], + ) + .unwrap() + }) + .collect() + } + + /// An IPC stream cut where the server cuts it: after the schema, after each + /// batch with its dictionaries, and after the end-of-stream marker. + fn messages( + schema: &Schema, + batches: &[RecordBatch], + options: IpcWriteOptions, + ) -> Vec> { + let mut writer = StreamWriter::try_new_with_options(Vec::new(), schema, options).unwrap(); + let mut messages = vec![std::mem::take(writer.get_mut())]; + for batch in batches { + writer.write(batch).unwrap(); + messages.push(std::mem::take(writer.get_mut())); + } + writer.finish().unwrap(); + messages.push(std::mem::take(writer.get_mut())); + messages + } + + fn chunks(body: &[u8], size: usize) -> Vec> { + body.chunks(size) + .map(|chunk| Ok(Bytes::copy_from_slice(chunk))) + .collect() + } + + #[tokio::test] + async fn impossible_ipc_body_lengths_return_errors() { + let batches = batches(); + let messages = messages(&batches[0].schema(), &batches, IpcWriteOptions::default()); + for length in [-1, i64::MAX - 31, i64::MAX] { + let mut message = messages[1].clone(); + let metadata_len = u32::from_le_bytes(message[4..8].try_into().unwrap()) as usize; + let metadata = arrow_ipc::root_as_message(&message[8..8 + metadata_len]).unwrap(); + let field = metadata + ._tab + .vtable() + .get(arrow_ipc::Message::VT_BODYLENGTH); + assert_ne!(field, 0, "fixture must contain a body length field"); + let offset = 8 + metadata._tab.loc() + field as usize; + message[offset..offset + 8].copy_from_slice(&length.to_le_bytes()); + // A valid schema and message metadata followed by just one body byte. + message.truncate(8 + metadata_len + 1); + let (_, returned, error) = read(vec![ + Ok(Bytes::copy_from_slice(&messages[0])), + Ok(Bytes::from(message)), + ]) + .await; + assert!(returned.is_empty()); + let error = error.unwrap().to_string(); + assert!( + error.contains("body length") || error.contains("cannot allocate IPC message"), + "unexpected error for length {length}: {error}" + ); + } + } + + /// The schema, the batches yielded, and the error that ended the stream. + async fn read( + chunks: Vec>, + ) -> (Option, Vec, Option) { + let stream = + match read_ipc_stream(futures::stream::iter(chunks), "request".into(), Some(7)).await { + Ok(stream) => stream, + Err(error) => return (None, vec![], Some(error)), + }; + let schema = stream.schema(); + let results = stream.collect::>().await; + let (batches, errors): (Vec<_>, Vec<_>) = results.into_iter().partition(|r| r.is_ok()); + assert!(errors.len() <= 1, "the stream ends at its first error"); + let error = errors + .into_iter() + .next() + .map(|e| Error::from(e.unwrap_err())); + let batches = batches.into_iter().map(|r| r.unwrap()).collect(); + (Some(schema), batches, error) + } + + fn assert_interrupted(error: Option, expected_batches: u64, expected_rows: u64) { + match error { + Some(Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + .. + }) => { + assert_eq!(request_id, "request"); + assert_eq!((batches, rows), (expected_batches, expected_rows)); + assert_eq!(table_version, Some(7)); + } + other => panic!("expected an interrupted response, got {other:?}"), + } + } + + // One-byte chunks split every message; a single chunk holds them all. + #[rstest] + #[case(1)] + #[case(7)] + #[case(usize::MAX)] + #[tokio::test] + async fn decodes_any_chunking(#[case] chunk_size: usize) { + let input = batches(); + let body = messages(&input[0].schema(), &input, IpcWriteOptions::default()).concat(); + + let (schema, output, error) = read(chunks(&body, chunk_size)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(schema.unwrap(), input[0].schema()); + assert_eq!(output, input); + } + + #[rstest] + #[case(IpcWriteOptions::default().with_dictionary_handling(DictionaryHandling::Delta))] + #[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::LZ4_FRAME)).unwrap())] + #[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::ZSTD)).unwrap())] + #[tokio::test] + async fn decodes_dictionary_deltas_and_compressed_batches(#[case] options: IpcWriteOptions) { + let input = batches(); + let body = messages(&input[0].schema(), &input, options).concat(); + + let (_, output, error) = read(chunks(&body, 5)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, input); + } + + #[tokio::test] + async fn fragmented_body_keeps_only_its_declared_allocation() { + use arrow_array::LargeBinaryArray; + + let bytes = vec![42; 3 * 1024 * 1024 + 13]; + let array = LargeBinaryArray::from(vec![bytes.as_slice()]); + let batch = RecordBatch::try_from_iter([("blob", Arc::new(array) as ArrayRef)]).unwrap(); + let body = messages( + &batch.schema(), + std::slice::from_ref(&batch), + IpcWriteOptions::default(), + ) + .concat(); + let (_, output, error) = read(chunks(&body, 8191)).await; + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, [batch]); + let blobs = output[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!( + blobs.values().capacity() <= bytes.len() + 256, + "IPC body retained {} bytes for {} value bytes", + blobs.values().capacity(), + bytes.len() + ); + } + + #[rstest] + #[case(false)] + #[case(true)] + #[tokio::test] + async fn zero_body_batches_and_legacy_prefixes(#[case] legacy: bool) { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let input = [vec![], vec![1, 2], vec![]] + .into_iter() + .map(|values| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(values))]) + .unwrap() + }) + .collect::>(); + let options = IpcWriteOptions::try_new(8, legacy, arrow_ipc::MetadataVersion::V4).unwrap(); + let body = messages(&schema, &input, options).concat(); + let (_, output, error) = read(chunks(&body, 1)).await; + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, input); + } + + #[tokio::test] + async fn partial_next_prefix_still_delivers_a_zero_body_batch() { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let empty = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(Vec::::new()))], + ) + .unwrap(); + let nonempty = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1]))]) + .unwrap(); + let messages = messages( + &schema, + &[empty.clone(), nonempty], + IpcWriteOptions::default(), + ); + let cutoff = messages[..2].concat().len() + 1; + let body = messages.concat(); + let (_, output, error) = read(chunks(&body[..cutoff], 1)).await; + assert_eq!(output, [empty]); + assert_interrupted(error, 1, 0); + } + + /// The server answers an empty result with the schema and the end-of-stream marker. + #[tokio::test] + async fn empty_result_keeps_its_schema() { + let schema = batches()[0].schema(); + let body = messages(&schema, &[], IpcWriteOptions::default()).concat(); + + let (decoded, output, error) = read(chunks(&body, 3)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(decoded.unwrap(), schema); + assert!(output.is_empty()); + } + + #[tokio::test] + async fn body_ending_without_end_of_stream_is_interrupted() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + let complete = messages[..messages.len() - 1].concat(); + let after_first_batch = messages[..2].concat().len(); + // Where the body stops, and how many batches it holds by then. + for (end, delivered) in [ + (complete.len(), 3), // between messages, after the last batch + (complete.len() - 3, 2), // inside the last batch + (after_first_batch, 1), // between messages + (messages[0].len(), 0), // after the schema + (messages[0].len() / 2, 0), // inside the schema + (0, 0), // an empty body + ] { + let (_, output, error) = read(chunks(&complete[..end], 4)).await; + assert_eq!(output, input[..delivered], "body cut at {end}"); + assert_interrupted(error, delivered as u64, 2 * delivered as u64); + } + } + + #[tokio::test] + async fn body_error_is_interrupted() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + let mut body = chunks(&messages[..2].concat(), usize::MAX); + body.push(Err(std::io::Error::other("connection reset"))); + + let (_, output, error) = read(body).await; + + assert_eq!(output, input[..1]); + let message = error.as_ref().map(ToString::to_string).unwrap_or_default(); + assert!(message.contains("connection reset"), "{message}"); + assert_interrupted(error, 1, 2); + } + + #[tokio::test] + async fn malformed_body_is_an_arrow_error() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + // A message whose metadata is not a flatbuffer. + let garbage = [&[0xff; 4][..], &8u32.to_le_bytes(), &[0xab; 8]].concat(); + // Anything after the end-of-stream marker. + let trailing = [messages.concat(), vec![0]].concat(); + for body in [[messages[0].clone(), garbage].concat(), trailing] { + let (_, _, error) = read(chunks(&body, usize::MAX)).await; + assert!(matches!(error, Some(Error::Arrow { .. })), "{error:?}"); + } + } + + /// What the test server does next for a query request. + enum Reply { + /// A complete response with this status and an empty body. + Status(u16), + /// Headers of a chunked body with this content type. + Head(Option<&'static str>), + Chunk(Vec), + /// The last chunk, ending the body cleanly. + End, + /// Close the connection in the middle of the body. + Abort, + } + + struct Server { + table: Table, + replies: mpsc::UnboundedSender, + /// Headers of each query request received. + queries: Arc>>>, + } + + impl Server { + fn reply(&self, replies: impl IntoIterator) { + replies + .into_iter() + .for_each(|reply| self.replies.send(reply).unwrap()); + } + } + + /// Serve table `t` over HTTP. Query requests are answered, in order, by the + /// replies the test sends. + async fn serve() -> Server { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (replies, mut pending) = mpsc::unbounded_channel(); + let queries = Arc::new(Mutex::new(Vec::new())); + let received = queries.clone(); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let (path, headers) = read_request(&mut socket).await; + if path.ends_with("/describe/") { + let schema = Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "vector", + DataType::new_fixed_size_list(DataType::Float32, 2, true), + false, + ), + ]); + let body = serde_json::json!({ + "version": 7, + "schema": JsonSchema::try_from(&schema).unwrap(), + }) + .to_string(); + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + socket.write_all(response.as_bytes()).await.unwrap(); + continue; + } + received.lock().unwrap().push(headers); + while let Some(reply) = pending.recv().await { + let last = !matches!(reply, Reply::Head(_) | Reply::Chunk(_)); + let bytes = match reply { + Reply::Status(status) => format!( + "HTTP/1.1 {status} Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .into_bytes(), + Reply::Head(content_type) => format!( + "HTTP/1.1 200 OK\r\n{}Transfer-Encoding: chunked\r\n\ + x-lancedb-version: 7\r\nConnection: close\r\n\r\n", + content_type + .map(|value| format!("Content-Type: {value}\r\n")) + .unwrap_or_default() + ) + .into_bytes(), + Reply::Chunk(chunk) => { + [format!("{:x}\r\n", chunk.len()).into_bytes(), chunk, b"\r\n".into()] + .concat() + } + Reply::End => b"0\r\n\r\n".to_vec(), + Reply::Abort => break, + }; + // The client may have stopped reading. + if socket.write_all(&bytes).await.is_err() || last { + break; + } + } + } + }); + let db = connect("db://test") + .api_key("key") + .region("us-east-1") + .host_override(&format!("http://{address}")) + .client_config(ClientConfig { + retry_config: RetryConfig { + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let table = db.open_table("t").execute().await.unwrap(); + Server { + table, + replies, + queries, + } + } + + async fn read_request(socket: &mut TcpStream) -> (String, HashMap) { + let mut request = Vec::new(); + let mut buf = [0; 4096]; + let head_end = loop { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request head"); + request.extend_from_slice(&buf[..n]); + if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") { + break end + 4; + } + }; + let head = String::from_utf8(request[..head_end].to_vec()).unwrap(); + let mut lines = head.lines(); + let path = lines.next().unwrap().split(' ').nth(1).unwrap().to_string(); + let headers: HashMap<_, _> = lines + .filter_map(|line| line.split_once(':')) + .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string())) + .collect(); + let length: usize = headers + .get("content-length") + .map_or(0, |length| length.parse().unwrap()); + while request.len() < head_end + length { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request body"); + request.extend_from_slice(&buf[..n]); + } + (path, headers) + } + + /// The query batches as the server sends them: `id` only. + fn id_messages() -> Vec> { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batches: Vec<_> = (0..3) + .map(|i| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![i]))]) + .unwrap() + }) + .collect(); + messages(&schema, &batches, IpcWriteOptions::default()) + } + + fn ids(batch: &RecordBatch) -> Vec { + batch["id"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + } + + #[tokio::test] + async fn first_batch_arrives_before_the_rest_of_the_body() { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + ]); + + // The server sends the rest only after the first batch has been read. + let (results, first) = tokio::time::timeout(Duration::from_secs(10), async { + let mut results = server.table.query().execute().await.unwrap(); + let first = results.next().await.unwrap().unwrap(); + (results, first) + }) + .await + .expect("the first batch must not wait for the whole body"); + assert_eq!(ids(&first), [0]); + server.reply([Reply::Chunk(messages[2..].concat()), Reply::End]); + let rest = results.try_collect::>().await.unwrap(); + assert_eq!(rest.iter().flat_map(ids).collect::>(), [1, 2]); + + let queries = server.queries.lock().unwrap(); + assert_eq!(queries.len(), 1); + assert_eq!(queries[0]["accept"], super::super::QUERY_ACCEPT); + } + + /// A server abort, and a proxy that turns it into a clean end of the body, + /// both fail the query after the batches already read. Neither is retried. + #[rstest] + #[case::abort(Reply::Abort, true)] + #[case::clean_end(Reply::End, false)] + #[tokio::test] + async fn interrupted_body_is_typed_and_not_retried( + #[case] end: Reply, + #[case] transport_error: bool, + ) { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + end, + ]); + + let mut results = server.table.query().execute().await.unwrap(); + assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]); + let error = results.next().await.unwrap().unwrap_err(); + assert!(results.next().await.is_none()); + + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("expected an interrupted response, got {error:?}"); + }; + assert!(!request_id.is_empty()); + assert_eq!((batches, rows, table_version), (1, 1, Some(7))); + assert_eq!(source.is::(), transport_error, "{source}"); + assert_eq!(server.queries.lock().unwrap().len(), 1); + } + + /// Vector queries run through a DataFusion plan, which must keep the error's type. + #[tokio::test] + async fn vector_query_keeps_the_interruption_type() { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + + let results = server + .table + .query() + .nearest_to(&[0.0f32, 0.0]) + .unwrap() + .execute() + .await + .unwrap(); + let error = results.try_collect::>().await.unwrap_err(); + + assert!( + matches!(error, Error::ResponseInterrupted { batches: 1, .. }), + "{error:?}" + ); + } + + /// A server without multi-vector support gets a request per vector, and the + /// plan merging the responses shares an error between its partitions. + #[tokio::test] + async fn multi_vector_query_keeps_the_interruption() { + let server = serve().await; + let messages = id_messages(); + // Which vector gets which response does not matter. + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages.concat()), + Reply::End, + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + + let results = server + .table + .query() + .nearest_to(&[0.0f32, 0.0]) + .unwrap() + .add_query_vector(&[1.0f32, 1.0]) + .unwrap() + .execute() + .await + .unwrap(); + let error = results.try_collect::>().await.unwrap_err(); + + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("expected an interrupted response, got {error:?}"); + }; + assert!(!request_id.is_empty()); + assert_eq!((batches, rows, table_version), (1, 1, Some(7))); + assert!(source.is::(), "{source}"); + assert_eq!(server.queries.lock().unwrap().len(), 2); + } + + #[tokio::test] + async fn timeout_covers_reading_the_body() { + let server = serve().await; + let messages = id_messages(); + // The body stalls after the first batch. + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + ]); + + let options = QueryExecutionOptions { + timeout: Some(Duration::from_millis(500)), + ..Default::default() + }; + let mut results = server + .table + .query() + .execute_with_options(options) + .await + .unwrap(); + assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]); + let error = tokio::time::timeout(Duration::from_secs(10), results.next()) + .await + .expect("the timeout must end a stalled body") + .unwrap() + .unwrap_err(); + + assert!( + !matches!(error, Error::ResponseInterrupted { .. }), + "{error:?}" + ); + assert!( + error.to_string().contains("Query timeout after 500 ms"), + "{error}" + ); + assert_eq!( + server.queries.lock().unwrap()[0]["x-request-timeout-ms"], + "500" + ); + } + + /// Servers that do not stream query results answer with file framing, or + /// with no content type at all. + #[rstest] + #[case(Some(ARROW_FILE_CONTENT_TYPE))] + #[case(None)] + #[tokio::test] + async fn file_framing_is_still_read(#[case] content_type: Option<&'static str>) { + let server = serve().await; + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![4, 5]))]) + .unwrap(); + let mut writer = FileWriter::try_new(Vec::new(), &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + server.reply([ + Reply::Head(content_type), + Reply::Chunk(writer.into_inner().unwrap()), + Reply::End, + ]); + + let results = server.table.query().execute().await.unwrap(); + let output = results.try_collect::>().await.unwrap(); + + assert_eq!(output, [batch]); + } + + #[tokio::test] + async fn failure_before_headers_is_retried() { + let server = serve().await; + server.reply([ + Reply::Status(503), + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(id_messages().concat()), + Reply::End, + ]); + + let results = server.table.query().execute().await.unwrap(); + let output = results.try_collect::>().await.unwrap(); + + assert_eq!(output.iter().flat_map(ids).collect::>(), [0, 1, 2]); + assert_eq!(server.queries.lock().unwrap().len(), 2); + } +} diff --git a/rust/lancedb/src/remote/table/ipc_stream/framing.rs b/rust/lancedb/src/remote/table/ipc_stream/framing.rs new file mode 100644 index 000000000..da20c8e99 --- /dev/null +++ b/rust/lancedb/src/remote/table/ipc_stream/framing.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Frame IPC bodies before decoding, avoiding StreamDecoder's growing scratch buffer. + +use arrow_buffer::Buffer; +use arrow_schema::ArrowError; +use bytes::Bytes; +use futures::StreamExt; +use futures::stream::BoxStream; + +use crate::error::BoxError; + +pub(super) enum FramingError { + Interrupted(BoxError), + Arrow(ArrowError), +} + +#[derive(Clone, Copy)] +enum Frame { + Header { + bytes: [u8; 4], + read: usize, + continuation: bool, + }, + Metadata(usize), + Body(usize), + End, +} + +impl Default for Frame { + fn default() -> Self { + Self::Header { + bytes: [0; 4], + read: 0, + continuation: false, + } + } +} + +pub(super) struct IpcFraming { + chunks: BoxStream<'static, Result>, + chunk: Buffer, + frame: Frame, +} + +impl IpcFraming { + pub(super) fn new(chunks: BoxStream<'static, Result>) -> Self { + Self { + chunks, + chunk: Buffer::default(), + frame: Frame::default(), + } + } + + pub(super) async fn next_buffer(&mut self) -> Result, FramingError> { + let buffer = match self.frame { + Frame::Header { + mut bytes, + mut read, + continuation, + } => { + // Forward even a partial prefix immediately. StreamDecoder may + // need that byte to yield the preceding zero-body record batch. + self.fill_chunk().await?; + let take = self.chunk.len().min(4 - read); + let buffer = self.chunk.slice_with_length(0, take); + self.chunk.advance(take); + bytes[read..read + take].copy_from_slice(&buffer); + read += take; + self.frame = if read == 4 { + match u32::from_le_bytes(bytes) { + u32::MAX if !continuation => Frame::Header { + bytes: [0; 4], + read: 0, + continuation: true, + }, + 0 => Frame::End, + length => Frame::Metadata(length as usize), + } + } else { + Frame::Header { + bytes, + read, + continuation, + } + }; + buffer + } + Frame::Metadata(length) => { + let metadata = self.read_exact(length).await?; + let message = arrow_ipc::root_as_message(&metadata).map_err(|error| { + FramingError::Arrow(ArrowError::IpcError(format!( + "Invalid IPC message: {error}" + ))) + })?; + let length = usize::try_from(message.bodyLength()).map_err(|_| { + FramingError::Arrow(ArrowError::IpcError( + "IPC message body length is negative or exceeds addressable memory".into(), + )) + })?; + self.frame = if length == 0 { + Frame::default() + } else { + Frame::Body(length) + }; + metadata + } + Frame::Body(length) => { + let body = self.read_exact(length).await?; + self.frame = Frame::default(); + body + } + Frame::End => { + // Forward trailing bytes to the decoder so it rejects data after EOS. + if !self.chunk.is_empty() { + return Ok(Some(std::mem::take(&mut self.chunk))); + } + return self + .chunks + .next() + .await + .transpose() + .map(|chunk| chunk.map(Buffer::from)) + .map_err(FramingError::Interrupted); + } + }; + Ok(Some(buffer)) + } + + async fn read_exact(&mut self, length: usize) -> Result { + self.fill_chunk().await?; + if self.chunk.len() >= length { + let buffer = self.chunk.slice_with_length(0, length); + self.chunk.advance(length); + return Ok(buffer); + } + // The declared length is untrusted. Arrow's infallible aligned allocator + // can panic on its layout or abort on OOM; Vec exposes both as errors. + // StreamDecoder handles any array-specific alignment when decoding. + let mut buffer = Vec::new(); + buffer.try_reserve_exact(length).map_err(|error| { + FramingError::Arrow(ArrowError::IpcError(format!( + "cannot allocate IPC message of {length} bytes: {error}" + ))) + })?; + while buffer.len() < length { + self.fill_chunk().await?; + let take = self.chunk.len().min(length - buffer.len()); + buffer.extend_from_slice(&self.chunk[..take]); + self.chunk.advance(take); + } + Ok(Buffer::from_vec(buffer)) + } + + async fn fill_chunk(&mut self) -> Result<(), FramingError> { + while self.chunk.is_empty() { + self.chunk = self + .chunks + .next() + .await + .ok_or_else(|| { + FramingError::Interrupted( + "the response ended before the Arrow end-of-stream marker".into(), + ) + })? + .map_err(FramingError::Interrupted)? + .into(); + } + Ok(()) + } +} diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs new file mode 100644 index 000000000..e3b1a612c --- /dev/null +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Compaction options supported by the remote SQL submission protocol. +use crate::error::{Error, Result}; + +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &crate::table::optimize::CompactionOverrides, +) -> Result { + let mut settings = compaction_sql_options(options)?; + if let Some(branch) = branch { + settings.insert(0, format!("branch = {}", super::quote_sql_string(branch))); + } + let mut sql = format!( + "OPTIMIZE {} REWRITE DATA", + super::quote_sql_identifier(table) + ); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + Ok(sql) +} + +pub(super) fn compaction_sql_options( + options: &crate::table::optimize::CompactionOverrides, +) -> Result> { + for (name, value) in [ + ("target_rows_per_fragment", options.target_rows_per_fragment), + ("max_source_rows", options.max_source_rows), + ("batch_size", options.batch_size), + ] { + if value == Some(0) { + return Err(Error::InvalidInput { + message: format!("{name} must be greater than 0"), + }); + } + } + let mut result = Vec::new(); + for (name, value) in [ + ( + "target_rows_per_fragment", + options.target_rows_per_fragment.map(|v| v as u64), + ), + ("max_source_rows", options.max_source_rows.map(|v| v as u64)), + ("io_buffer_size", options.io_buffer_size), + ("batch_size", options.batch_size.map(|v| v as u64)), + ] { + if let Some(value) = value { + result.push(format!("{name} = {value}")); + } + } + Ok(result) +} + +const UNSUPPORTED_OPTIMIZE: &str = "Compaction on an Enterprise table requires support for OPTIMIZE
      REWRITE DATA. Upgrade LanceDB Enterprise to a compatible release."; +const UNSUPPORTED_OPTIONS: &str = "The requested compaction options are not supported by this version of LanceDB Enterprise. Upgrade to a compatible release; requested options will not be removed or retried."; + +/// The client generates the whole statement, so parser errors indicate a +/// client/server syntax mismatch. Match option errors without enumerating names. +fn unsupported_optimize_message(message: &str) -> Option<&'static str> { + let message = message.to_ascii_lowercase(); + if message.contains("parsererror") { + Some(UNSUPPORTED_OPTIMIZE) + } else if message.contains("unknown optimize option") { + Some(UNSUPPORTED_OPTIONS) + } else { + None + } +} + +/// Apply compatibility handling only to this constructed operation. +/// Preserve every unrelated SQL/authentication/transport error unchanged. +pub(super) fn map_optimize_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<(&Error, &'static str)> { + match error { + Error::Sql { + message, grpc_code, .. + } if *grpc_code == tonic::Code::InvalidArgument as i32 => { + unsupported_optimize_message(message).map(|reason| (error, reason)) + } + Error::JobFailed { failure, .. } => failure + .source + .as_deref() + .and_then(|source| unsupported(source)), + _ => None, + } + } + if let Some((source, reason)) = unsupported(&error) { + let diagnostic = match &error { + Error::Sql { .. } => error.to_string(), + // JobFailure's Display omits its source, including the SQL request ID. + _ => format!("{error}; {source}"), + }; + Error::NotSupported { + message: format!("{reason} Server diagnostic: {diagnostic}"), + } + } else { + error + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::JobFailure; + use crate::table::{CompactionOptions, CompactionOverrides}; + use std::sync::Arc; + + fn sql_error(code: tonic::Code, message: &str) -> Error { + Error::Sql { + message: message.into(), + request_id: "optimize-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + } + } + + #[test] + fn direct_optimize_error_prints_its_diagnostic_once() { + let diagnostic = "ParserError: Expected: end of statement, found: REWRITE"; + let Error::NotSupported { message } = + map_optimize_error(sql_error(tonic::Code::InvalidArgument, diagnostic)) + else { + panic!("known optimize syntax must be unsupported"); + }; + assert_eq!(message.matches(diagnostic).count(), 1); + assert_eq!(message.matches("request_id=optimize-request").count(), 1); + } + + #[test] + fn wrapped_optimize_error_keeps_job_context_and_sql_diagnostic() { + let diagnostic = "ParserError: Expected: end of statement, found: REWRITE"; + let error = Error::JobFailed { + job_id: Some("optimize-job".into()), + failure: Box::new(JobFailure { + phase: Some("planning".into()), + message: Some("SQL planning failed".into()), + source: Some(Arc::new(sql_error( + tonic::Code::InvalidArgument, + diagnostic, + ))), + ..Default::default() + }), + }; + let Error::NotSupported { message } = map_optimize_error(error) else { + panic!("wrapped unsupported optimize SQL must be translated"); + }; + assert!(message.contains(UNSUPPORTED_OPTIMIZE)); + assert!(message.contains("optimize-job")); + assert!(message.contains("SQL planning failed (in planning)")); + assert_eq!(message.matches(diagnostic).count(), 1); + assert_eq!(message.matches("request_id=optimize-request").count(), 1); + } + + #[test] + fn unrelated_wrapped_sql_errors_pass_through_unchanged() { + let unsupported = "ParserError: Expected: end of statement, found: REWRITE"; + for (code, diagnostic) in [ + (tonic::Code::PermissionDenied, unsupported), + (tonic::Code::Unavailable, unsupported), + (tonic::Code::InvalidArgument, "invalid table configuration"), + ] { + let source = Arc::new(sql_error(code, diagnostic)); + let error = Error::JobFailed { + job_id: Some("optimize-job".into()), + failure: Box::new(JobFailure { + phase: Some("planning".into()), + message: Some("SQL planning failed".into()), + sql_job_id: Some("sql-job".into()), + retryable: Some(false), + source: Some(source.clone()), + ..Default::default() + }), + }; + let Error::JobFailed { job_id, failure } = map_optimize_error(error) else { + panic!("{code:?}: unrelated SQL failure must keep its classification"); + }; + assert_eq!(job_id.as_deref(), Some("optimize-job")); + assert_eq!(failure.phase.as_deref(), Some("planning")); + assert_eq!(failure.message.as_deref(), Some("SQL planning failed")); + assert_eq!(failure.sql_job_id.as_deref(), Some("sql-job")); + assert_eq!(failure.retryable, Some(false)); + assert!(Arc::ptr_eq(failure.source.as_ref().unwrap(), &source)); + } + } + + #[test] + fn generated_optimize_syntax_errors_indicate_incompatible_servers() { + for diagnostic in [ + "ParserError: Expected: end of statement, found: REWRITE", + "ParserError: Expected: identifier", + "SQL error: ParserError: future grammar diagnostic", + "parsererror: lowercase diagnostic", + ] { + assert_eq!( + unsupported_optimize_message(diagnostic), + Some(UNSUPPORTED_OPTIMIZE) + ); + } + for diagnostic in [ + "Unknown OPTIMIZE option 'io_buffer_size'", + "Error during planning: Unknown OPTIMIZE option 'future_option'", + ] { + assert_eq!( + unsupported_optimize_message(diagnostic), + Some(UNSUPPORTED_OPTIONS) + ); + } + for diagnostic in [ + "permission denied", + "table not found", + "connection reset", + "invalid table configuration", + ] { + assert!( + unsupported_optimize_message(diagnostic).is_none(), + "{diagnostic}" + ); + } + } + + #[test] + fn omissions_and_explicit_default_target_are_distinct() { + assert!( + compaction_sql_options(&CompactionOverrides::default()) + .unwrap() + .is_empty() + ); + let target = CompactionOptions::default().target_rows_per_fragment; + assert_eq!( + compaction_sql_options(&CompactionOverrides { + target_rows_per_fragment: Some(target), + io_buffer_size: Some(0), + ..Default::default() + }) + .unwrap(), + [ + format!("target_rows_per_fragment = {target}"), + "io_buffer_size = 0".into() + ] + ); + } + + #[test] + fn unsupported_settings_are_rejected() { + assert!(matches!( + CompactionOverrides::try_from(CompactionOptions { + max_source_bytes: Some(1024), + ..Default::default() + }), + Err(Error::NotSupported { .. }) + )); + } + + #[test] + fn invalid_row_settings_are_rejected() { + for options in [ + CompactionOverrides { + target_rows_per_fragment: Some(0), + ..Default::default() + }, + CompactionOverrides { + max_source_rows: Some(0), + ..Default::default() + }, + CompactionOverrides { + batch_size: Some(0), + ..Default::default() + }, + ] { + assert!(matches!( + compaction_sql_options(&options), + Err(Error::InvalidInput { .. }) + )); + } + } +} diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs new file mode 100644 index 000000000..09510109e --- /dev/null +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -0,0 +1,363 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! SQL submission and preview decoding for data-cache prewarm jobs. + +use arrow_array::{Array, RecordBatch, StringArray}; +use datafusion_sql::sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Token}; + +use super::{quote_sql_identifier, quote_sql_string}; +use crate::{Error, Result, table::PrewarmDataOptions}; + +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &PrewarmDataOptions, +) -> Result { + let invalid = |message: &str| Error::InvalidInput { + message: message.into(), + }; + if options.concurrency == Some(0) { + return Err(invalid("prewarm concurrency must be greater than 0")); + } + if let Some(parameters) = &options.parameters { + if options.filter.is_none() { + return Err(invalid("prewarm parameters require a filter")); + } + if parameters.num_rows() != 1 { + return Err(invalid("prewarm parameters must contain exactly one row")); + } + } + if let Some(filter) = &options.filter { + if filter.trim().is_empty() { + return Err(invalid("prewarm filter must not be empty")); + } + let dialect = GenericDialect {}; + let mut parser = Parser::new(&dialect) + .try_with_sql(filter) + .map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?; + parser + .parse_expr() + .map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?; + if parser.peek_token().token != Token::EOF { + return Err(invalid("prewarm filter must be a single SQL expression")); + } + } + let mut settings = Vec::new(); + if let Some(branch) = branch { + if branch.trim().is_empty() { + return Err(invalid("prewarm branch must not be empty")); + } + settings.push(format!("branch = {}", quote_sql_string(branch))); + } + if let Some(concurrency) = options.concurrency { + settings.push(format!("concurrency = {concurrency}")); + } + let mut sql = "PREWARM".to_string(); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + let mut columns = Vec::new(); + for column in &options.columns { + let parts = lance::datatypes::parse_field_path(column)?; + let column = parts + .iter() + .map(|part| quote_sql_identifier(part)) + .collect::>() + .join("."); + if !columns.contains(&column) { + columns.push(column); + } + } + let projection = if columns.is_empty() { + "*".into() + } else { + columns.join(", ") + }; + sql.push_str(&format!( + " AS SELECT {projection} FROM {}", + quote_sql_identifier(table) + )); + if let Some(filter) = &options.filter { + sql.push_str(&format!(" WHERE {filter}")); + } + Ok(sql) +} + +/// Decode the versioned JSON payload without depending on the display text. +pub(super) fn plan(batches: &[RecordBatch]) -> Result { + let invalid = || { + Error::Runtime { + message: "EXPLAIN PREWARM did not return a valid structured preview; a server supporting EXPLAIN (FORMAT JSON) PREWARM is required".into(), + } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let payload = batch + .column_by_name("plan") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if payload.is_null(0) { + return Err(invalid()); + } + #[derive(serde::Deserialize)] + struct Preview { + format_version: u32, + #[serde(flatten)] + plan: crate::table::PrewarmDataPlan, + } + let preview: Preview = serde_json::from_str(payload.value(0)).map_err(|_| invalid())?; + if preview.format_version != 1 { + return Err(invalid()); + } + Ok(preview.plan) +} + +pub(super) fn map_explain_error(error: Error) -> Error { + fn unsupported_format(error: &Error) -> bool { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let diagnostic = message.to_ascii_lowercase(); + // Older servers hand this EXPLAIN to DataFusion, which rejects + // JSON as a configuration error (sometimes gRPC Internal). + (*grpc_code == tonic::Code::Internal as i32 + || *grpc_code == tonic::Code::InvalidArgument as i32) + && diagnostic.contains("invalid explain format.") + && diagnostic.contains("got 'json'") + } + Error::JobFailed { failure, .. } => { + failure.source.as_deref().is_some_and(unsupported_format) + } + _ => false, + } + } + let error = if unsupported_format(&error) { + Error::NotSupported { + message: error.to_string(), + } + } else { + map_error(error) + }; + match error { + Error::NotSupported { message } => Error::NotSupported { + message: format!( + "Data prewarm previews require a server supporting EXPLAIN (FORMAT JSON) PREWARM; upgrade the server. Preview will not fall back to text or REST. Server diagnostic: {message}" + ), + }, + other => other, + } +} + +pub(super) fn map_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<&Error> { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let diagnostic = message.to_ascii_lowercase(); + (*grpc_code == tonic::Code::Unimplemented as i32 + || (*grpc_code == tonic::Code::InvalidArgument as i32 + && (diagnostic.contains("found: prewarm") + || diagnostic.contains("supported syntax: prewarm") + || diagnostic.contains("unknown prewarm option")))) + .then_some(error) + } + Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported), + _ => None, + } + } + if let Some(source) = unsupported(&error) { + let diagnostic = if matches!(error, Error::Sql { .. }) { + error.to_string() + } else { + format!("{error}; {source}") + }; + Error::NotSupported { + message: format!( + "Data prewarm requires a compatible SQL PREWARM server; upgrade the server. Requested options will not be removed and submission will not fall back to REST. Server diagnostic: {diagnostic}" + ), + } + } else { + error + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[test] + fn preview_maps_old_explain_format_errors_without_masking_auth_or_filters() { + for (code, message, unsupported) in [ + ( + tonic::Code::Internal, + "Invalid or Unsupported Configuration: Invalid explain format. Expected 'indent', 'tree', 'pgjson' or 'graphviz'. Got 'JSON'", + true, + ), + ( + tonic::Code::InvalidArgument, + "Invalid explain format. Got 'JSON'", + true, + ), + ( + tonic::Code::PermissionDenied, + "Invalid explain format. Got 'JSON'", + false, + ), + ( + tonic::Code::InvalidArgument, + "invalid filter expression", + false, + ), + ] { + let error = map_explain_error(Error::Sql { + message: message.into(), + request_id: "preview-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error}" + ); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("preview-request")); + if unsupported { + assert!(error.to_string().contains("EXPLAIN (FORMAT JSON) PREWARM")); + } + } + } + + #[test] + fn preview_requires_one_versioned_typed_payload() { + let valid = serde_json::json!({ + "format_version": 1, "table_version": 42, "plan": "display only", + "pruning": {"mode":"future_mode", "input_fragments":3, + "selected_fragments":0, "pruned_fragments":3, "selected_row_ranges":0}, + "future_field": true, + }); + let batch = |value: &serde_json::Value| { + RecordBatch::try_from_iter([( + "plan", + Arc::new(StringArray::from(vec![value.to_string()])) as arrow_array::ArrayRef, + )]) + .unwrap() + }; + let result = plan(&[batch(&valid)]).unwrap(); + assert_eq!(result.table_version, 42); + assert_eq!(result.pruning.mode, "future_mode"); + assert_eq!(result.pruning.selected_row_ranges, Some(0)); + assert_eq!(result.pruning.fallback_reason, None); + for mutation in ["version", "missing", "negative", "text"] { + let mut value = valid.clone(); + match mutation { + "version" => value["format_version"] = 2.into(), + "missing" => { + value.as_object_mut().unwrap().remove("pruning"); + } + "negative" => value["pruning"]["selected_fragments"] = (-1).into(), + _ => value = "legacy display text".into(), + } + assert!(plan(&[batch(&value)]).is_err(), "{mutation}"); + } + assert!(plan(&[]).is_err()); + assert!(plan(&[batch(&valid), batch(&valid)]).is_err()); + } + + #[test] + fn bound_values_are_never_rendered_into_sql() { + let value = "training' OR TRUE; DROP TABLE clips; --"; + let parameters = RecordBatch::try_from_iter(vec![( + "tag", + Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let options = PrewarmDataOptions::new() + .filter("tag = $tag") + .parameters(parameters); + let sql = statement("clips", Some("experiment"), &options).unwrap(); + assert!(sql.ends_with("WHERE tag = $tag")); + assert!(!sql.contains(value)); + assert!(!format!("{options:?}").contains(value)); + assert!( + statement( + "clips", + None, + &PrewarmDataOptions::new().parameters(options.parameters.unwrap()) + ) + .is_err() + ); + } + + #[test] + fn quotes_paths_branch_and_filter_without_changing_options() { + let options = PrewarmDataOptions::new() + .columns(["attrs.score", "`caption.text`", "attrs.score"]) + .filter("quality > 0.7 AND caption = 'it''s ready'") + .concurrency(4); + assert_eq!( + statement("clip\"name", Some("o'brien"), &options).unwrap(), + "PREWARM WITH (branch = 'o''brien', concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7 AND caption = 'it''s ready'" + ); + assert_eq!( + statement("clips", None, &Default::default()).unwrap(), + "PREWARM AS SELECT * FROM \"clips\"" + ); + assert!(statement("clips", None, &PrewarmDataOptions::new().filter("-1 < id")).is_ok()); + } + + #[test] + fn rejects_invalid_inputs_before_submission() { + for options in [ + PrewarmDataOptions::new().filter(""), + PrewarmDataOptions::new().filter("id > 0; DROP TABLE clips"), + PrewarmDataOptions::new().filter("id > 0 LIMIT 1"), + PrewarmDataOptions::new().filter("id >"), + PrewarmDataOptions::new().columns(["attrs..score"]), + PrewarmDataOptions::new().concurrency(0), + ] { + assert!(statement("clips", None, &options).is_err(), "{options:?}"); + } + } + + #[test] + fn compatibility_errors_preserve_permission_and_predicate_diagnostics() { + for (code, message, unsupported) in [ + ( + tonic::Code::InvalidArgument, + "ParserError: found: PREWARM", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown PREWARM option 'branch'", + true, + ), + (tonic::Code::PermissionDenied, "permission denied", false), + ( + tonic::Code::InvalidArgument, + "ParserError: expected expression, found unsupported_filter", + false, + ), + ] { + let error = map_error(Error::Sql { + message: message.into(), + request_id: "prewarm-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }); + assert_eq!(matches!(error, Error::NotSupported { .. }), unsupported); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("prewarm-request")); + } + } +} diff --git a/rust/lancedb/src/remote/table/profile_tests.rs b/rust/lancedb/src/remote/table/profile_tests.rs new file mode 100644 index 000000000..ca599402e --- /dev/null +++ b/rust/lancedb/src/remote/table/profile_tests.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::json; + +use super::{FreshnessHeaders, FreshnessState, MaterializedViewRefreshJob}; +use crate::job::{ + FunctionProfileKind, FunctionProfileOptions, FunctionProfileStatus, FunctionProfileWaitOptions, + Job, +}; +use crate::materialized_view::RefreshMaterializedViewResult; +use crate::remote::client::test_utils::client_with_handler; +use crate::remote::job::RemoteJob; + +#[tokio::test] +async fn materialized_view_refresh_handles_forward_profile_operations_without_finishing_refresh() { + let client = client_with_handler(|request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "job-1"); + let action = request.url().path(); + let value = if action == "/v1/jobs/profile/artifact" { + json!({"format":"lancedb.cuda.v1", "traceEvents":[], "truncated":true}) + } else { + assert!(matches!( + action, + "/v1/jobs/profile/capture" | "/v1/jobs/profile/status" + )); + if action.ends_with("/capture") { + assert_eq!(body["worker_id"], "worker-1"); + assert_eq!(body["kind"], "gpu"); + } else { + assert_eq!(body["profile_id"], "profile-1"); + } + json!({ + "profile_id":"profile-1", "job_id":"job-1", "worker_id":"worker-1", + "execution_epoch":1, "session_slot":0, "kind":"gpu", "duration_seconds":2, + "status":if action.ends_with("/capture") { "pending" } else { "complete" }, + "requested_at_millis":1000, "deadline_at_millis":46000, + "expires_at_millis":3601000, "artifact_id":"profile-1" + }) + }; + http::Response::builder() + .status(200) + .body(value.to_string()) + .unwrap() + }); + let freshness = Arc::new(Mutex::new(FreshnessState::default())); + let job: Job = + Job::new_typed(Box::new(MaterializedViewRefreshJob { + inner: RemoteJob::new(client.clone(), "job-1".into()), + client, + db_name: "analytics".into(), + name: "view".into(), + namespace: vec![], + identifier: "view".into(), + server_version: Default::default(), + sql_client: None, + freshness: freshness.clone(), + freshness_request: FreshnessHeaders::default(), + })); + let capture = job + .capture_profile( + "worker-1", + FunctionProfileOptions::new(FunctionProfileKind::Gpu).duration(Duration::from_secs(2)), + ) + .await + .unwrap(); + assert_eq!(capture.status, FunctionProfileStatus::Pending); + assert_eq!( + job.wait_for_profile(&capture.profile_id, FunctionProfileWaitOptions::new()) + .await + .unwrap() + .status, + FunctionProfileStatus::Complete + ); + assert_eq!( + job.profile_artifact(&capture.profile_id).await.unwrap()["truncated"], + true + ); + assert_eq!(job.state(), None); + assert!(freshness.lock().unwrap().checkout_baseline.is_none()); +} diff --git a/rust/lancedb/src/remote/table/receipt.rs b/rust/lancedb/src/remote/table/receipt.rs new file mode 100644 index 000000000..818302cd7 --- /dev/null +++ b/rust/lancedb/src/remote/table/receipt.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{Array, UInt64Array}; +use serde::de::DeserializeOwned; + +use super::{cleanup, optimize, prewarm}; +use crate::job::Job; +use crate::remote::client::{HttpSend, RestfulLanceDbClient}; +use crate::remote::job::RemoteJob; +use crate::remote::sql::receipt::ReceiptRow; +use crate::sql::Query; +use crate::{Error, Result}; + +#[derive(Clone, Copy)] +pub(super) enum JobReceipt { + Compact, + Prewarm, + Cleanup, +} + +impl JobReceipt { + fn invalid(self) -> Error { + let receipt = match self { + Self::Compact => "OPTIMIZE did not return a single nonempty job_id receipt", + Self::Prewarm => "PREWARM did not return a single (job_id, table_version) receipt", + Self::Cleanup => "VACUUM did not return a single nonempty job_id receipt", + }; + Error::Runtime { + message: format!( + "{receipt}; inspect jobs before retrying because work may already have been submitted" + ), + } + } + + /// A registry job can already be running when its SQL response is lost. + /// Only construct the handle after reading one valid row and the end of the stream. + pub(super) async fn accept( + self, + submission: Result, + client: &RestfulLanceDbClient, + ) -> Result> + where + T: Clone + DeserializeOwned + Send + Sync + 'static, + S: HttpSend, + { + let map_error = match self { + Self::Compact => optimize::map_optimize_error, + Self::Prewarm => prewarm::map_error, + Self::Cleanup => cleanup::map_error, + }; + let query = submission.map_err(map_error)?; + let row = ReceiptRow::read(&query) + .await + .map_err(map_error)? + .ok_or_else(|| self.invalid())?; + let Ok(Some(job_id)) = row.job_id() else { + return Err(self.invalid()); + }; + if matches!(self, Self::Prewarm) { + row.column("table_version") + .and_then(|column| column.as_any().downcast_ref::()) + .filter(|versions| !versions.is_null(0)) + .ok_or_else(|| self.invalid())?; + } + Ok(Job::new_typed(Box::new(RemoteJob::new( + client.clone(), + job_id.to_owned(), + )))) + } +} diff --git a/rust/lancedb/src/remote/table/write_tests.rs b/rust/lancedb/src/remote/table/write_tests.rs new file mode 100644 index 000000000..2e0ca1d45 --- /dev/null +++ b/rust/lancedb/src/remote/table/write_tests.rs @@ -0,0 +1,487 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Real HTTP faults with a local Lance table behind the staging fixture. This +//! exercises SDK behavior; it does not model Sophon's asynchronous txn cleanup. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{LargeBinaryArray, RecordBatch}; +use arrow_ipc::reader::StreamReader; +use arrow_schema::{DataType, Field, Schema}; +use lance::arrow::json::JsonSchema; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use super::RemoteTable; +use crate::remote::client::{ClientConfig, RestfulLanceDbClient, RetryConfig, TimeoutConfig}; +use crate::remote::db::ServerVersion; +use crate::table::AddDataBuilder; + +#[derive(Clone, Copy, Debug)] +enum Fault { + Close, + Timeout, + Status(u16), +} + +#[derive(Default)] +struct State { + creates: usize, + completes: usize, + aborts: usize, + attempts: Vec<(String, Vec)>, + parts: HashMap>, +} + +async fn read_request(socket: &mut tokio::net::TcpStream) -> (String, Vec) { + let mut header = Vec::new(); + while !header.ends_with(b"\r\n\r\n") { + header.push(socket.read_u8().await.unwrap()); + assert!(header.len() < 64 * 1024); + } + let header = String::from_utf8(header).unwrap(); + let path = header.split_whitespace().nth(1).unwrap().to_owned(); + let length = header + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().unwrap()) + }) + .unwrap_or(0); + assert!( + !header + .to_ascii_lowercase() + .contains("transfer-encoding: chunked") + ); + let mut body = vec![0; length]; + socket.read_exact(&mut body).await.unwrap(); + (path, body) +} + +async fn respond(socket: &mut tokio::net::TcpStream, status: u16, body: &str) { + let response = format!( + "HTTP/1.1 {status} Result\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; +} + +#[tokio::test] +async fn multipart_http_faults_preserve_committed_blob_payloads() { + for complete_fault in [false, true] { + for fault in [ + Fault::Close, + Fault::Timeout, + Fault::Status(500), + Fault::Status(502), + Fault::Status(503), + Fault::Status(504), + ] { + let dir = tempfile::tempdir().unwrap(); + let db = crate::connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![crate::blob::blob("payload", true)])); + let stored = db + .create_empty_table("stored", schema.clone()) + .execute() + .await + .unwrap(); + let state = Arc::new(Mutex::new(State::default())); + let server_state = state.clone(); + let server_table = stored.clone(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let mut tasks = tokio::task::JoinSet::new(); + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let state = server_state.clone(); + let table = server_table.clone(); + tasks.spawn(async move { + let (path, body) = read_request(&mut socket).await; + let mut apply_fault = false; + let response; + if path.contains("multipart_write/create") { + state.lock().unwrap().creates += 1; + response = r#"{"upload_id":"00000000-0000-0000-0000-000000000001"}"# + .to_string(); + } else if path.contains("/insert/") { + let url = url::Url::parse(&format!("http://localhost{path}")).unwrap(); + let params: HashMap<_, _> = url.query_pairs().into_owned().collect(); + assert_eq!(params["upload_id"], "00000000-0000-0000-0000-000000000001"); + let part = params["upload_part_id"].clone(); + let mut state = state.lock().unwrap(); + apply_fault = !complete_fault && state.attempts.is_empty(); + state.attempts.push((part.clone(), body.clone())); + // Match the verified server contract: replace the txn + // associated with this part ID before acknowledging it. + state.parts.insert(part, body); + response = "{}".into(); + } else if path.contains("multipart_write/complete") { + let parts = { + let mut state = state.lock().unwrap(); + state.completes += 1; + state.parts.values().cloned().collect::>() + }; + for body in parts { + let reader = + StreamReader::try_new(std::io::Cursor::new(body), None) + .unwrap(); + let batches = reader.collect::, _>>().unwrap(); + table.add(batches).execute().await.unwrap(); + } + apply_fault = complete_fault; + response = r#"{"version":2}"#.into(); + } else if path.contains("multipart_write/abort") { + state.lock().unwrap().aborts += 1; + panic!("abort must never follow a possibly committed complete"); + } else { + panic!("unexpected request {path}"); + } + if apply_fault { + match fault { + Fault::Close => return, + Fault::Timeout => { + tokio::time::sleep(Duration::from_secs(2)).await; + return; + } + Fault::Status(status) => { + respond( + &mut socket, + status, + "gateway fault after staging/commit", + ) + .await; + return; + } + } + } + respond(&mut socket, 200, &response).await; + }); + } + }); + let client = RestfulLanceDbClient::try_new( + &crate::remote::client::parse_db_url("db://test").unwrap(), + "us-east-1", + Some(format!("http://{address}")), + Default::default(), + ClientConfig { + timeout_config: TimeoutConfig { + read_timeout: Some(Duration::from_secs(1)), + ..Default::default() + }, + retry_config: RetryConfig { + retries: Some(3), + read_retries: Some(3), + connect_retries: Some(3), + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let remote = Arc::new(RemoteTable::new_with_sql_client( + client, + "test".into(), + "test".into(), + vec![], + "test".into(), + ServerVersion(semver::Version::new(0, 4, 0)), + None, + )); + remote.seed_schema(&serde_json::json!({"version": 1, "schema": JsonSchema::try_from(schema.as_ref()).unwrap()}).to_string()); + let payload_a = vec![17u8; 32 * 1024]; + let payload_b = vec![29u8; 32 * 1024]; + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(LargeBinaryArray::from(vec![ + Some(payload_a.as_slice()), + Some(payload_b.as_slice()), + ]))], + ) + .unwrap(); + let progress = Arc::new(Mutex::new(Vec::new())); + let seen = progress.clone(); + let result = AddDataBuilder::new(remote, Box::new(input), None) + .write_parallelism(2) + .progress(move |p| { + seen.lock() + .unwrap() + .push((p.output_rows(), p.output_bytes(), p.done())) + }) + .execute() + .await; + if complete_fault { + assert!( + result + .unwrap_err() + .to_string() + .contains("commit outcome unknown"), + "{fault:?}" + ); + } else { + result.unwrap(); + } + assert_eq!( + stored.count_rows(None).await.unwrap(), + 2, + "{fault:?}, complete={complete_fault}" + ); + let payloads = stored.fetch_blobs("payload", &[0, 1]).await.unwrap(); + assert_eq!(payloads.value(0), payload_a); + assert_eq!(payloads.value(1), payload_b); + let state = state.lock().unwrap(); + assert_eq!((state.creates, state.completes, state.aborts), (1, 1, 0)); + assert_eq!(state.parts.len(), 1); + assert_eq!(state.attempts.len(), if complete_fault { 1 } else { 2 }); + if !complete_fault { + assert_eq!(state.attempts[0], state.attempts[1]); + } + let progress = progress.lock().unwrap(); + let last = progress.last().unwrap(); + assert_eq!(last.0, 2); + assert!(last.1 > 0 && last.2); + assert_eq!( + progress.first().unwrap().1, + 0, + "scan is not an acknowledgement" + ); + assert!(progress.windows(2).all(|pair| pair[0].1 <= pair[1].1)); + assert_eq!(last.1, state.parts.values().map(Vec::len).sum::()); + server.abort(); + } + } +} + +#[tokio::test] +async fn multipart_retries_sixth_part_after_reused_connection_closes() { + use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; + use datafusion_execution::TaskContext; + use datafusion_physical_plan::ExecutionPlan; + use futures::TryStreamExt; + + let progress = Arc::new(Mutex::new(Vec::new())); + let observed = progress.clone(); + let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { + observed + .lock() + .unwrap() + .push((p.output_rows(), p.output_bytes())); + })); + let tracker = Arc::new(WriteProgressTracker::new(callback, Some(6))); + tracker.use_acknowledged_parts(); + let during_request = progress.clone(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let mut attempts = Vec::new(); + let mut acknowledged_bytes = 0; + let (mut socket, _) = listener.accept().await.unwrap(); + for n in 0..6 { + let (path, body) = read_request(&mut socket).await; + let rows = StreamReader::try_new(body.as_slice(), None) + .unwrap() + .map(|batch| batch.unwrap().num_rows()) + .sum::(); + assert_eq!(rows, 1, "one scanned batch must split into six parts"); + let reported = *during_request.lock().unwrap().last().unwrap(); + assert_eq!( + reported, + (n, acknowledged_bytes), + "progress must exclude the unacknowledged part" + ); + if n < 5 { + acknowledged_bytes += body.len(); + } + attempts.push((path, body)); + if n == 5 { + break; + } + // Keep one connection pooled for the first five acknowledged parts. + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") + .await + .unwrap(); + } + // The sixth part was staged, but the peer closes before response headers. + drop(socket); + let (mut socket, _) = listener.accept().await.unwrap(); + let (path, body) = read_request(&mut socket).await; + let reported = *during_request.lock().unwrap().last().unwrap(); + assert_eq!( + reported, + (5, acknowledged_bytes), + "retry must not report the lost acknowledgement" + ); + acknowledged_bytes += body.len(); + attempts.push((path, body)); + respond(&mut socket, 200, "{}").await; + (attempts, acknowledged_bytes) + }); + let client = RestfulLanceDbClient::try_new( + &crate::remote::client::parse_db_url("db://test").unwrap(), + "test-region", + Some(format!("http://{address}")), + Default::default(), + ClientConfig { + retry_config: RetryConfig { + retries: Some(3), + read_retries: Some(3), + connect_retries: Some(3), + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let input = arrow_array::record_batch!(("id", Int32, [1, 2, 3, 4, 5, 6])).unwrap(); + let plan = Arc::new( + crate::table::datafusion::scannable_exec::ScannableExec::new( + Box::new(input), + Some(tracker.clone()), + ), + ); + let exec = super::insert::RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + plan, + false, + "upload-1".into(), + Some(tracker), + None, + Some(1), + None, + ); + exec.execute(0, Arc::new(TaskContext::default())) + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (attempts, acknowledged_bytes) = server.await.unwrap(); + let progress = progress.lock().unwrap(); + assert_eq!(*progress.first().unwrap(), (0, 0)); + assert_eq!(*progress.last().unwrap(), (6, acknowledged_bytes)); + assert!( + progress + .windows(2) + .all(|pair| pair[0].0 <= pair[1].0 && pair[0].1 <= pair[1].1) + ); + assert_eq!(attempts.len(), 7); + assert_eq!( + attempts[5], attempts[6], + "retry must reuse both part ID and bytes" + ); + let unique: std::collections::HashSet<_> = attempts.iter().map(|(path, _)| path).collect(); + assert_eq!(unique.len(), 6, "the staged sixth txn must be replaced"); +} + +#[tokio::test] +async fn multipart_rejections_preserve_progress_and_cleanup_boundaries() { + // Stage rejection, definite complete rejection, and ambiguous successful responses. + for (stage_status, complete_status, complete_body, cleanup) in [ + (503, 200, "{}", true), + (200, 409, "transaction conflict", true), + (200, 429, "rate limited", true), + (200, 200, "{}", false), + (200, 200, "not json", false), + (200, 503, "gateway failure", false), + ] { + for abort_status in [200, 503] { + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = requests.clone(); + let progress = Arc::new(Mutex::new(Vec::new())); + let during_request = progress.clone(); + let remote = Arc::new(RemoteTable::new_mock( + "test".into(), + move |request| { + let path = request.url().path(); + observed.lock().unwrap().push(path.to_owned()); + let (status, body) = if path.ends_with("/create") { + (200, r#"{"upload_id":"rejected-upload"}"#) + } else if path.ends_with("/insert/") { + let progress = during_request.lock().unwrap(); + assert!(!progress.is_empty(), "must execute the scan tracker"); + assert!(progress.iter().all(|p: &(usize, usize, bool)| p.1 == 0)); + (stage_status, "{}") + } else if path.ends_with("/complete") { + (complete_status, complete_body) + } else if path.ends_with("/abort") { + (abort_status, "cleanup response") + } else { + panic!("unexpected request {path}") + }; + http::Response::builder() + .status(status) + .body(body.to_owned()) + .unwrap() + }, + Some(semver::Version::new(0, 4, 0)), + )); + let input = arrow_array::record_batch!(("id", Int32, [1, 2])).unwrap(); + remote.seed_schema(&serde_json::json!({"version": 1, "schema": JsonSchema::try_from(input.schema().as_ref()).unwrap()}).to_string()); + let seen = progress.clone(); + let error = AddDataBuilder::new(remote, Box::new(input), None) + .write_parallelism(2) + .retries(0) + .progress(move |p| { + seen.lock() + .unwrap() + .push((p.output_rows(), p.output_bytes(), p.done())) + }) + .execute() + .await + .unwrap_err(); + let requests = requests.lock().unwrap(); + let count = |suffix: &str| { + requests + .iter() + .filter(|path| path.ends_with(suffix)) + .count() + }; + assert_eq!(count("/create"), 1); + assert_eq!(count("/insert/"), 1); + assert_eq!(count("/complete"), usize::from(stage_status == 200)); + assert_eq!( + count("/abort"), + usize::from(cleanup), + "cleanup must honor retries=0: {error}" + ); + assert_eq!( + error.to_string().contains("commit outcome unknown"), + !cleanup, + "{error}" + ); + let progress = progress.lock().unwrap(); + let last = progress.last().unwrap(); + assert!(last.2); + assert_eq!( + progress.first().unwrap().0, + 0, + "scan is not an acknowledgement" + ); + assert_eq!(last.0, if stage_status == 200 { 2 } else { 0 }); + if stage_status != 200 { + assert!( + progress.iter().all(|p| p.1 == 0), + "unacknowledged bytes reported" + ); + } + } + } +} diff --git a/rust/lancedb/src/remote/util.rs b/rust/lancedb/src/remote/util.rs index 1c368e2f5..dcfaf9312 100644 --- a/rust/lancedb/src/remote/util.rs +++ b/rust/lancedb/src/remote/util.rs @@ -1,7 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use arrow_array::{ + Array, ArrayRef, GenericListViewArray, OffsetSizeTrait, RecordBatch, UInt64Array, + cast::AsArray, make_array, +}; +use arrow_buffer::ScalarBuffer; +use arrow_data::ArrayData; use arrow_ipc::CompressionType; +use arrow_schema::{ArrowError, DataType, Field}; +use arrow_select::{dictionary::garbage_collect_any_dictionary, take::take}; use futures::{Stream, StreamExt}; use reqwest::Response; @@ -9,6 +17,269 @@ use crate::{Result, arrow::SendableRecordBatchStream}; use super::db::ServerVersion; +fn has_dictionary(data: &ArrayData) -> bool { + matches!(data.data_type(), DataType::Dictionary(_, _)) + || data.child_data().iter().any(has_dictionary) +} + +fn has_list_view(data: &ArrayData) -> bool { + matches!( + data.data_type(), + DataType::ListView(_) | DataType::LargeListView(_) + ) || data.child_data().iter().any(has_list_view) +} + +// Arrow take on ordinary lists copies nested ListView ranges through +// MutableArrayData, losing sharing. Select child row IDs instead, then apply +// that selection recursively to the real children. +fn take_dictionary_rows( + array: &dyn Array, + indices: &UInt64Array, +) -> std::result::Result { + let data = array.to_data(); + if !has_list_view(&data) { + return take(array, indices, None); + } + let item = || std::sync::Arc::new(Field::new_list_field(DataType::UInt64, false)); + let proxy_type = match data.data_type() { + DataType::List(_) | DataType::Map(_, _) => DataType::List(item()), + DataType::LargeList(_) => DataType::LargeList(item()), + DataType::FixedSizeList(_, size) => DataType::FixedSizeList(item(), *size), + DataType::Struct(fields) => DataType::Struct( + fields + .iter() + .map(|f| f.as_ref().clone().with_data_type(DataType::UInt64)) + .collect(), + ), + // ListView take already preserves sharing; its actual child selection + // is performed by compact_list_view before dictionary collection. + _ => return take(array, indices, None), + }; + let children = data + .child_data() + .iter() + .map(|child| UInt64Array::from_iter_values(0..child.len() as u64).to_data()) + .collect(); + let proxy = make_array( + data.clone() + .into_builder() + .data_type(proxy_type) + .child_data(children) + .build()?, + ); + let selected = take(proxy.as_ref(), indices, None)?.to_data(); + let children = data + .child_data() + .iter() + .zip(selected.child_data()) + .map(|(child, ids)| { + let ids = UInt64Array::from(ids.clone()); + Ok(take_dictionary_rows(make_array(child.clone()).as_ref(), &ids)?.to_data()) + }) + .collect::, ArrowError>>()?; + Ok(make_array( + selected + .into_builder() + .data_type(data.data_type().clone()) + .child_data(children) + .build()?, + )) +} + +fn compact_list_view( + views: &GenericListViewArray, +) -> std::result::Result { + let mut ranges: Vec<_> = (0..views.len()) + .filter_map(|row| { + let start = views.value_offsets()[row].as_usize(); + let size = views.value_sizes()[row].as_usize(); + (views.is_valid(row) && size != 0).then(|| (start, start + size)) + }) + .collect(); + ranges.sort_unstable(); + let mut union: Vec<(usize, usize, usize)> = Vec::with_capacity(ranges.len()); + let mut len = 0; + for (start, end) in ranges { + if let Some(last) = union.last_mut().filter(|last| start <= last.1) { + let end = end.max(last.1); + len += end - last.1; + last.1 = end; + } else { + union.push((start, end, len)); + len += end - start; + } + } + let mut offsets = Vec::with_capacity(views.len()); + let mut sizes = Vec::with_capacity(views.len()); + for row in 0..views.len() { + let size = views.value_sizes()[row]; + if views.is_null(row) || size.as_usize() == 0 { + offsets.push(O::usize_as(0)); + sizes.push(O::usize_as(0)); + } else { + let start = views.value_offsets()[row].as_usize(); + let range = union[union.partition_point(|r| r.0 <= start) - 1]; + // Removing gaps cannot increase a valid original offset. + offsets.push(O::from_usize(range.2 + start - range.0).unwrap()); + sizes.push(size); + } + } + // Each child position is selected once, even for unsorted, overlapping views. + let indices = UInt64Array::from_iter_values( + union + .iter() + .flat_map(|&(start, end, _)| (start..end).map(|i| i as u64)), + ); + let child = take_dictionary_rows(views.values().as_ref(), &indices)?; + views + .to_data() + .into_builder() + .offset(0) + .buffers(vec![ + ScalarBuffer::from(offsets).into_inner(), + ScalarBuffer::from(sizes).into_inner(), + ]) + .child_data(vec![child.to_data()]) + .build() +} + +fn compact_dictionary_data(data: ArrayData) -> std::result::Result { + let data = match data.data_type() { + DataType::Dictionary(_, _) => { + let array = make_array(data); + garbage_collect_any_dictionary(array.as_any_dictionary())?.to_data() + } + DataType::ListView(_) => compact_list_view(make_array(data).as_list_view::())?, + DataType::LargeListView(_) => compact_list_view(make_array(data).as_list_view::())?, + // Selecting dictionary values retains view backing buffers, which IPC + // otherwise serializes in full even when most views are unreferenced. + DataType::Utf8View => make_array(data).as_string_view().gc().to_data(), + DataType::BinaryView => make_array(data).as_binary_view().gc().to_data(), + _ => data, + }; + let children = data + .child_data() + .iter() + .cloned() + .map(compact_dictionary_data) + .collect::, _>>()?; + data.into_builder().child_data(children).build() +} + +/// Compact dictionaries retained by row slices without changing the schema. +/// Row slices (and `take` alone) retain the original dictionary lookup tables. +/// Struct/fixed-size-list validity does not mask child slots, so values hidden +/// only by those ancestor nulls may remain referenced. +pub(super) fn compact_batch_dictionaries( + batch: RecordBatch, +) -> std::result::Result { + let columns = batch + .columns() + .iter() + .map(|array| { + let data = array.to_data(); + if !has_dictionary(&data) { + return Ok(array.clone()); + } + // Normalize container offsets and select their child rows before + // collecting dictionaries nested in lists/structs/maps. + let data = if matches!(data.data_type(), DataType::Dictionary(_, _)) { + data + } else { + let indices = UInt64Array::from_iter_values(0..array.len() as u64); + take_dictionary_rows(array.as_ref(), &indices)?.to_data() + }; + Ok(make_array(compact_dictionary_data(data)?)) + }) + .collect::, ArrowError>>()?; + RecordBatch::try_new_with_options( + batch.schema(), + columns, + &arrow_array::RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + ) +} + +/// Split batches before IPC encoding, preserving row order and allowing a single +/// oversized row. Compact each dictionary before measuring or splitting it so +/// descendants never repeatedly scan or encode the full source dictionary. +/// Yield slices on demand so compacted dictionary copies are not all retained. +pub(super) fn split_batch( + batch: RecordBatch, + max_bytes: usize, +) -> impl Iterator> { + let mut pending = vec![batch]; + std::iter::from_fn(move || { + while let Some(batch) = pending.pop() { + let batch = match compact_batch_dictionaries(batch) { + Ok(batch) => batch, + Err(err) => { + pending.clear(); + return Some(Err(err)); + } + }; + let size: usize = batch + .columns() + .iter() + .map(|array| { + array + .to_data() + .get_slice_memory_size() + .unwrap_or_else(|_| array.get_buffer_memory_size()) + }) + .sum(); + if size > max_bytes && batch.num_rows() > 1 { + let middle = batch.num_rows() / 2; + pending.push(batch.slice(middle, batch.num_rows() - middle)); + pending.push(batch.slice(0, middle)); + } else { + return Some(Ok(batch)); + } + } + None + }) +} + +pub(super) const IPC_BATCH_BYTES: usize = 8 * 1024 * 1024; +pub(super) const MAX_CREATE_BYTES: usize = 256 * 1024 * 1024; + +/// Validate the entire create payload before issuing its single atomic request. +/// A truncated IPC stream can be accepted as EOF by Arrow readers, so failing a +/// live request body after exceeding the budget cannot guarantee atomic failure. +/// Spooling bounds memory while ensuring an oversized input never reaches create. +pub(super) async fn create_body(data: SendableRecordBatchStream) -> Result { + use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; + let io_error = |err: std::io::Error| crate::Error::Other { + message: "Failed to prepare atomic remote create payload".into(), + source: Some(Box::new(err)), + }; + let file = tempfile::tempfile().map_err(io_error)?; + let mut file = tokio::fs::File::from_std(file); + let mut stream = Box::pin(stream_as_ipc(data)?); + let mut bytes = 0usize; + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + bytes = bytes.saturating_add(chunk.len()); + if bytes > MAX_CREATE_BYTES { + return Err(crate::Error::InvalidInput { + message: format!( + "Remote create_table exceeds the {MAX_CREATE_BYTES}-byte single-request budget. \ + Create the table with db.create_table(name, schema=...), then upload with \ + table.add(data, progress=True)." + ), + }); + } + file.write_all(&chunk).await.map_err(io_error)?; + } + file.rewind().await.map_err(io_error)?; + let stream = futures::stream::try_unfold(file, |mut file| async move { + let mut chunk = vec![0; 64 * 1024]; + let len = file.read(&mut chunk).await?; + chunk.truncate(len); + Ok::<_, std::io::Error>((len != 0).then_some((chunk, file))) + }); + Ok(reqwest::Body::wrap_stream(stream)) +} + pub fn stream_as_ipc( data: SendableRecordBatchStream, ) -> Result>> { @@ -18,6 +289,13 @@ pub fn stream_as_ipc( let buf = Vec::with_capacity(WRITE_BUF_SIZE); let writer = arrow_ipc::writer::StreamWriter::try_new_with_options(buf, &data.schema(), options)?; + let data = data.flat_map(|batch| match batch { + Ok(batch) => futures::stream::iter( + split_batch(batch, IPC_BATCH_BYTES).map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }); let stream = futures::stream::try_unfold( (data, writer, false), move |(mut data, mut writer, finished)| async move { @@ -42,11 +320,6 @@ pub fn stream_as_ipc( Ok(stream) } -pub fn stream_as_body(data: SendableRecordBatchStream) -> Result { - let stream = stream_as_ipc(data)?; - Ok(reqwest::Body::wrap_stream(stream)) -} - pub fn parse_server_version(req_id: &str, rsp: &Response) -> Result { let version = rsp .headers() diff --git a/rust/lancedb/src/secrets.rs b/rust/lancedb/src/secrets.rs index c15c7ead9..29a07ba95 100644 --- a/rust/lancedb/src/secrets.rs +++ b/rust/lancedb/src/secrets.rs @@ -82,7 +82,7 @@ impl SecretReference { #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[non_exhaustive] pub enum SecretBinding { - /// Delivered as an environment variable, which the UDF's library already + /// Delivered as an environment variable, which the function's library already /// reads. The variable is the delivery target; the Secret is what fills it. Env { variable: String, diff --git a/rust/lancedb/src/server_info.rs b/rust/lancedb/src/server_info.rs new file mode 100644 index 000000000..48daf508b --- /dev/null +++ b/rust/lancedb/src/server_info.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Remote server provenance for diagnostics without submitting a query or job. + +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Immutable identity compiled into a server executable. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerBuildInfo { + /// Release of this executable. + pub release: String, + /// Git revision used to build the executable. + pub git_sha: String, + /// UTC RFC 3339 build timestamp, when known. + pub build_date: Option, +} + +impl fmt::Display for ServerBuildInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} (git {}, built {})", + self.release, + self.git_sha, + self.build_date.as_deref().unwrap_or("unknown") + ) + } +} + +/// Identity of the query node that answered a discovery request. +/// +/// Different requests can reach different versions during a rolling upgrade. +/// Configured images do not establish which version a running job uses. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerInfo { + /// The responding executable; absent if its identity was not initialized. + pub query_node: Option, + /// Lance library linked into the responding server. + pub lance_version: String, + /// LanceDB library linked into the responding server. + pub lancedb_version: String, + /// Function worker protocol supported by this server build. + pub function_worker_protocol_version: u16, + /// Configured query-node image, not an independently observed digest. + pub configured_query_node_image: Option, + /// Default CPU/job worker image; existing jobs can retain earlier pins. + pub configured_job_worker_image: Option, + /// CLI image configured for newly launched SQL jobs. + pub configured_sql_job_image: Option, + /// Configured GPU worker image, not an observation of a running worker. + pub configured_gpu_worker_image: Option, +} diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index 5c01fe898..88195aff2 100644 --- a/rust/lancedb/src/sql.rs +++ b/rust/lancedb/src/sql.rs @@ -3,7 +3,7 @@ //! Handles to SQL queries running on a LanceDB Enterprise database. -use std::{fmt, sync::Arc}; +use std::{fmt, sync::Arc, time::Duration}; use async_trait::async_trait; use chrono::{DateTime, Utc}; @@ -11,6 +11,23 @@ use uuid::Uuid; use crate::{Result, arrow::SendableRecordBatchStream}; +/// Controls for one SQL execution. +#[non_exhaustive] +#[derive(Clone, Debug, Default)] +pub struct QueryOptions { + /// Limit submission and result consumption together, starting at submission. + /// On expiry, the SDK stops reading and attempts to cancel Flight execution. + /// Durable server-side jobs still require explicit job cancellation. + pub timeout: Option, + /// Limit each wait for a server response or the next result batch. + /// Defaults to the connection's read timeout. + pub read_timeout: Option, + /// Attempt to cancel deferred Flight execution when its unread handle or + /// reader is dropped. Defaults to false so deferred queries can be detached. + /// Directly streamed queries always stop when their reader is dropped. + pub cancel_on_drop: bool, +} + /// The externally visible lifecycle state of a submitted SQL query. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum QueryStatus { @@ -44,6 +61,10 @@ impl fmt::Display for QueryStatus { pub struct QueryDescription { /// The stable, connection-scoped identifier assigned when the query was submitted. pub id: Uuid, + /// The durable Job Registry identifier for a server-side SQL job, when the + /// submitted statement ran as one. This identifier can be passed to + /// `open_job`; `id` remains connection-scoped. + pub job_id: Option, /// The server-visible lifecycle state. pub status: QueryStatus, /// Server-reported completion progress, when known. Values are in `[0.0, 1.0]`, @@ -56,6 +77,9 @@ pub struct QueryDescription { #[async_trait] pub(crate) trait QueryHandle: Send + Sync { fn id(&self) -> Uuid; + fn job_id(&self) -> Option { + None + } async fn describe(&self) -> Result; async fn reader(&self) -> Result; async fn cancel(&self) -> Result<()>; @@ -66,10 +90,12 @@ pub(crate) trait QueryHandle: Send + Sync { /// The handle can be inspected, opened as an Arrow reader, or cancelled. /// The server may stream results on the initial call or defer execution and /// return result tickets. Dropping an unread handle or its reader stops a -/// directly streamed query; deferred execution continues until explicitly -/// cancelled. This applies equally with and without parameters. -/// Identifier lookup is scoped to the connection that submitted the query and -/// is not a durable resume mechanism. +/// directly streamed query. Deferred execution continues until cancelled, +/// unless a timeout or `cancel_on_drop` was set on its execution builder. +/// This applies equally with and without parameters. +/// [`Self::id`] is scoped to the connection that submitted the query. When the +/// server runs the statement as a SQL job, [`Self::job_id`] exposes the durable +/// Job Registry identifier accepted by `open_job`. pub struct Query { handle: Arc, } @@ -79,6 +105,7 @@ impl std::fmt::Debug for Query { formatter .debug_struct("Query") .field("id", &self.id()) + .field("job_id", &self.job_id()) .finish() } } @@ -94,6 +121,16 @@ impl Query { self.handle.id() } + /// Return the durable Job Registry identifier when the server has reported + /// one for this query. + /// + /// A running query may report it after [`Self::describe`] observes the + /// server's latest status. The connection-scoped [`Self::id`] remains a + /// separate identifier. + pub fn job_id(&self) -> Option { + self.handle.job_id() + } + /// Get a point-in-time description of the query. /// /// Directly streamed queries stay [`QueryStatus::Running`] until the result @@ -115,7 +152,12 @@ impl Query { self.handle.reader().await } - /// Request cancellation of the query. + /// Request cancellation of this query's Flight execution. + /// + /// For a durable server-side SQL job, the operation may return + /// [`Error::NotSupported`] because the Flight waiter cannot cancel the + /// registry job. Use [`Connection::cancel_job`](crate::Connection::cancel_job) + /// with [`Self::job_id`] to cancel that job. pub async fn cancel(&self) -> Result<()> { self.handle.cancel().await } diff --git a/rust/lancedb/src/storage_integration.rs b/rust/lancedb/src/storage_integration.rs index 50bfc0aca..fcd2c4f5d 100644 --- a/rust/lancedb/src/storage_integration.rs +++ b/rust/lancedb/src/storage_integration.rs @@ -40,6 +40,9 @@ impl SecretReference { #[derive(Debug, Clone, Serialize, Deserialize)] #[non_exhaustive] pub struct CreateStorageIntegrationRequest { + /// Return the stored configuration unchanged when the integration already exists. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, pub storage_provider: StorageProvider, pub storage_prefix: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -59,6 +62,8 @@ pub struct CreateStorageIntegrationRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub azure_client_secret_secret: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_storage_account_access_key_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub gcp_credentials_json_secret: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub huggingface_token_secret: Option, @@ -77,12 +82,31 @@ pub enum StorageProvider { HuggingFace, } +fn is_false(value: &bool) -> bool { + !*value +} + impl CreateStorageIntegrationRequest { + /// Return an existing integration without changing its configuration. + /// Defaults to false, which reports an error for an existing name. + /// + /// ``` + /// use lancedb::storage_integration::CreateStorageIntegrationRequest; + /// let config = CreateStorageIntegrationRequest::huggingface( + /// "hf://datasets/acme/data/", + /// ).exist_ok(true); + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Register a prefix and the customer-owned IAM role authorized to access it. pub fn s3(storage_prefix: impl Into, aws_role_arn: impl Into) -> Self { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: Some(aws_role_arn.into()), aws_access_key_id_secret: None, aws_secret_access_key_secret: None, @@ -91,6 +115,7 @@ impl CreateStorageIntegrationRequest { azure_tenant_id_secret: None, azure_client_id_secret: None, azure_client_secret_secret: None, + azure_storage_account_access_key_secret: None, gcp_credentials_json_secret: None, huggingface_token_secret: None, } @@ -105,6 +130,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: None, aws_access_key_id_secret: Some(access_key), aws_secret_access_key_secret: Some(secret_key), @@ -113,6 +139,7 @@ impl CreateStorageIntegrationRequest { azure_tenant_id_secret: None, azure_client_id_secret: None, azure_client_secret_secret: None, + azure_storage_account_access_key_secret: None, gcp_credentials_json_secret: None, huggingface_token_secret: None, } @@ -138,10 +165,43 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Azure, storage_prefix: storage_prefix.into(), + exist_ok: false, azure_storage_account: Some(storage_account.into()), azure_tenant_id_secret: Some(tenant_id), azure_client_id_secret: Some(client_id), azure_client_secret_secret: Some(client_secret), + azure_storage_account_access_key_secret: None, + gcp_credentials_json_secret: None, + huggingface_token_secret: None, + aws_role_arn: None, + aws_access_key_id_secret: None, + aws_secret_access_key_secret: None, + aws_region: None, + } + } + + /// Register Azure Blob access using a Secret containing a storage account access key. + /// + /// ``` + /// use lancedb::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; + /// let config = CreateStorageIntegrationRequest::azure_with_account_access_key( + /// "az://customer-data/raw/", "customeraccount", SecretReference::new("azure_key"), + /// ); + /// ``` + pub fn azure_with_account_access_key( + storage_prefix: impl Into, + storage_account: impl Into, + access_key: SecretReference, + ) -> Self { + Self { + storage_provider: StorageProvider::Azure, + storage_prefix: storage_prefix.into(), + exist_ok: false, + azure_storage_account: Some(storage_account.into()), + azure_storage_account_access_key_secret: Some(access_key), + azure_tenant_id_secret: None, + azure_client_id_secret: None, + azure_client_secret_secret: None, gcp_credentials_json_secret: None, huggingface_token_secret: None, aws_role_arn: None, @@ -163,6 +223,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Gcp, storage_prefix: storage_prefix.into(), + exist_ok: false, gcp_credentials_json_secret: Some(credentials_json), huggingface_token_secret: None, aws_role_arn: None, @@ -173,6 +234,7 @@ impl CreateStorageIntegrationRequest { azure_tenant_id_secret: None, azure_client_id_secret: None, azure_client_secret_secret: None, + azure_storage_account_access_key_secret: None, } } @@ -189,6 +251,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::HuggingFace, storage_prefix: storage_prefix.into(), + exist_ok: false, huggingface_token_secret: None, gcp_credentials_json_secret: None, aws_role_arn: None, @@ -199,6 +262,7 @@ impl CreateStorageIntegrationRequest { azure_tenant_id_secret: None, azure_client_id_secret: None, azure_client_secret_secret: None, + azure_storage_account_access_key_secret: None, } } @@ -244,6 +308,8 @@ pub struct StorageIntegrationInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub azure_client_secret_secret: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + pub azure_storage_account_access_key_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub gcp_credentials_json_secret: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub huggingface_token_secret: Option, diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index df4e0cca6..39cdd7e0a 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -29,7 +29,9 @@ use lance::index::scalar::load_segment_params; use lance::io::{ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; use lance_index::IndexCriteria; -use lance_io::object_store::{LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor, StorageOptionsProvider, +}; pub use query::AnyQuery; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; @@ -49,7 +51,7 @@ use std::format; use std::path::Path; use std::sync::Arc; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{LayeredStorageOptionsProvider, NamespaceClientPushdownOperation}; use crate::DistanceType; use crate::blob::BlobRangeRequest; @@ -82,9 +84,16 @@ mod create_index; pub mod datafusion; pub(crate) mod dataset; pub mod delete; +pub mod delta; pub mod freshness; +pub mod function_column_status; pub mod merge; pub mod optimize; +pub use optimize::CompactionResult; +mod cleanup; +pub use cleanup::{CleanupOptions, CleanupPlan, CleanupResult}; +mod prewarm; +pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary}; pub(crate) mod primary_key; pub mod query; pub mod refresh; @@ -106,14 +115,24 @@ pub use computed_columns::{ ComputedColumn, ComputedColumnKind, computed_column_from_field, computed_columns, }; pub use delete::DeleteResult; +pub use delta::{DeltaRef, TableDelta}; +pub use function_column_status::{ + FunctionColumnAutoRefreshBlockedReason, FunctionColumnAutoRefreshState, + FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, + FunctionColumnVersionStatus, +}; use futures::future::join_all; pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags}; pub use lance::dataset::scanner::DatasetRecordBatchStream; pub use lance_index::optimize::OptimizeOptions; pub use optimize::{ - CompactionMode, CompactionOptions, IndexRemapMode, OptimizeAction, OptimizeStats, + CompactionMode, CompactionOptions, CompactionOverrides, IndexRemapMode, OptimizeAction, + OptimizeStats, +}; +pub use refresh::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget, + RefreshColumnOptions, RefreshColumnResult, }; -pub use refresh::{RefreshColumnOptions, RefreshColumnResult}; pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats}; pub use schema_evolution::{ AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate, @@ -268,6 +287,10 @@ pub struct WriteOptions { /// /// Overlapping `OpenTableBuilder` options (e.g. [AddDataBuilder::mode]) will take /// precedence over their counterparts in `WriteOptions` (e.g. [WriteParams::mode]). + /// + /// In LanceDB Enterprise, `add` returns [`Error::NotSupported`] when + /// `max_rows_per_file`, `max_rows_per_group`, or `max_bytes_per_file` is + /// non-default, because the remote insert protocol only transmits the write mode. pub lance_write_params: Option, } @@ -595,6 +618,25 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("remote materialized-view refresh is not supported on this table type"), }) } + /// Submit an Enterprise refresh with aggregate resource caps and GPU placement. + #[doc(hidden)] + async fn refresh_materialized_view_async_with_options( + &self, + source_version: Option, + full: bool, + options: crate::materialized_view::RefreshMaterializedViewOptions, + ) -> Result> { + options.validate()?; + if !options.is_empty() { + return Err(Error::NotSupported { + message: + "this table cannot enforce materialized-view resource budgets or GPU placement" + .into(), + }); + } + self.refresh_materialized_view_async(source_version, full) + .await + } /// Create a read-only handle pinned to the table's current active revision. /// /// The returned handle is independent from later refreshes or checkouts on @@ -659,6 +701,23 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Currently only supported in LanceDB Enterprise. /// If `columns` is `None`, all columns are prewarmed. async fn prewarm_data(&self, columns: Option>) -> Result<()>; + + /// Submit a data-cache prewarm and return its durable job handle. + async fn prewarm_data_async( + &self, + _options: PrewarmDataOptions, + ) -> Result> { + Err(Error::NotSupported { + message: "data prewarm jobs are only supported on remote tables".into(), + }) + } + /// Preview data-cache prewarm without submitting a warming job. + async fn explain_prewarm_data(&self, _options: PrewarmDataOptions) -> Result { + Err(Error::NotSupported { + message: "data prewarm previews are only supported on remote tables".into(), + }) + } + /// Get statistics about the index. async fn index_stats(&self, index_name: &str) -> Result>; /// Merge insert new records into the table. @@ -806,6 +865,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "blob_columns is not supported on this table type".into(), }) } + /// Bind a remote payload reader to an identity from its producing query. + async fn query_snapshot_with_identity( + &self, + _version: u64, + _identity: &str, + ) -> Result> { + Err(Error::NotSupported { + message: "query snapshot identities are not supported on this table type".into(), + }) + } /// Materialize blob bytes for the given row ids. See [`Table::fetch_blobs`]. async fn fetch_blobs(&self, _column: &str, _row_ids: &[u64]) -> Result { Err(Error::NotSupported { @@ -842,6 +911,36 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn tags(&self) -> Result>; /// Optimize the dataset. async fn optimize(&self, action: OptimizeAction) -> Result; + /// Submit Enterprise version cleanup and retain its durable job and outcome. + async fn cleanup_async(&self, _options: CleanupOptions) -> Result> { + Err(Error::NotSupported { + message: "durable cleanup jobs are only supported on remote tables".into(), + }) + } + + async fn explain_cleanup(&self, _options: CleanupOptions) -> Result { + Err(Error::NotSupported { + message: "cleanup previews require LanceDB Enterprise".into(), + }) + } + + /// Submit remote compaction and retain its durable job and actual outcome. + async fn compact_async( + &self, + _options: optimize::CompactionOverrides, + ) -> Result> { + Err(Error::NotSupported { + message: "compaction jobs are only supported on remote tables".into(), + }) + } + /// Compact with optional fields, preserving remote policy inheritance. + async fn compact(&self, options: optimize::CompactionOverrides) -> Result { + self.optimize(OptimizeAction::Compact { + options: options.into_options(), + remap_options: None, + }) + .await + } /// Add columns to the table. async fn add_columns( &self, @@ -874,6 +973,17 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("Function columns are supported only in LanceDB Enterprise"), }) } + /// Declare multiple immutable registered-Function bindings in one schema commit. + async fn add_function_bindings( + &self, + _bindings: &[(crate::function::FunctionApplication, Option)], + _options: computed_columns::ComputedColumnOptions, + ) -> Result { + Err(Error::NotSupported { + message: DocLink::Functions + .append_to("Batch Function declarations require LanceDB Enterprise support"), + }) + } /// Fill a computed column's unfilled rows and recompute those whose /// inputs changed. /// @@ -883,14 +993,19 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "this operation is only supported on LanceDB Embedded".into(), }) } - /// Refresh with options; expression-backed local refreshes ignore the - /// Function batch size. + /// Refresh with options. A local refresh ignores the Function batch size + /// and GPU placement and rejects every other option. async fn refresh_column_with_options( &self, column: &str, options: RefreshColumnOptions, ) -> Result { options.validate()?; + if let Some(name) = options.enterprise_only_option() { + return Err(Error::NotSupported { + message: format!("{name} requires a LanceDB Enterprise refresh"), + }); + } self.refresh_column(column).await } /// Fill a computed column's unfilled rows and recompute those whose @@ -910,8 +1025,22 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { options: RefreshColumnOptions, ) -> Result> { options.validate()?; + if let Some(name) = options.enterprise_only_option() { + return Err(Error::NotSupported { + message: format!("{name} requires a LanceDB Enterprise refresh"), + }); + } self.refresh_column_async(column).await } + /// Resume a failed Function refresh on this table and branch. + async fn resume_refresh( + &self, + _job_id: &str, + ) -> Result> { + Err(Error::NotSupported { + message: "resuming a Function refresh requires LanceDB Enterprise".into(), + }) + } /// The per-row errors Function refreshes recorded on this table; see /// [`Table::function_errors`]. The default returns `NotSupported`. async fn function_errors( @@ -923,12 +1052,61 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("per-row Function errors are recorded only in LanceDB Enterprise"), }) } + /// Change the quarantine state of current failed rows. + async fn quarantine_function_errors( + &self, + _column: &str, + _options: &crate::function::FunctionQuarantineOptions, + ) -> Result { + Err(Error::NotSupported { + message: "Function quarantine requires LanceDB Enterprise".into(), + }) + } + + /// Read per-row producing Function versions from LanceDB Enterprise. + async fn function_provenance( + &self, + _column: &str, + _options: &crate::function::FunctionProvenanceOptions, + ) -> Result { + Err(Error::NotSupported { + message: "Function provenance requires LanceDB Enterprise".into(), + }) + } + + /// Exact four-way freshness status for Function-backed output columns. + /// + /// `column` filters to one user-visible output; `None` returns every + /// Function output. The default returns `NotSupported`. + async fn function_column_statuses( + &self, + _column: Option<&str>, + ) -> Result> { + Err(Error::NotSupported { + message: DocLink::Functions + .append_to("exact Function column status is supported only in LanceDB Enterprise"), + }) + } /// Alter columns in the table. async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result; /// Drop columns from the table. async fn drop_columns(&self, columns: &[&str]) -> Result; /// Get the version of the table. async fn version(&self) -> Result; + /// Compare two persisted versions on this table's current branch. + /// + /// The default implementation returns [`Error::NotSupported`]; table types + /// without a local Lance dataset, such as remote tables, cannot stream row + /// changes. + async fn delta( + &self, + _from_version: DeltaRef, + _to_version: Option, + ) -> Result { + Err(Error::NotSupported { + message: "table.delta is only supported on LanceDB Embedded tables".into(), + }) + } /// Return a new table handle pinned to the exact revision currently visible. async fn checkout_current(&self) -> Result> { Err(Error::NotSupported { @@ -942,6 +1120,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn checkout_tag(&self, tag: &str) -> Result<()>; /// Checkout the latest version of the table. async fn checkout_latest(&self) -> Result<()>; + /// Advance a latest handle to the current snapshot before a polling read. + /// + /// Pinned version, tag, and snapshot handles must remain unchanged. This + /// lets a freshness wait observe publications that arrive after it starts + /// without changing an explicit time-travel selection. + #[doc(hidden)] + async fn checkout_latest_if_latest(&self) -> Result<()> { + Ok(()) + } /// Return an independent handle pinned to the version currently selected. /// /// Backends that can advance between requests should override this for @@ -1295,6 +1482,19 @@ impl Table { }) } + /// Create an independent remote handle constrained by a query response. + #[doc(hidden)] + pub async fn query_snapshot_with_identity(&self, version: u64, identity: &str) -> Result { + Ok(Self { + inner: self + .inner + .query_snapshot_with_identity(version, identity) + .await?, + database: self.database.clone(), + embedding_registry: self.embedding_registry.clone(), + }) + } + /// Count the number of rows in this dataset. /// /// # Arguments @@ -1352,6 +1552,12 @@ impl Table { /// # } /// ``` /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// Blobs inside lists cannot be fetched by row id. Returns /// [`Error::InvalidInput`] for those paths, when the column does not exist, /// or when it is not a blob column. Returns [`Error::NotSupported`] on @@ -1372,8 +1578,13 @@ impl Table { /// ranges for the same blob. The output has the same length and order as /// the requests. Null blobs produce null output slots; empty ranges on /// non-null blobs produce empty byte strings. - /// LanceDB Enterprise tables read through version-pinned [`BlobFile`] handles using - /// HTTP byte-range requests. + /// LanceDB Enterprise uses the batched endpoint when the server advertises + /// support, splitting calls at 1024 ranges and 64 MiB of requested bytes. + /// Individual larger ranges are partitioned and reassembled into one result. + /// Older servers use descriptor queries and [`Self::fetch_blob_files`] range + /// reads. Both protocols read one exact branch and version without changing + /// this handle's checkout. The final materialized output still occupies memory. + /// Errors from an advertised endpoint propagate without switching protocols. /// /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no @@ -1398,6 +1609,12 @@ impl Table { /// # } /// ``` /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// Returns an error when a range is invalid, a requested row id does not /// exist, or the column is not a blob column. Returns /// [`Error::NotSupported`] on table types without blob support. @@ -1406,10 +1623,14 @@ impl Table { column: impl AsRef, requests: impl IntoIterator, ) -> Result { - let requests = requests.into_iter().collect::>(); - self.inner - .fetch_blob_ranges(column.as_ref(), &requests) - .await + let mut ranges = Vec::new(); + for request in requests { + ranges.try_reserve(1).map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + ranges.push(request); + } + self.inner.fetch_blob_ranges(column.as_ref(), &ranges).await } /// Open lazy [`BlobFile`] handles for the given row ids. @@ -1421,6 +1642,12 @@ impl Table { /// `ClientConfig::blob_request_concurrency` or the /// `LANCE_CLIENT_BLOB_REQUEST_CONCURRENCY` environment variable to tune it. /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no /// partial handles are returned. @@ -1448,7 +1675,10 @@ impl Table { /// /// The descriptor carries its table version, branch, column and row identity. /// Opening does not materialize the payload or change this table's checkout. - /// Remote reads use the table's authenticated HTTP byte-range endpoint. + /// On Enterprise clusters that enable direct Blob reads, large range reads + /// may use a short-lived object-store URL; the client needs network access + /// to that endpoint in addition to the LanceDB endpoint. Small reads stay + /// on the authenticated LanceDB byte-range endpoint. /// /// ``` /// use lancedb::{Table, blob::BlobDescriptor}; @@ -1739,10 +1969,17 @@ impl Table { /// Create a [`Query`] Builder. /// /// Queries allow you to search your existing data. By default the query will - /// return all the data in the table in no particular order. The builder + /// return all the data in the table. The builder /// returned by this method can be used to control the query using filtering, /// vector similarity, sorting, and more. /// + /// An ordinary unfiltered base-only scan of a fixed table version in + /// Embedded returns manifest order: fragments in manifest order, then rows + /// in fragment order. RTE tables scan the LSM by default; use + /// `use_rte(false)` for the base table guarantee. Compaction, updates, and + /// newer versions can change that order. Use [`Query::scan_in_order`] to + /// require it explicitly and fail on paths that cannot uphold it. + /// /// Note: By default, all columns are returned. For best performance, you should /// only fetch the columns you need. See [`Query::select_with_projection`] for /// more details. @@ -1809,8 +2046,10 @@ impl Table { /// /// ## Full scan /// - /// This query will return everything in the table in no particular - /// order. + /// This query returns everything in the table. On an Embedded table, an + /// ordinary unfiltered base-only scan of a fixed version returns manifest + /// order. RTE tables scan the LSM by default and need `use_rte(false)` for + /// base manifest order. /// /// ```no_run /// # use arrow_array::RecordBatch; @@ -1864,9 +2103,20 @@ impl Table { /// There is an ongoing effort to make row ids stable which is tracked at /// https://github.com/lancedb/lancedb/issues/1120 /// - /// No guarantees are made regarding the order in which results are returned. If you - /// desire an output order that matches the order of the given ids, you will need - /// to add the row id column to the output and align it yourself. + /// Results follow the requested row-id order, including repeated IDs. Missing or + /// deleted IDs are omitted. An explicit nonempty [`QueryBase::order_by`] overrides + /// the requested order. Limits and offsets apply after restoring occurrences. + /// These guarantees also apply to remote tables. + /// + /// ```rust + /// use lancedb::query::ExecutableQuery; + /// # async fn example(table: &lancedb::Table, first: u64, second: u64) -> lancedb::Result<()> { + /// // If both IDs exist, return second, first, then second again. + /// let rows = table.take_row_ids(vec![second, first, second]).execute().await?; + /// # Ok(()) + /// # } + /// ``` + /// /// Parameters /// ---------- /// row_ids: list[int] @@ -1904,14 +2154,122 @@ impl Table { /// /// # LanceDB Enterprise (remote tables) /// - /// Only [`OptimizeAction::Compact`] with default `options` and no custom - /// `remap_options` is supported; `All`, `Prune`, and `Index` return + /// [`OptimizeAction::Compact`] supports per-job `target_rows_per_fragment`, + /// `max_source_rows`, `io_buffer_size`, and `batch_size`, with no custom + /// `remap_options`. Other non-default options, `All`, `Prune`, and `Index` return /// [`crate::Error::NotSupported`]. See [`OptimizeAction::Compact`] for /// what a remote call submits and what it does and does not wait for. pub async fn optimize(&self, action: OptimizeAction) -> Result { self.inner.optimize(action).await } + /// Compact data files with optional tuning fields. On remote tables, + /// omitted fields inherit table tuning, then deployment/built-in defaults. + /// Returns after job submission; remote statistics are placeholders. + /// + /// ``` + /// use lancedb::{Table, table::optimize::CompactionOverrides}; + /// # async fn compact(table: &Table) -> lancedb::Result<()> { + /// table.compact(CompactionOverrides { + /// io_buffer_size: Some(64 * 1024 * 1024), + /// ..Default::default() + /// }).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn compact(&self, options: optimize::CompactionOverrides) -> Result { + self.inner.compact(options).await + } + + /// Submit remote compaction and return its durable job after acceptance. + /// + /// Uses SQL `OPTIMIZE ... REWRITE DATA` with the table handle's namespace + /// and branch. The four fields of [`optimize::CompactionOverrides`] retain + /// server defaults when omitted. Requires a compatible remote SQL server + /// and table Ownership plus database/namespace Usage under Standard authorization. + /// Historical-version and local handles are unsupported. + /// + /// Unlike [`Self::optimize`], waiting on this handle waits for compaction + /// itself and returns actual [`CompactionResult`] values. Status, progress, + /// events, and cancellation use the generic HTTP job APIs. A timeout or + /// dropping the handle does not cancel work. Missing result payloads are + /// errors, never placeholder zero statistics. An older worker may omit + /// file counts, represented as `None`. Reopen with + /// `connection.open_job(id).await?.into_typed::()?`. + /// + /// ```no_run + /// # async fn compact(table: &lancedb::Table) -> lancedb::Result<()> { + /// let job = table.compact_async(Default::default()).await?; + /// let result = job.wait().await?; + /// println!("Committed {} rows", result.rows_succeeded); + /// # Ok(()) + /// # } + /// ``` + pub async fn compact_async( + &self, + options: optimize::CompactionOverrides, + ) -> Result> { + self.inner.compact_async(options).await + } + + /// Submit durable version cleanup through SQL VACUUM and return after acceptance. + /// + /// Retention resolves invocation > selected table/branch > deployment. Requires + /// Ownership and parent Usage. Local and historical handles are unsupported. + /// Operators must disable/drain automatic cleanup and prevent other cleanup, + /// tag/branch publication and restore until completion, including direct clients. + /// The server does not enforce that coordination. Preview is available without deletion. + /// Wait, cancel and reopen reuse the shared Job APIs; timeout does not cancel, + /// and cancellation cannot undo deletion or prove storage I/O has stopped. + /// + /// ``` + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// let job = table.cleanup_async(lancedb::table::CleanupOptions::new() + /// .min_age_seconds(604800)).await?; + /// let result = job.wait().await?; + /// println!("{:?}", result.old_versions); + /// # Ok(()) } + /// ``` + pub async fn cleanup_async(&self, options: CleanupOptions) -> Result> { + self.inner.cleanup_async(options).await + } + + /// Explain Enterprise version cleanup without deleting files or submitting a job. + /// Requires the same ownership and retention options as [`Self::cleanup_async`]. + /// Counts are observational estimates, not a reservation for later execution. + pub async fn explain_cleanup(&self, options: CleanupOptions) -> Result { + self.inner.explain_cleanup(options).await + } + + /// Language-binding entry point retaining optional compaction fields. + #[doc(hidden)] + pub async fn optimize_full_with_overrides( + &self, + options: optimize::CompactionOverrides, + older_than: Option, + before_timestamp: Option>, + delete_unverified: Option, + ) -> Result { + if self.as_native().is_some() { + return self + .optimize_full( + options.into_options(), + older_than, + before_timestamp, + delete_unverified, + ) + .await; + } + if older_than.is_some() || before_timestamp.is_some() || delete_unverified == Some(true) { + return Err(Error::NotSupported { message: "pruning is not supported in LanceDB Enterprise; omit pruning options to run compaction only".into() }); + } + let stats = self.compact(options).await?; + Ok(OptimizeStats { + compaction: stats.compaction, + prune: Some(RemovalStats::default()), + }) + } + /// Prune versions committed before an absolute timestamp. /// /// This is an internal entry point for language bindings whose public API @@ -1945,10 +2303,10 @@ impl Table { /// /// This is an internal entry point for language bindings. On a remote /// table (LanceDB Enterprise) only [`OptimizeAction::Compact`] with its - /// defaults is supported. A caller asking for anything pruning-related + /// supported per-job options is supported. A caller asking for anything pruning-related /// (`older_than`, `before_timestamp`, or `delete_unverified: Some(true)`) - /// gets `NotSupported` before anything is submitted, the same way a - /// non-default `CompactionOptions` is already rejected -- rather than a + /// gets `NotSupported` before anything is submitted, the same way + /// unsupported `CompactionOptions` are rejected -- rather than a /// success that silently reports zero bytes pruned when nothing was /// pruned at all. A plain call with none of those set only compacts: /// `Prune` and `Index` are skipped here rather than attempted and @@ -2044,10 +2402,18 @@ impl Table { /// /// [`RefreshColumnOptions::batch_size()`] caps rows per Function call in /// LanceDB Enterprise and must be greater than zero when set. + /// [`RefreshColumnOptions::publication_interval_rows()`] sets an opt-in + /// row-count publication threshold for completed Function outputs; unset + /// keeps whole-fragment publication. + /// [`RefreshColumnOptions::total_memory_bytes()`] sets the aggregate CPU, + /// memory, and GPU budget for a Function refresh. /// [`RefreshColumnOptions::gpu_class()`] selects a GPU pool and - /// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget. - /// These options have no effect on expression-backed columns in LanceDB - /// Embedded. Remote refreshes require + /// [`RefreshColumnOptions::total_gpu_count()`] sets the aggregate GPU budget + /// without changing the deployment's CPU and memory defaults. + /// Batch-size and GPU options have no effect on expression-backed columns + /// in LanceDB Embedded; a resource budget and publication threshold are + /// rejected there. + /// Remote refreshes require /// [`Table::refresh_column_async_with_options`]. /// /// ``` @@ -2099,17 +2465,66 @@ impl Table { self.inner.refresh_column_async(column.as_ref()).await } + /// Resume a failed Function refresh on this table and its current branch. + /// Returns the successor attempt. Its result includes the published table version. + /// + /// ``` + /// # use lancedb::Table; + /// # async fn resume(table: &Table, failed_job_id: &str) -> lancedb::Result<()> { + /// let job = table.resume_refresh(failed_job_id).await?; + /// let result = job.wait().await?; + /// println!("assigned {} rows", result.rows_assigned); + /// # Ok(()) + /// # } + /// ``` + pub async fn resume_refresh( + &self, + job_id: impl AsRef, + ) -> Result> { + self.inner.resume_refresh(job_id.as_ref()).await + } + /// Like [`Table::refresh_column_async`], with explicit refresh options. /// /// Set [`RefreshColumnOptions::batch_size()`] to cap the rows each remote /// Function call receives, for example to keep slow Functions within the /// executor's per-call deadline. Set - /// [`RefreshColumnOptions::gpu_class()`] and - /// [`RefreshColumnOptions::gpu_count()`] to override the registered GPU - /// class or set an aggregate GPU budget for Function workers. Unset values - /// use the Function and server defaults; zero counts and malformed class - /// names are rejected before submitting a job. Embedded expression - /// refreshes ignore all three options. + /// [`RefreshColumnOptions::publication_interval_rows()`] to publish + /// completed Function outputs at a row-count threshold; unset keeps + /// whole-fragment publication. Set + /// [`RefreshColumnOptions::total_memory_bytes()`] to pass a complete aggregate + /// CPU, memory, and GPU budget for a Function refresh. The standalone + /// [`RefreshColumnOptions::total_gpu_count()`] shorthand and + /// [`RefreshColumnOptions::gpu_class()`] placement remain available; a + /// resource budget cannot be combined with the gpu-count shorthand. Unset + /// values use the Function and server defaults; invalid counts and malformed + /// class names are rejected before submitting a job. Embedded expression + /// refreshes ignore the batch-size and GPU options, and reject resource + /// budgets, publication thresholds, and other Enterprise-only options. + /// + /// Native failed-row retry and upgrades require Enterprise workflow version + /// 1 or later. The SDK checks the server capability before submitting them. + /// An upgrade targets an existing immutable version of the same Function. + /// + /// ``` + /// # use lancedb::{Table, table::RefreshColumnOptions}; + /// use lancedb::function::FunctionRecompute; + /// # async fn retry_and_upgrade(table: &Table) -> lancedb::Result<()> { + /// let retry = table.refresh_column_async_with_options( + /// "embedding", + /// RefreshColumnOptions::default() + /// .retry_errors(true) + /// .retry_error_type("ValueError"), + /// ).await?; + /// retry.wait().await?; + /// let upgrade = table.refresh_column_async_with_options( + /// "embedding", + /// RefreshColumnOptions::default().upgrade("2", FunctionRecompute::Failed), + /// ).await?; + /// upgrade.wait().await?; + /// # Ok(()) + /// # } + /// ``` /// /// ``` /// # use lancedb::{Table, table::RefreshColumnOptions}; @@ -2119,7 +2534,7 @@ impl Table { /// RefreshColumnOptions::default() /// .batch_size(8) /// .gpu_class("a10g") - /// .gpu_count(2), + /// .total_gpu_count(2), /// ).await?; /// let result = job.wait().await?; /// # Ok(()) @@ -2135,12 +2550,89 @@ impl Table { .await } + /// Return exact freshness status for all Function-backed output columns. + /// + /// The server evaluates all counts at one table version. Clients never + /// derive counts by joining schema, Job, and error listings. A handle + /// pinned with `checkout` sends that exact version, while a latest handle + /// keeps the existing read-freshness headers. + pub async fn function_column_statuses( + &self, + column: Option<&str>, + ) -> Result> { + let statuses = self.inner.function_column_statuses(column).await?; + function_column_status::validate_statuses(&statuses)?; + Ok(statuses) + } + + /// Return exact freshness status for one Function-backed output column. + pub async fn function_column_status(&self, column: &str) -> Result { + let mut statuses = self.function_column_statuses(Some(column)).await?; + if statuses.len() != 1 || statuses[0].column != column { + return Err(Error::ColumnNotFound { + name: column.to_string(), + }); + } + Ok(statuses.remove(0)) + } + + /// Poll until a Function output has no stale or never-computed rows. + /// + /// Failed rows do not keep the call pending. A typed + /// `function_column_status_finalization_pending` response is retried with + /// bounded exponential backoff; every other error is returned immediately. + /// Latest handles checkout the current snapshot before each poll so they + /// observe publications that happened after the wait started. Pinned + /// handles keep their explicit version. + pub async fn wait_for_function_column( + &self, + column: &str, + timeout: Option, + ) -> Result { + let started = std::time::Instant::now(); + let mut delay = std::time::Duration::from_millis(250); + loop { + self.inner.checkout_latest_if_latest().await?; + let result = self.function_column_status(column).await; + match result { + Ok(status) if status.stale == 0 && status.never_computed == 0 => return Ok(status), + Ok(_) => {} + Err(error) if function_column_status::is_finalization_pending(&error) => {} + Err(error) => return Err(error), + } + + let sleep_for = match timeout { + Some(timeout) => { + let remaining = timeout.saturating_sub(started.elapsed()); + if remaining.is_zero() { + return Err(Error::Timeout { + message: format!( + "Function column '{column}' did not become fresh before timeout" + ), + }); + } + delay.min(remaining) + } + None => delay, + }; + tokio::time::sleep(sleep_for).await; + delay = std::cmp::min(delay * 2, std::time::Duration::from_secs(1)); + } + } + /// The per-row errors Function refreshes recorded on this table: the /// rows a refresh skipped under its skip policy, with the failing input /// and the error, plus a summary for any fragment whose detail was /// capped. Filter by job or column through the request; a listing that /// hit its limit reports [`FunctionErrors::truncated`]. /// + /// A record carries a stable `row_id` when the refresh source used stable + /// row IDs. Prefer it over the physical `row_address` for retries: + /// compaction and rewrite can change the address. + /// With Enterprise workflow version 1, the default lists current failures; + /// [`FunctionErrorsRequest::history`] selects retained historical attempts. + /// Earlier servers retain their existing default behavior. + /// /// LanceDB Enterprise only, and the caller needs read access /// to the table, since a message carries the value that failed. /// @@ -2165,6 +2657,62 @@ impl Table { self.inner.function_errors(&request).await } + /// Quarantine current failures, or release them with `quarantined=false`. + /// Normal and automatic Function refreshes skip quarantined rows. + /// Requires Enterprise workflow version 1 or later. + /// + /// ``` + /// # use lancedb::Table; + /// use lancedb::function::FunctionQuarantineOptions; + /// # async fn quarantine(table: &Table) -> lancedb::Result<()> { + /// let count = table.quarantine_function_errors( + /// "embedding", + /// FunctionQuarantineOptions { + /// after_attempts: Some(3), + /// ..Default::default() + /// }, + /// ).await?; + /// println!("quarantined {count} rows"); + /// # Ok(()) + /// # } + /// ``` + pub async fn quarantine_function_errors( + &self, + column: &str, + options: crate::function::FunctionQuarantineOptions, + ) -> Result { + self.inner + .quarantine_function_errors(column, &options) + .await + } + + /// Read the producing Function version and job for each returned row. + /// Inspect `truncated` before treating this as a complete snapshot. + /// Requires Enterprise workflow version 1 or later. + /// + /// ``` + /// # use lancedb::Table; + /// use lancedb::function::FunctionProvenanceOptions; + /// # async fn provenance(table: &Table) -> lancedb::Result<()> { + /// let values = table.function_provenance( + /// "embedding", FunctionProvenanceOptions::default(), + /// ).await?; + /// if !values.truncated { + /// for value in values.records { + /// println!("{:?}: {}", value.row_id, value.function_version); + /// } + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn function_provenance( + &self, + column: &str, + options: crate::function::FunctionProvenanceOptions, + ) -> Result { + self.inner.function_provenance(column, &options).await + } + /// Change a column's name, data type, or nullability. /// /// Each alteration must specify at least one of `rename`, `data_type`, or @@ -2330,9 +2878,16 @@ impl Table { /// Merge Enterprise table overrides into the current stored overrides. /// - /// This method uses patch semantics: fields present in `overrides` are - /// recursively merged into the existing table overrides and unrelated fields - /// are preserved. + /// Fetches the current overrides, recursively merges nested objects locally, + /// then sends the complete replacement using REST PUT. Other values replace + /// existing values; unrelated fields from the read snapshot are preserved. + /// This read-modify-write is not atomic: concurrent edits can be overwritten, + /// even to unrelated fields. Coordinate writers when concurrent edits must + /// be preserved. An empty update only reads and returns the current overrides. + /// + /// Unlike this SDK method, CLI `set` and REST PUT replace the overrides object + /// without merging. Use [`Self::reset_table_overrides`] to clear all overrides. + /// Supported only on remote Enterprise tables. pub async fn update_table_overrides( &self, overrides: TableOverrides, @@ -2444,6 +2999,48 @@ impl Table { self.inner.version().await } + /// Compare two persisted versions of this table on its current branch. + /// + /// `from_version` is exclusive and `to_version` is inclusive. Both accept + /// a version number (starting at 1) or a tag on the current branch. + /// Omitting `to_version` uses the version this handle currently sees, + /// including a time-travel [`Self::checkout`]. The endpoints are resolved + /// once when this method is called, so moving a tag or advancing the table + /// later does not change the delta, and the table's own checkout state is + /// left untouched. + /// + /// The returned [`TableDelta`] streams the rows inserted, updated, + /// upserted, or deleted between the endpoints. Those row-level readers + /// require stable row ids at both endpoints; create the table with + /// `storage_options={"new_table_enable_stable_row_ids": "true"}` to enable + /// them. [`TableDelta::list_transactions`] works without stable row ids. + /// Equal valid versions produce empty streams with the same schemas. + /// + /// Reversed ranges, version 0, missing versions or tags, and tags from a + /// different branch are rejected. A row-level range that contains a + /// `Restore`, or whose transaction history is incomplete, is rejected + /// because the restored snapshot can retain older row-version metadata that + /// the delta readers would omit; recompute the checkpoint with a full + /// rescan and reinitialize it at the end version. Remote tables return + /// [`Error::NotSupported`]. + /// + /// ```no_run + /// # use lancedb::table::DeltaRef; + /// # async fn example(table: &lancedb::Table) -> Result<(), Box> { + /// let delta = table.delta(1u64, Some(DeltaRef::Version(table.version().await?))).await?; + /// let _inserted = delta.inserted_rows().await?; + /// let transactions = delta.list_transactions().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn delta( + &self, + from_version: impl Into, + to_version: Option, + ) -> Result { + self.inner.delta(from_version.into(), to_version).await + } + /// Return a new table handle pinned to the exact revision currently visible. /// /// This is used when asynchronous preparation must remain consistent with @@ -2478,6 +3075,10 @@ impl Table { /// Checks out a specific version of the Table by tag /// + /// On Enterprise tables, the tag must belong to this handle's branch. Use + /// [`Self::checkout_branch`] to obtain a handle for another branch first. + /// A failed Enterprise tag checkout leaves the handle unchanged. + /// /// Any read operation on the table will now access the data at the version referenced by the tag. /// As a consequence, calling this method will disable any read consistency interval /// that was previously set. @@ -2741,8 +3342,9 @@ impl Table { /// supported in LanceDB Enterprise. /// /// This call initiates prewarming and returns once the request is accepted. - /// It is idempotent and safe to call from multiple clients concurrently — - /// calling it on already-prewarmed columns is a no-op on the server. + /// Remote tables use SQL PREWARM and require Flight SQL connectivity. + /// Use [`Self::prewarm_data_async`] to retain the durable job handle. + /// Repeated submissions can create distinct jobs; warming cached data is safe. /// /// This operation has a large upfront cost but can speed up future queries /// that need to fetch the given columns. Large columns such as embeddings @@ -2754,6 +3356,64 @@ impl Table { self.inner.prewarm_data(columns).await } + /// Submit a durable data-cache prewarm job through SQL and return when accepted. + /// + /// The handle tracks the warming job, rather than the SQL submission. Use + /// [`Job::wait`] to wait for warming to finish, or save [`Job::id`] and + /// reopen it through [`crate::Connection::open_job`]. A wait timeout or + /// dropping the handle does not cancel the job. Waiting returns the reported + /// [`PrewarmDataResult`]; unavailable measurements remain `None`. + /// + /// Requires a compatible remote server with SQL PREWARM support and Flight + /// SQL connectivity. Under Standard authorization, submission requires + /// Select on the table and Usage on its database and namespace hierarchy. + /// Status and waiting use the generic HTTP job APIs; events and cancellation + /// retain their separate privileges. Unsupported servers are not retried + /// through REST or with requested settings removed. Local tables are unsupported. + /// Historical-version checkouts are unsupported; use `checkout_latest()` first. + /// After [`Job::refresh`], the pinned source version is in [`Job::spec`]. + /// + /// ```no_run + /// # async fn warm(table: &lancedb::Table) -> lancedb::Result<()> { + /// use lancedb::table::PrewarmDataOptions; + /// let job = table.prewarm_data_async(PrewarmDataOptions::new() + /// .columns(["video"]) + /// .filter("quality > 0.7") + /// .concurrency(4)).await?; + /// job.wait().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn prewarm_data_async( + &self, + options: PrewarmDataOptions, + ) -> Result> { + self.inner.prewarm_data_async(options).await + } + + /// Preview data-cache prewarm using the same options as [`Self::prewarm_data_async`]. + /// + /// Requires LanceDB Enterprise with structured SQL PREWARM previews and + /// SELECT permission plus database/namespace usage. Reads metadata without + /// submitting a warming job. A later submission plans its own snapshot. + /// Historical-version and Embedded handles are unsupported. + /// + /// ```no_run + /// # async fn preview(table: &lancedb::Table) -> lancedb::Result<()> { + /// use lancedb::table::PrewarmDataOptions; + /// let plan = table.explain_prewarm_data(PrewarmDataOptions::new() + /// .columns(["video"]).filter("quality > 0.7")).await?; + /// println!("version={}, selected={}", plan.table_version, plan.pruning.selected_fragments); + /// # Ok(()) + /// # } + /// ``` + pub async fn explain_prewarm_data( + &self, + options: PrewarmDataOptions, + ) -> Result { + self.inner.explain_prewarm_data(options).await + } + /// Poll until the columns are fully indexed. Will return Error::Timeout if the columns /// are not fully indexed within the timeout. pub async fn wait_for_index( @@ -2966,6 +3626,43 @@ impl NativeTable { .await } + /// Open a native table at a retained version of the dataset at `uri`. + /// + /// The version is selected during the dataset open. The returned handle is + /// read-only until it checks out the latest version. `params` supplies the + /// session, storage options, and commit handler for the dataset. + /// + /// ``` + /// use lancedb::table::{BaseTable, NativeTable}; + /// + /// async fn count_snapshot(uri: &str, version: u64) -> lancedb::Result { + /// let table = NativeTable::open_at_version(uri, "events", version, Default::default()).await?; + /// let rows = table.count_rows(None).await?; + /// table.checkout_latest().await?; + /// Ok(rows) + /// } + /// ``` + pub async fn open_at_version( + uri: &str, + name: &str, + version: u64, + params: ReadParams, + ) -> Result { + Self::open_native( + uri, + name, + Vec::new(), + None, + Some(params), + None, + None, + HashSet::new(), + None, + Some(version), + ) + .await + } + /// Opens an existing Table /// /// # Arguments @@ -2992,6 +3689,34 @@ impl NativeTable { namespace_client: Option>, pushdown_operations: HashSet, managed_versioning: Option, + ) -> Result { + Self::open_native( + uri, + name, + namespace, + write_store_wrapper, + params, + read_consistency_interval, + namespace_client, + pushdown_operations, + managed_versioning, + None, + ) + .await + } + + #[allow(clippy::too_many_arguments)] + async fn open_native( + uri: &str, + name: &str, + namespace: Vec, + write_store_wrapper: Option>, + params: Option, + read_consistency_interval: Option, + namespace_client: Option>, + pushdown_operations: HashSet, + managed_versioning: Option, + version: Option, ) -> Result { let params = params.unwrap_or_default(); // patch the params if we have a write store wrapper @@ -3030,6 +3755,9 @@ impl NativeTable { }; let mut builder = DatasetBuilder::from_uri(uri).with_read_params(params); + if let Some(version) = version { + builder = builder.with_version(version); + } // Set up commit handler when managed_versioning is enabled if managed_versioning && let Some(ref ns_client) = namespace_client { @@ -3057,9 +3785,12 @@ impl NativeTable { Err(e) => return Err(e.into()), }; - crate::docs::check_table_maintenance_warnings(&dataset, uri).await; - - let dataset = DatasetConsistencyWrapper::new_latest(dataset, read_consistency_interval); + let dataset = if version.is_some() { + DatasetConsistencyWrapper::new_time_travel(dataset, read_consistency_interval) + } else { + crate::docs::check_table_maintenance_warnings(&dataset, uri).await; + DatasetConsistencyWrapper::new_latest(dataset, read_consistency_interval) + }; let id = Self::build_id(&namespace, name); Ok(Self { @@ -3204,7 +3935,7 @@ impl NativeTable { } // patch the params if we have a write store wrapper - let params = match write_store_wrapper.clone() { + let mut params = match write_store_wrapper.clone() { Some(wrapper) => params.patch_with_store_wrapper(wrapper)?, None => params, }; @@ -3215,9 +3946,49 @@ impl NativeTable { // Use DatasetBuilder::from_namespace which automatically fetches location // and storage options from the namespace - let builder = DatasetBuilder::from_namespace(namespace_client.clone(), table_id) - .await - .map_err(|e| map_namespace_lance_error(e, name))?; + let mut builder = + DatasetBuilder::from_namespace(namespace_client.clone(), table_id.clone()) + .await + .map_err(|e| map_namespace_lance_error(e, name))?; + + // A caller-supplied read-params accessor replaces the namespace-backed + // accessor in with_read_params. Preserve an explicit provider/accessor; + // only layer static caller options onto the live namespace provider so + // refresh keeps working and namespace values retain their precedence. + if let Some(mut store_options) = params.store_options.take() { + if let Some(accessor) = store_options.get_accessor() { + if accessor.provider().is_some() { + builder = builder.with_store_params(store_options); + } else { + let caller_options = accessor + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let namespace_provider: Arc = + Arc::new(LanceNamespaceStorageOptionsProvider::new( + namespace_client.clone(), + table_id, + )); + let provider: Arc = + Arc::new(LayeredStorageOptionsProvider::new( + caller_options.clone(), + namespace_provider, + )); + let accessor = if caller_options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + caller_options, + provider, + )) + }; + store_options.storage_options_accessor = Some(accessor); + builder = builder.with_store_params(store_options); + } + } else { + builder = builder.with_store_params(store_options); + } + } let dataset = builder .with_read_params(params) @@ -3310,7 +4081,11 @@ impl NativeTable { namespace_client: Option>, pushdown_operations: HashSet, ) -> Result { - let batches = computed_columns::admit_create_source(batches)?; + let session = params.as_ref().and_then(|p| p.session.as_deref()); + let batches = computed_columns::admit_create_source( + batches, + session.and_then(lance::session::Session::datafusion_session), + )?; // Default params uses format v1. let params = params.unwrap_or(WriteParams { ..Default::default() @@ -3411,16 +4186,20 @@ impl NativeTable { pushdown_operations: HashSet, session: Option>, ) -> Result { - let batches = computed_columns::admit_create_source(batches)?; + let batches = computed_columns::admit_create_source( + batches, + session + .as_deref() + .and_then(lance::session::Session::datafusion_session), + )?; // Build table_id from namespace + name for the storage options provider let mut table_id = namespace.clone(); table_id.push(name.to_string()); // Set up storage options provider from namespace - let storage_options_provider = Arc::new(LanceNamespaceStorageOptionsProvider::new( - namespace_client.clone(), - table_id, - )); + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(namespace_client.clone(), table_id), + ); // Start with provided params or defaults let mut params = params.unwrap_or_default(); @@ -3430,17 +4209,40 @@ impl NativeTable { params.session = Some(sess); } - // Ensure store_params exists and set the storage options provider + // Ensure store_params exists and preserve an already-layered provider + // from create_table, or attach the namespace provider to the caller's + // initial options for other callers. let store_params = params .store_params .get_or_insert_with(ObjectStoreParams::default); - let accessor = match store_params.storage_options().cloned() { - Some(options) => { - StorageOptionsAccessor::with_initial_and_provider(options, storage_options_provider) + let accessor = match store_params.storage_options_accessor.take() { + Some(existing) + if existing.provider().is_some() + && existing.initial_storage_options().is_some() => + { + existing } - None => StorageOptionsAccessor::with_provider(storage_options_provider), + Some(existing) => { + let options = existing + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(options.clone(), namespace_provider), + ); + if options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + options, provider, + )) + } + } + None => Arc::new(StorageOptionsAccessor::with_provider(Arc::new( + LayeredStorageOptionsProvider::new(HashMap::new(), namespace_provider), + ))), }; - store_params.storage_options_accessor = Some(Arc::new(accessor)); + store_params.storage_options_accessor = Some(accessor); // Patch the params if we have a write store wrapper let params = match write_store_wrapper.clone() { @@ -3624,10 +4426,18 @@ impl BaseTable for NativeTable { self } - /// Lance scans fragments in order (`Scanner::ordered` defaults to true, and we - /// never clear it), so repeated identical scans agree. + /// Lance scans fragments in order at one dataset version (`Scanner::ordered` + /// defaults to true, and we never clear it), so repeated scans of a local + /// handle agree. A main/latest handle that may push its query to a namespace + /// server does not: the QueryTable request carries no order. fn scan_order_is_deterministic(&self) -> bool { - true + let may_push_down_namespace_query = self.namespace_client.is_some() + && self + .pushdown_operations + .contains(&NamespaceClientPushdownOperation::QueryTable) + && self.dataset.current_branch().is_none() + && self.dataset.time_travel_version().is_none(); + !may_push_down_namespace_query } fn name(&self) -> &str { @@ -3657,6 +4467,15 @@ impl BaseTable for NativeTable { Ok(self.dataset.get().await?.version().version) } + async fn delta( + &self, + from_version: DeltaRef, + to_version: Option, + ) -> Result { + let visible = self.dataset.get().await?; + TableDelta::from_visible_snapshot(&visible, from_version, to_version).await + } + async fn checkout_current(&self) -> Result> { let current = self.dataset.get().await?; let dataset = dataset::DatasetConsistencyWrapper::new_time_travel( @@ -3669,6 +4488,14 @@ impl BaseTable for NativeTable { })) } + async fn snapshot_at_current_version(&self) -> Result>> { + // A native handle can advance between requests when read consistency + // refreshes, and a namespace-backed handle can answer a query from a + // different snapshot than the local count/version. Hand the caller an + // independent time-travel handle so one build sees one dataset. + Ok(Some(self.checkout_current().await?)) + } + async fn checkout(&self, version: u64) -> Result<()> { self.dataset.as_time_travel(version).await } @@ -3908,14 +4735,18 @@ impl BaseTable for NativeTable { } async fn create_index(&self, opts: IndexBuilder) -> Result<()> { - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(()); + }; self.build_index(opts, prepared).await } async fn create_index_async(&self, opts: IndexBuilder) -> Result { // Prepare before spawning so bad input is reported by this call rather // than only by the job. - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(Job::new_done()); + }; let table = self.clone(); Ok(Job::spawned(tokio::spawn(async move { table.build_index(opts, prepared).await @@ -3978,6 +4809,7 @@ impl BaseTable for NativeTable { params: MergeInsertBuilder, new_data: Box, ) -> Result { + self.dataset.ensure_mutable()?; let source_schema = arrow_array::RecordBatchReader::schema(&new_data); self.ensure_not_a_view("merge insert into").await?; computed_columns::ensure_not_written( @@ -4556,6 +5388,41 @@ mod tests { assert_eq!(table.name, "test") } + #[tokio::test] + async fn opens_a_retained_native_version_with_an_unreadable_latest_manifest() { + let dir = tempdir().unwrap(); + let path = dir.path().join("events.lance"); + let uri = path.to_str().unwrap(); + let batch = make_test_batches(); + let rows = batch.num_rows(); + let mut dataset = Dataset::write( + RecordBatchIterator::new([Ok(batch.clone())], batch.schema()), + uri, + None, + ) + .await + .unwrap(); + let retained = dataset.version().version; + dataset + .append( + RecordBatchIterator::new([Ok(batch.clone())], batch.schema()), + None, + ) + .await + .unwrap(); + assert_eq!(dataset.count_rows(None).await.unwrap(), rows * 2); + let latest = dataset.manifest_location().path.filename().unwrap(); + std::fs::write(path.join("_versions").join(latest), b"unreadable manifest").unwrap(); + assert!(NativeTable::open(uri).await.is_err()); + + let pinned = NativeTable::open_at_version(uri, "events", retained, ReadParams::default()) + .await + .unwrap(); + assert_eq!(pinned.version().await.unwrap(), retained); + assert_eq!(pinned.count_rows(None).await.unwrap(), rows); + assert!(pinned.dataset.ensure_mutable().is_err()); + } + /// The per-row error store is a server feature; a LanceDB Embedded table says so /// rather than answering with an empty listing. #[tokio::test] @@ -5264,6 +6131,22 @@ mod tests { // a pinned version is a detached head: writes are rejected assert!(pinned.add(sample_rows(vec![9])).execute().await.is_err()); + let exp_head = head.version().await.unwrap(); + for pinned_table in [&pinned, &pinned_direct] { + let mut merge = pinned_table.merge_insert(&["i"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let err = merge.execute(sample_rows(vec![300])).await.unwrap_err(); + assert!(matches!(err, Error::InvalidInput { message } + if message == "table cannot be modified when a specific version is checked out")); + assert_eq!(pinned_table.version().await.unwrap(), exp_v2); + assert_eq!(pinned_table.count_rows(None).await.unwrap(), 2); + } + assert_eq!(head.version().await.unwrap(), exp_head); + assert_eq!(head.count_rows(None).await.unwrap(), 3); + assert_eq!(table.version().await.unwrap(), main_v2); + assert_eq!(table.count_rows(None).await.unwrap(), 4); // version-only (no branch) time-travels main itself: its fork-point // version holds only main's first row, and the shared version number @@ -5362,6 +6245,60 @@ mod tests { assert_eq!(at2.count_rows(Some("i = 10".to_string())).await.unwrap(), 0); } + #[tokio::test] + async fn test_create_branch_from_tag_on_branch_with_same_version_as_main() { + let tmp_dir = tempdir().unwrap(); + let uri = tmp_dir.path().to_str().unwrap(); + let conn = ConnectBuilder::new(uri) + .read_consistency_interval(Duration::from_secs(0)) + .execute() + .await + .unwrap(); + + let table = conn + .create_table("my_table", sample_rows(vec![0])) + .execute() + .await + .unwrap(); + let fork_point = table.version().await.unwrap(); + + // Advance exp and main to the same version number with different rows. + let exp = table.create_branch("exp", fork_point).await.unwrap(); + exp.add(sample_rows(vec![10])).execute().await.unwrap(); + let exp_version = exp.version().await.unwrap(); + table.add(sample_rows(vec![100])).execute().await.unwrap(); + assert_eq!(exp_version, table.version().await.unwrap()); + + // Tag exp at that shared version number. The tag must keep exp's branch + // identity, so forking from it sees exp's snapshot rather than main's + // version with the same number. + let mut tags = exp.tags().await.unwrap(); + tags.create("exp-v2", exp_version).await.unwrap(); + + let from_tag = table + .create_branch( + "from-tag", + lance::dataset::refs::Ref::Tag("exp-v2".to_string()), + ) + .await + .unwrap(); + assert_eq!(from_tag.current_branch().as_deref(), Some("from-tag")); + assert_eq!( + from_tag + .count_rows(Some("i = 10".to_string())) + .await + .unwrap(), + 1 + ); + assert_eq!( + from_tag + .count_rows(Some("i = 100".to_string())) + .await + .unwrap(), + 0 + ); + } + #[tokio::test] async fn test_branch_name_validation() { let tmp_dir = tempdir().unwrap(); @@ -5595,8 +6532,35 @@ mod tests { .unwrap(); let version = table.version().await.unwrap(); table.add(some_sample_data()).execute().await.unwrap(); + let latest_version = table.version().await.unwrap(); + let opened = conn + .open_table("my_table") + .version(version) + .execute() + .await + .unwrap(); table.checkout(version).await.unwrap(); - assert!(table.add(some_sample_data()).execute().await.is_err()) + assert!(table.add(some_sample_data()).execute().await.is_err()); + for pinned_table in [&table, &opened] { + let mut merge = pinned_table.merge_insert(&["i"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let err = merge.execute(sample_rows(vec![300])).await.unwrap_err(); + assert!(matches!(err, Error::InvalidInput { message } + if message == "table cannot be modified when a specific version is checked out")); + assert_eq!(pinned_table.version().await.unwrap(), version); + assert_eq!(pinned_table.count_rows(None).await.unwrap(), 1); + } + + table.checkout_latest().await.unwrap(); + assert_eq!(table.version().await.unwrap(), latest_version); + assert_eq!(table.count_rows(None).await.unwrap(), 2); + let mut merge = table.merge_insert(&["i"]); + merge.when_not_matched_insert_all(); + let result = merge.execute(sample_rows(vec![300])).await.unwrap(); + assert_eq!(result.num_inserted_rows, 1); + assert_eq!(table.count_rows(None).await.unwrap(), 3); } #[tokio::test] diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index be319a8be..012eb7d98 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -18,7 +18,7 @@ pub struct AddColumnsBuilder { parent: Arc, transform: Option, computed: Vec<(String, String)>, - function: Option<(FunctionApplication, Option)>, + functions: Vec<(FunctionApplication, Option)>, read_columns: Option>, options: Option, } @@ -29,7 +29,7 @@ impl std::fmt::Debug for AddColumnsBuilder { .field("parent", &self.parent) .field("has_transform", &self.transform.is_some()) .field("computed", &self.computed) - .field("has_function", &self.function.is_some()) + .field("function_count", &self.functions.len()) .field("read_columns", &self.read_columns) .finish() } @@ -41,7 +41,7 @@ impl AddColumnsBuilder { parent, transform: None, computed: Vec::new(), - function: None, + functions: Vec::new(), read_columns: None, options: None, } @@ -89,6 +89,30 @@ impl AddColumnsBuilder { /// # Ok(()) /// # } /// ``` + /// + /// In LanceDB Embedded, an expression can also call functions registered + /// on a DataFusion `SessionContext` attached to the connection's Lance + /// session. They are not stored with the table, so attach them on every + /// connection that opens it. + /// + /// ```no_run + /// # use std::sync::Arc; + /// # use datafusion::execution::context::SessionContext; + /// # use datafusion::logical_expr::ScalarUDF; + /// # async fn declare(my_udf: ScalarUDF) -> Result<(), Box> { + /// let functions = SessionContext::new(); + /// functions.register_udf(my_udf); + /// let session = lance::session::Session::default().with_datafusion_session(functions); + /// let db = lancedb::connect("data/db") + /// .session(Arc::new(session)) + /// .execute() + /// .await?; + /// let table = db.open_table("t").execute().await?; + /// table.add_columns().computed("y", "my_udf(x)").execute().await?; + /// table.refresh_column("y").await?; + /// # Ok(()) + /// # } + /// ``` pub fn computed(mut self, name: impl Into, expression: impl Into) -> Self { self.computed.push((name.into(), expression.into())); self @@ -107,7 +131,7 @@ impl AddColumnsBuilder { /// # } /// ``` pub fn function(mut self, application: FunctionApplication) -> Self { - self.function = Some((application, None)); + self.functions = vec![(application, None)]; self } @@ -132,7 +156,19 @@ impl AddColumnsBuilder { name: impl Into, application: FunctionApplication, ) -> Self { - self.function = Some((application, Some(name.into()))); + self.functions = vec![(application, Some(name.into()))]; + self + } + + /// Declare several registered Function bindings in one Enterprise schema commit. + /// Pass a destination name for a scalar or whole struct result. Use `None` + /// to expand a named struct into its ordered fields. Inputs may reference + /// other outputs in this declaration, regardless of their order. + pub fn function_bindings( + mut self, + bindings: impl IntoIterator)>, + ) -> Self { + self.functions = bindings.into_iter().collect(); self } @@ -147,15 +183,22 @@ impl AddColumnsBuilder { /// Configure automatic refresh for every output declared in this call. /// Settings are stored with the declaration. They require computed or - /// Function columns; LanceDB Embedded persists them without starting a scheduler. + /// Function columns. LanceDB Embedded persists enabled and interval settings + /// without starting a scheduler; an automatic resource budget requires an + /// Enterprise registered Function and rejects SQL-expression columns. /// /// ``` /// # use lancedb::{Table, table::computed_columns::ComputedColumnOptions}; /// # async fn declare(table: &Table) -> lancedb::Result<()> { /// table.add_columns().computed("doubled", "x * 2") /// .computed_options(ComputedColumnOptions { + /// gpu_class: Default::default(), + /// gpu_count: Default::default(), /// auto_refresh_enabled: true, /// auto_refresh_interval_seconds: Some(300), + /// total_cpu_millis: None, + /// total_memory_bytes: None, + /// total_gpu_count: None, /// }).execute().await?; /// # Ok(()) /// # } @@ -171,22 +214,28 @@ impl AddColumnsBuilder { parent, transform, computed, - function, + functions, read_columns, options, } = self; - if let Some(options) = options { + if let Some(options) = &options { options.validate()?; - if computed.is_empty() && function.is_none() { + if computed.is_empty() && functions.is_empty() { return Err(Error::InvalidInput { message: "automatic refresh options require computed or Function columns" .into(), }); } + if options.has_resource_defaults() && functions.is_empty() { + return Err(Error::InvalidInput { + message: "total_* resources require a registered Function declaration".into(), + }); + } } let options = options.unwrap_or_default(); - let declaration_count = usize::from(!computed.is_empty()) + usize::from(function.is_some()); + let declaration_count = + usize::from(!computed.is_empty()) + usize::from(!functions.is_empty()); if transform.is_some() && declaration_count != 0 || declaration_count > 1 { return Err(Error::InvalidInput { message: "add_columns cannot mix transforms, SQL computed columns, and a Function application; they cannot be added atomically in one call" @@ -194,11 +243,11 @@ impl AddColumnsBuilder { }); } - match (transform, computed.is_empty(), function) { - (None, true, None) => Err(Error::InvalidInput { + match (transform, computed.is_empty(), functions.as_slice()) { + (None, true, []) => Err(Error::InvalidInput { message: "add_columns requires a transform or a computed column".into(), }), - (Some(transform), true, None) => { + (Some(transform), true, []) => { if read_columns.is_some() && !matches!(transform, NewColumnTransform::BatchUDF(_)) { return Err(Error::InvalidInput { message: "read_columns applies only to a BatchUDF transform; \ @@ -208,7 +257,7 @@ impl AddColumnsBuilder { } parent.add_columns(transform, read_columns).await } - (None, false, None) => { + (None, false, []) => { if read_columns.is_some() { return Err(Error::InvalidInput { message: "read_columns applies only to a BatchUDF transform; \ @@ -218,16 +267,21 @@ impl AddColumnsBuilder { } parent.add_computed_columns(&computed, options).await } - (None, true, Some((application, output_name))) => { + (None, true, bindings) => { if read_columns.is_some() { return Err(Error::InvalidInput { message: "read_columns does not apply to a Function application; its inputs are already bound" .into(), }); } - parent - .add_function_columns(&application, output_name.as_deref(), options) - .await + match bindings { + [(application, name)] => { + parent + .add_function_columns(application, name.as_deref(), options) + .await + } + _ => parent.add_function_bindings(bindings, options).await, + } } _ => unreachable!("mixed add_columns modes were rejected above"), } @@ -263,13 +317,18 @@ mod tests { let table = table_with_two_columns("options").await; let version = table.version().await.unwrap(); let options = ComputedColumnOptions { + gpu_class: Default::default(), + gpu_count: Default::default(), auto_refresh_enabled: false, auto_refresh_interval_seconds: Some(300), + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, }; let result = table .add_columns() .computed("doubled", "x * 2") - .computed_options(options) + .computed_options(options.clone()) .execute() .await .unwrap(); @@ -285,7 +344,7 @@ mod tests { for interval in [0, u64::MAX] { let invalid = ComputedColumnOptions { auto_refresh_interval_seconds: Some(interval), - ..options + ..options.clone() }; assert!( table @@ -304,7 +363,7 @@ mod tests { "once".into(), "x".into() )])) - .computed_options(options) + .computed_options(options.clone()) .execute() .await .is_err() @@ -349,6 +408,38 @@ mod tests { ); } + #[tokio::test] + async fn auto_refresh_resource_budget_requires_a_function() { + let table = table_with_two_columns("budget_expression").await; + let err = table + .add_columns() + .computed("doubled", "x * 2") + .computed_options(ComputedColumnOptions { + gpu_class: Default::default(), + gpu_count: Default::default(), + auto_refresh_enabled: true, + auto_refresh_interval_seconds: None, + total_cpu_millis: Some(1000), + total_memory_bytes: Some(1024), + total_gpu_count: Some(0), + }) + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("registered Function")), + "{err:?}" + ); + assert!( + table + .schema() + .await + .unwrap() + .field_with_name("doubled") + .is_err() + ); + } + #[tokio::test] async fn test_requires_a_transform() { let table = table_with_two_columns("no_transform").await; diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index 8c5dc4b45..d6323449d 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -65,6 +65,7 @@ pub struct AddDataBuilder { pub(crate) progress_callback: Option, pub(crate) write_parallelism: Option, pub(crate) allow_external_blob_outside_bases: bool, + pub(crate) retries: Option, } impl std::fmt::Debug for AddDataBuilder { @@ -93,9 +94,18 @@ impl AddDataBuilder { progress_callback: None, write_parallelism: None, allow_external_blob_outside_bases: false, + retries: None, } } + /// Override the remote retry budget for this call. `0` disables retries, + /// including retries of idempotent multipart parts. Ambiguous commits are + /// never replayed, regardless of this setting. Ignored by embedded tables. + pub fn retries(mut self, retries: u8) -> Self { + self.retries = Some(retries); + self + } + pub fn mode(mut self, mode: AddDataMode) -> Self { self.mode = mode; self @@ -217,6 +227,7 @@ impl AddDataBuilder { mode: self.mode, tracker, allow_external_blob_outside_bases: self.allow_external_blob_outside_bases, + retries: self.retries, }) } } @@ -231,6 +242,7 @@ pub struct PreprocessingOutput { pub mode: AddDataMode, pub tracker: Option>, pub allow_external_blob_outside_bases: bool, + pub retries: Option, } /// Check that the input schema is valid for insert. diff --git a/rust/lancedb/src/table/cleanup.rs b/rust/lancedb/src/table/cleanup.rs new file mode 100644 index 000000000..8d4eb67e6 --- /dev/null +++ b/rust/lancedb/src/table/cleanup.rs @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Options and results for durable remote version cleanup. + +/// Per-invocation retention. Omission inherits table/branch then deployment policy. +#[derive(Debug, Clone, Default)] +#[non_exhaustive] +pub struct CleanupOptions { + /// Minimum old-version age in seconds. None inherits server policy. + pub min_age_seconds: Option, +} + +impl CleanupOptions { + /// Inherit selected table/branch and deployment retention. + pub fn new() -> Self { + Self::default() + } + + /// Set the minimum old-version age in seconds; zero is explicit, not omitted. + pub fn min_age_seconds(mut self, seconds: u64) -> Self { + self.min_age_seconds = Some(seconds); + self + } +} + +/// Successful remote version cleanup. Auxiliary sweeps are best effort and +/// excluded from the counts. Retry/recovery can leave counts unknown (`None`). +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(try_from = "CleanupResultWire")] +#[non_exhaustive] +pub struct CleanupResult { + /// Objects that could not be deleted, if measured. Other removals remain committed. + pub failed_deletes: Option, + /// Public result schema version; currently 1. + pub format_version: u32, + /// Retention resolved and recorded when the server accepted this job. + pub min_age_seconds: u64, + /// Whether the entire invocation's version-deletion counts are known. + pub statistics_complete: bool, + /// Old versions removed, or None after uncertain retry/recovery. + pub old_versions: Option, + /// Bytes removed by version deletion, excluding auxiliary sweeps. + pub bytes_removed: Option, +} + +#[derive(serde::Deserialize)] +struct CleanupResultWire { + failed_deletes: Option, + format_version: u32, + min_age_seconds: u64, + statistics_complete: bool, + old_versions: Option, + bytes_removed: Option, +} + +impl TryFrom for CleanupResult { + type Error = &'static str; + fn try_from(value: CleanupResultWire) -> std::result::Result { + if value.format_version != 1 + || if value.statistics_complete { + value.old_versions.is_none() || value.bytes_removed.is_none() + } else { + value.old_versions.is_some() + || value.bytes_removed.is_some() + || value.failed_deletes.is_some() + } + { + return Err("unsupported or inconsistent cleanup result"); + } + Ok(Self { + failed_deletes: value.failed_deletes, + format_version: value.format_version, + min_age_seconds: value.min_age_seconds, + statistics_complete: value.statistics_complete, + old_versions: value.old_versions, + bytes_removed: value.bytes_removed, + }) + } +} + +/// Read-only version-deletion estimate. Execution re-evaluates current state; +/// no job or deletion snapshot is reserved and auxiliary sweeps are excluded. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct CleanupPlan { + #[serde(deserialize_with = "preview_version")] + pub format_version: u32, + pub source_version: u64, + pub min_age_seconds: u64, + pub cutoff_millis: i64, + pub versions_to_remove: u64, + pub bytes_to_remove: u64, +} + +fn preview_version<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + let version = ::deserialize(deserializer)?; + if version != 1 { + return Err(serde::de::Error::custom( + "unsupported cleanup preview format", + )); + } + Ok(version) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleanup_result_distinguishes_known_zero_unknown_and_invalid() { + let mut value = serde_json::json!({"format_version":1,"min_age_seconds":0, + "statistics_complete":true,"old_versions":0,"bytes_removed":0,"future":true}); + assert_eq!( + serde_json::from_value::(value.clone()) + .unwrap() + .old_versions, + Some(0) + ); + value["statistics_complete"] = false.into(); + assert!(serde_json::from_value::(value.clone()).is_err()); + value["old_versions"] = serde_json::Value::Null; + value["bytes_removed"] = serde_json::Value::Null; + assert_eq!( + serde_json::from_value::(value.clone()) + .unwrap() + .old_versions, + None + ); + value["format_version"] = 2.into(); + assert!(serde_json::from_value::(value).is_err()); + } +} diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 0e02e7ce2..108101b5b 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; use arrow_schema::{DataType, Field as ArrowField, Fields, Schema as ArrowSchema, SchemaRef}; +use datafusion::execution::context::SessionContext; use datafusion_common::{ScalarValue, tree_node::TreeNode}; use datafusion_expr::Expr; use datafusion_physical_plan::PhysicalExpr; @@ -39,7 +40,8 @@ use lance_namespace::models::{JsonArrowDataType, JsonArrowField, JsonArrowSchema use serde::{Deserialize, Serialize}; use serde_json::Value; -use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding}; +use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding, OutputMapping}; +use crate::materialized_view::without_declarations; use crate::utils::resolve_arrow_field_path; use crate::{Error, Result}; @@ -59,10 +61,9 @@ pub const INPUTS_META_KEY: &str = "computed_column.inputs"; pub const AUTO_REFRESH_ENABLED_META_KEY: &str = "computed_column.auto_refresh_enabled"; /// Minimum interval between successful automatic refreshes, in seconds. pub const AUTO_REFRESH_INTERVAL_META_KEY: &str = "computed_column.auto_refresh_interval_seconds"; - /// Scheduling settings persisted on each computed output. LanceDB Embedded /// stores these settings; automatic scheduling requires LanceDB Enterprise. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct ComputedColumnOptions { /// Permit automatic refresh. Manual refresh is always available. @@ -71,6 +72,22 @@ pub struct ComputedColumnOptions { /// When omitted, the server determines when to refresh. #[serde(skip_serializing_if = "Option::is_none")] pub auto_refresh_interval_seconds: Option, + /// Default total CPU budget in millicores for manual and automatic refreshes. + /// Requires a registered Function output. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_cpu_millis: Option, + /// Default total memory budget in bytes for manual and automatic refreshes. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_memory_bytes: Option, + /// Default total GPU budget for manual and automatic refreshes. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_gpu_count: Option, + /// GPU pool used by each Function worker unless overridden at refresh. + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu_class: Option, + /// Positive number of GPUs per worker, independent of the total budget. + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu_count: Option, } impl Default for ComputedColumnOptions { @@ -78,11 +95,24 @@ impl Default for ComputedColumnOptions { Self { auto_refresh_enabled: true, auto_refresh_interval_seconds: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + gpu_class: None, + gpu_count: None, } } } impl ComputedColumnOptions { + pub fn has_resource_defaults(&self) -> bool { + self.total_cpu_millis.is_some() + || self.total_memory_bytes.is_some() + || self.total_gpu_count.is_some() + || self.gpu_class.is_some() + || self.gpu_count.is_some() + } + /// Reject intervals that cannot be represented by the server scheduler. pub fn validate(&self) -> Result<()> { if self @@ -93,6 +123,29 @@ impl ComputedColumnOptions { message: "auto_refresh_interval_seconds must be a positive integer no greater than u64::MAX / 1000".into(), }); } + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { + return Err(Error::InvalidInput { + message: "total_cpu_millis and total_memory_bytes must be positive integers".into(), + }); + } + if let Some(class) = &self.gpu_class { + crate::function::validate_gpu_class_name(class)?; + } + if self.gpu_count == Some(0) { + return Err(Error::InvalidInput { + message: "gpu_count must be positive".into(), + }); + } + if self + .gpu_count + .zip(self.total_gpu_count) + .is_some_and(|(per_worker, total)| per_worker > total) + || (self.gpu_class.is_some() && self.total_gpu_count == Some(0)) + { + return Err(Error::InvalidInput { + message: "total_gpu_count cannot fit one Function worker".into(), + }); + } Ok(()) } @@ -110,6 +163,29 @@ impl ComputedColumnOptions { message: "auto_refresh_interval_seconds must be a positive integer".into(), })?); } + if let Some(value) = metadata.get("computed_column.total_cpu_millis") { + options.total_cpu_millis = Some(value.parse().map_err(|_| Error::InvalidInput { + message: "invalid total_cpu_millis".into(), + })?); + } + if let Some(value) = metadata.get("computed_column.total_memory_bytes") { + options.total_memory_bytes = Some(value.parse().map_err(|_| Error::InvalidInput { + message: "invalid total_memory_bytes".into(), + })?); + } + if let Some(value) = metadata.get("computed_column.total_gpu_count") { + options.total_gpu_count = Some(value.parse().map_err(|_| Error::InvalidInput { + message: "invalid total_gpu_count".into(), + })?); + } + options.gpu_class = metadata.get("computed_column.gpu_class").cloned(); + options.gpu_count = metadata + .get("computed_column.gpu_count") + .map(|value| value.parse()) + .transpose() + .map_err(|_| Error::InvalidInput { + message: "invalid gpu_count".into(), + })?; options.validate()?; Ok(options) } @@ -117,6 +193,7 @@ impl ComputedColumnOptions { /// Attach validated settings to newly declared computed output fields. pub fn apply_to_schema(&self, schema: &ArrowSchema) -> Result { self.validate()?; + let option_metadata = self.metadata()?; let fields = schema .fields() .iter() @@ -132,7 +209,7 @@ impl ComputedColumnOptions { return field.clone(); } let mut metadata = field.metadata().clone(); - metadata.extend(self.metadata()); + metadata.extend(option_metadata.clone()); Arc::new(field.as_ref().clone().with_metadata(metadata)) }) .collect::>(); @@ -143,7 +220,7 @@ impl ComputedColumnOptions { } /// Field metadata values shared by native and server declaration paths. - pub fn metadata(&self) -> HashMap { + pub fn metadata(&self) -> Result> { let mut metadata = HashMap::from([( AUTO_REFRESH_ENABLED_META_KEY.into(), self.auto_refresh_enabled.to_string(), @@ -151,7 +228,22 @@ impl ComputedColumnOptions { if let Some(interval) = self.auto_refresh_interval_seconds { metadata.insert(AUTO_REFRESH_INTERVAL_META_KEY.into(), interval.to_string()); } - metadata + for (key, value) in [ + ("total_cpu_millis", self.total_cpu_millis), + ("total_memory_bytes", self.total_memory_bytes), + ("total_gpu_count", self.total_gpu_count.map(u64::from)), + ] { + if let Some(value) = value { + metadata.insert(format!("computed_column.{key}"), value.to_string()); + } + } + if let Some(class) = &self.gpu_class { + metadata.insert("computed_column.gpu_class".into(), class.clone()); + } + if let Some(count) = self.gpu_count { + metadata.insert("computed_column.gpu_count".into(), count.to_string()); + } + Ok(metadata) } } @@ -171,6 +263,10 @@ pub const FUNCTION_BINDINGS_META_KEY: &str = "lancedb::function_bindings"; /// Version of the schema-level Function binding envelope. pub const FUNCTION_BINDINGS_VERSION: u32 = 1; +/// Envelope version required when a Function binding contains constant inputs. +/// Older readers reject this version instead of dropping those inputs. +pub const FUNCTION_LITERAL_BINDINGS_VERSION: u32 = 2; + /// Field metadata key holding `{fragment id -> input signature}` as JSON, /// recorded by the refresh that last computed each fragment. Outside the /// declaration namespace on purpose: a declaration is immutable through @@ -179,6 +275,11 @@ pub const FUNCTION_BINDINGS_VERSION: u32 = 1; /// declared before signatures existed. pub const SOURCE_SIGNATURE_META_KEY: &str = "computed_refresh.source_signature"; +/// Signatures of input-preserving rewrites whose retained Function outputs +/// are current but whose inserted rows still need their first computation. +/// A sidecar reference keeps this separate from completed freshness stamps. +pub const PENDING_FILL_SIGNATURE_META_KEY: &str = "computed_refresh.pending_fill_signature"; + /// Field metadata key holding the definition digest a column was last /// computed under. A change to it makes every row stale. pub const DEFINITION_VERSION_META_KEY: &str = "computed_refresh.definition_version"; @@ -292,6 +393,17 @@ struct FunctionBindingEnvelope { /// Encode immutable Function bindings for schema-level persistence. pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result { + bindings + .iter() + .try_for_each(FunctionBinding::validate_inputs)?; + let version = if bindings + .iter() + .any(|binding| !binding.literal_inputs().is_empty()) + { + FUNCTION_LITERAL_BINDINGS_VERSION + } else { + FUNCTION_BINDINGS_VERSION + }; let bindings = bindings .iter() .map(serde_json::to_value) @@ -299,12 +411,10 @@ pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result Result> { .bindings .into_iter() .map(|binding| { - serde_json::from_value(binding).map_err(|e| Error::InvalidInput { - message: format!("invalid Function binding metadata: {e}"), - }) + let binding: FunctionBinding = + serde_json::from_value(binding).map_err(|e| Error::InvalidInput { + message: format!("invalid Function binding metadata: {e}"), + })?; + binding.validate_inputs()?; + Ok(binding) }) .collect() } @@ -333,7 +446,10 @@ fn function_binding_envelope(schema: &ArrowSchema) -> Result Result Result .collect::>>()?; let mut binding_ids = BTreeSet::new(); for binding in &bindings { + binding.validate_inputs()?; if !binding_ids.insert(binding.binding_id().to_string()) { return Err(Error::InvalidInput { message: format!("duplicate Function binding '{}'", binding.binding_id()), @@ -784,6 +913,7 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { "binding_id", "function", "inputs", + "literal_inputs", "outputs", "assignment", "input_schema", @@ -793,6 +923,14 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { "binding", )?; let object = value.as_object().unwrap(); + if let Some(inputs) = object.get("literal_inputs") { + for input in inputs + .as_array() + .ok_or_else(|| invalid_function("Function literal_inputs must be an array"))? + { + reject_unknown_object_fields(input, &["parameter", "value"], "literal input binding")?; + } + } reject_unknown_object_fields( object .get("function") @@ -1252,7 +1390,23 @@ fn function_output_type_matches(expected: &DataType, actual: &DataType) -> bool } } +/// Whether a whole-result binding may carry the server-owned assignment marker. +/// +/// Only a nullable scalar result needs a marker to distinguish a computed NULL +/// from an unfilled row. A non-nullable result, a whole named-struct column, +/// and a Blob v2 value keep their existing rejection. +fn nullable_scalar_allows_assignment(output: &OutputMapping) -> Result { + if !output.nullable || output.arrow_type == FUNCTION_BLOB_V2_TYPE { + return Ok(false); + } + let json = parse_output_arrow_type(&output.arrow_type)?; + let data_type = lance_namespace::schema::convert_json_arrow_type(&json) + .map_err(|e| invalid_function(format!("invalid Function output type: {e}")))?; + Ok(!matches!(data_type, DataType::Struct(_))) +} + fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding) -> Result<()> { + binding.validate_inputs()?; let mut input_fields = Vec::with_capacity(binding.inputs().len()); for input in binding.inputs() { let resolved = resolve_field_path(schema, &input.field_path)?; @@ -1298,6 +1452,52 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding } input_fields.push(parameter_field); } + if !binding.literal_inputs().is_empty() { + // Column types still come from the table. Literal types come from the + // complete signature schema persisted by the Enterprise service. + let declared: JsonArrowSchema = + serde_json::from_value(binding.input_schema().cloned().ok_or_else(|| { + invalid_function("literal Function binding requires an input schema") + })?) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + let mut columns = input_fields + .into_iter() + .map(|field| (field.name().clone(), field)) + .collect::>(); + let mut literals = binding + .literal_inputs() + .iter() + .map(|input| (input.parameter.as_str(), &input.value)) + .collect::>(); + input_fields = Vec::with_capacity(declared.fields.len()); + for field in &declared.fields { + if let Some(column) = columns.remove(&field.name) { + input_fields.push(column); + } else if let Some(value) = literals.remove(field.name.as_str()) { + let field = + lance_namespace::schema::convert_json_arrow_field(field).map_err(|e| { + invalid_function(format!("invalid Function literal field: {e}")) + })?; + if field.is_blob_v2() || (value.is_null() && !field.is_nullable()) { + return Err(invalid_function(format!( + "invalid literal for Function parameter '{}'", + field.name() + ))); + } + input_fields.push(field); + } else { + return Err(invalid_function(format!( + "Function input schema has an unknown or duplicate parameter '{}'", + field.name + ))); + } + } + if !columns.is_empty() || !literals.is_empty() { + return Err(invalid_function( + "Function input schema is missing bound parameters", + )); + } + } let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(input_fields)) .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; @@ -1382,13 +1582,14 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding } let mut declared_output_schema = binding.output_schema().cloned(); if let Some(assignment) = binding.assignment() { - if binding + if let Some(whole_result) = binding .outputs() .iter() - .any(|output| output.result_field == WHOLE_RESULT_FIELD) + .find(|output| output.result_field == WHOLE_RESULT_FIELD) + && (binding.outputs().len() != 1 || !nullable_scalar_allows_assignment(whole_result)?) { return Err(invalid_function(format!( - "Function binding '{}' cannot attach an assignment column to a whole result", + "Function binding '{}' cannot attach an assignment column to a whole result; only a single nullable scalar output permits one", binding.binding_id() ))); } @@ -1428,6 +1629,56 @@ pub(crate) fn plan_function_application( output_name: Option<&str>, ) -> Result { ensure_supported_function_metadata(schema)?; + let (outputs, output_schema) = plan_function_outputs(schema, application, output_name)?; + plan_function_inputs(schema, &HashSet::new(), application, outputs, output_schema) +} + +/// All output types are known from the registered signatures. Resolve inputs +/// against the complete set so an application can read a later sibling. +pub(crate) fn plan_function_bindings( + schema: &ArrowSchema, + bindings: &[(FunctionApplication, Option)], +) -> Result> { + ensure_supported_function_metadata(schema)?; + let mut fields = schema.fields().to_vec(); + let mut destinations = HashSet::new(); + let mut plans = Vec::with_capacity(bindings.len()); + for (application, name) in bindings { + let (outputs, output_schema) = plan_function_outputs(schema, application, name.as_deref())?; + for field in &output_schema.fields { + if !destinations.insert(field.name.clone()) { + return Err(Error::ColumnAlreadyExists { + name: field.name.clone(), + }); + } + let field = + lance_namespace::schema::convert_json_arrow_field(field).map_err(|error| { + invalid_function(format!("invalid Function output schema: {error}")) + })?; + fields.push(Arc::new(field)); + } + plans.push((application, outputs, output_schema)); + } + let candidate = ArrowSchema::new(fields); + plans + .into_iter() + .map(|(application, outputs, output_schema)| { + plan_function_inputs( + &candidate, + &destinations, + application, + outputs, + output_schema, + ) + }) + .collect() +} + +fn plan_function_outputs( + schema: &ArrowSchema, + application: &FunctionApplication, + output_name: Option<&str>, +) -> Result<(Vec, JsonArrowSchema)> { if application.has_unknown_fields() { return Err(Error::NotSupported { message: "Function application contains fields from a newer contract".into(), @@ -1439,72 +1690,11 @@ pub(crate) fn plan_function_application( )); } - let mut parameters = BTreeSet::new(); - let mut input_bindings = Vec::with_capacity(application.inputs().len()); - let mut input_fields = Vec::with_capacity(application.inputs().len()); - for input in application.inputs() { - if !parameters.insert(input.parameter.as_str()) { - return Err(invalid_function(format!( - "duplicate Function parameter '{}'", - input.parameter - ))); - } - if input.kind != "column" { - return Err(Error::NotSupported { - message: format!( - "Function input kind '{}' is not supported for column declaration", - input.kind - ), - }); - } - let source = input.value.as_object().ok_or_else(|| { - invalid_function(format!( - "Function parameter '{}' has an invalid column source", - input.parameter - )) - })?; - if source.len() != 1 { - return Err(Error::NotSupported { - message: format!( - "Function parameter '{}' uses a newer column source contract", - input.parameter - ), - }); - } - let path = source.get("path").and_then(Value::as_str).ok_or_else(|| { - invalid_function(format!( - "Function parameter '{}' requires a column path", - input.parameter - )) - })?; - let resolved = resolve_field_path(schema, path)?; - let nullable = function_input_nullability(&resolved, path)?; - let field = resolved.leaf; - let parameter_field = - ArrowField::new(input.parameter.clone(), field.data_type().clone(), nullable) - .with_metadata(function_input_metadata(field)); - let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ - parameter_field.clone(), - ])) - .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; - let json_field = input_schema.fields.into_iter().next().unwrap(); - input_bindings.push(FunctionInputTarget { - parameter: input.parameter.clone(), - field_path: path.to_string(), - arrow_type: canonical_input_arrow_type(&json_field)?, - nullable, - }); - input_fields.push(parameter_field); - } - let input_schema = - lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(input_fields)) - .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; - let output = application.output(); let mut outputs = Vec::new(); let mut output_fields = Vec::new(); match output.kind.as_str() { - "scalar" => { + "scalar" | "scalar_blob_writer" => { if !application.columns().is_empty() { return Err(invalid_function( "scalar Function applications cannot rename result fields", @@ -1515,14 +1705,17 @@ pub(crate) fn plan_function_application( "a scalar Function application must be mapped to one output column", ) })?; - if output.nullable != Some(false) { - return Err(invalid_function( - "Function logical outputs must be non-nullable during NULL assignment", - )); - } + let nullable = output.nullable.ok_or_else(|| { + invalid_function("scalar Function output must declare nullability") + })?; let arrow_type = output.arrow_type.as_deref().ok_or_else(|| { invalid_function("scalar Function output is missing its Arrow type") })?; + if nullable && arrow_type == FUNCTION_BLOB_V2_TYPE { + return Err(invalid_function( + "Blob v2 Function outputs cannot be nullable", + )); + } outputs.push(FunctionOutputTarget { result_field: WHOLE_RESULT_FIELD.to_string(), output_name: name.to_string(), @@ -1530,7 +1723,7 @@ pub(crate) fn plan_function_application( }); output_fields.push(function_output_field(name, true, arrow_type)?); } - "named_struct" => { + "named_struct" | "named_struct_blob_writer" => { if output.fields.is_empty() { return Err(invalid_function( "named-struct Function output requires at least one field", @@ -1622,12 +1815,96 @@ pub(crate) fn plan_function_application( } } + Ok((outputs, JsonArrowSchema::new(output_fields))) +} + +fn plan_function_inputs( + schema: &ArrowSchema, + new_outputs: &HashSet, + application: &FunctionApplication, + outputs: Vec, + output_schema: JsonArrowSchema, +) -> Result { + let mut parameters = BTreeSet::new(); + let mut input_bindings = Vec::with_capacity(application.inputs().len()); + let mut input_fields = Vec::with_capacity(application.inputs().len()); + for input in application.inputs() { + if !parameters.insert(input.parameter.as_str()) { + return Err(invalid_function(format!( + "duplicate Function parameter '{}'", + input.parameter + ))); + } + if input.kind == "literal" { + crate::function::validate_literal(&input.value)?; + continue; + } + if input.kind != "column" { + return Err(Error::NotSupported { + message: format!( + "Function input kind '{}' is not supported for column declaration", + input.kind + ), + }); + } + let source = input.value.as_object().ok_or_else(|| { + invalid_function(format!( + "Function parameter '{}' has an invalid column source", + input.parameter + )) + })?; + if source.len() != 1 { + return Err(Error::NotSupported { + message: format!( + "Function parameter '{}' uses a newer column source contract", + input.parameter + ), + }); + } + let path = source.get("path").and_then(Value::as_str).ok_or_else(|| { + invalid_function(format!( + "Function parameter '{}' requires a column path", + input.parameter + )) + })?; + let resolved = resolve_field_path(schema, path)?; + let nullable = !new_outputs.contains(resolved.root.name()) + && function_input_nullability(&resolved, path)?; + let field = resolved.leaf; + let parameter_field = + ArrowField::new(input.parameter.clone(), field.data_type().clone(), nullable) + .with_metadata(function_input_metadata(field)); + let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + parameter_field.clone(), + ])) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + let json_field = input_schema.fields.into_iter().next().unwrap(); + input_bindings.push(FunctionInputTarget { + parameter: input.parameter.clone(), + field_path: path.to_string(), + arrow_type: canonical_input_arrow_type(&json_field)?, + nullable, + }); + input_fields.push(parameter_field); + } + let input_schema = + lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(input_fields)) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + Ok(FunctionDeclarationPlan { application: application.clone(), - binding_metadata_version: FUNCTION_BINDINGS_VERSION, + binding_metadata_version: if application + .inputs() + .iter() + .any(|input| input.kind == "literal") + { + FUNCTION_LITERAL_BINDINGS_VERSION + } else { + FUNCTION_BINDINGS_VERSION + }, input_bindings, input_schema, - output_schema: JsonArrowSchema::new(output_fields), + output_schema, outputs, }) } @@ -1640,8 +1917,12 @@ pub(crate) fn plan_function_application( /// /// Paths are compared at their root: a declaration reading `metadata` is /// invalidated by a change to `metadata.age` just as surely. -pub(crate) fn ensure_not_an_input(schema: &SchemaRef, paths: &[&str]) -> Result<()> { - ensure_not_an_input_of(schema, paths, &[]) +pub(crate) fn ensure_not_an_input( + schema: &SchemaRef, + paths: &[&str], + session: Option<&SessionContext>, +) -> Result<()> { + ensure_not_an_input_of(schema, paths, &[], session) } /// [`ensure_not_an_input`] where `removed` names columns whose own @@ -1651,6 +1932,7 @@ pub(crate) fn ensure_not_an_input_of( schema: &SchemaRef, paths: &[&str], removed: &[&str], + session: Option<&SessionContext>, ) -> Result<()> { // By identity, not spelling: a quoted path names the same column, while // a path *into* one removes no declaration at all. @@ -1668,7 +1950,7 @@ pub(crate) fn ensure_not_an_input_of( // The expression, not stored inputs, is the source of truth; an // expression that no longer parses proves nothing, so refuse. let inputs = match &declaration.kind { - ComputedColumnKind::Sql { expression } => Planner::new(schema.clone()) + ComputedColumnKind::Sql { expression } => session_planner(schema.clone(), session) .parse_expr(expression) .map(|parsed| Planner::column_names_in_expr(&parsed)) .map_err(|e| Error::InvalidInput { @@ -1715,10 +1997,20 @@ pub(crate) fn ensure_not_written<'a>( schema: &ArrowSchema, written: impl IntoIterator, ) -> Result<()> { - let declared: Vec = computed_columns(schema) + ensure_supported_function_metadata(schema)?; + let mut declared: Vec = computed_columns(schema) .into_iter() .map(|declaration| declaration.name) .collect(); + declared.extend( + function_bindings(schema)? + .into_iter() + .filter_map(|binding| { + binding + .assignment() + .map(|assignment| assignment.output_name.clone()) + }), + ); for name in written { if declared.iter().any(|declared| *declared == root(name)) { return Err(Error::InvalidInput { @@ -1760,7 +2052,10 @@ pub(crate) fn ensure_batch_writes_no_computed_values( /// Function declaration satisfies the binding contract, and no SQL /// declaration reads another computed column. What passes here is what /// `refresh_column` can execute. -pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<()> { +pub(crate) fn ensure_declarations_are_planned( + schema: &ArrowSchema, + session: Option<&SessionContext>, +) -> Result<()> { let invalid = |message: String| Error::InvalidInput { message }; // A field with any declaration key is a declaration; a partial one is // not "no declaration", it is a broken one. @@ -1794,7 +2089,12 @@ pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<() .filter(|f| f.name() != &column.name) .map(|f| f.as_ref().clone()) .collect(); - let bound = bind(Arc::new(ArrowSchema::new(others)), &column.name, expression)?; + let bound = bind( + Arc::new(ArrowSchema::new(others)), + &column.name, + expression, + session, + )?; if let Some(input) = bound.roots.iter().find(|r| declared.contains(*r)) { return Err(invalid(format!( "computed column '{}' reads computed column '{input}'", @@ -1944,6 +2244,17 @@ pub(crate) struct BoundExpression { pub blob_paths: Vec, /// A directly projected Blob v2 field whose semantics the output inherits. projected_blob_field: Option, + /// Field metadata of the expression's return field, e.g. a function's + /// logical type. + return_metadata: HashMap, +} + +/// Plans against `session`'s functions when given, else Lance's defaults. +fn session_planner(schema: SchemaRef, session: Option<&SessionContext>) -> Planner { + match session { + Some(session) => Planner::new_with_session(schema, session.clone()), + None => Planner::new(schema), + } } fn is_direct_field_projection(expr: &Expr) -> bool { @@ -2089,7 +2400,12 @@ fn referenced_blob_paths(schema: &ArrowSchema, inputs: &[String]) -> Result 0`), /// and the guard protecting the stored SQL has to see every column the text /// names, not just the ones the simplified form still reads. -pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result { +pub(crate) fn bind( + schema: SchemaRef, + column: &str, + expression: &str, + session: Option<&SessionContext>, +) -> Result { let invalid = |message: String| Error::InvalidExpression { column: column.to_string(), message, @@ -2102,7 +2418,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .into_iter() .collect::>(); let parsing_schema = blob_runtime_schema(schema.as_ref(), &all_blob_paths); - let planner = Planner::new(parsing_schema); + let planner = session_planner(parsing_schema, session); let parsed = planner .parse_expr(expression) .map_err(|e| invalid(e.to_string()))?; @@ -2171,22 +2487,22 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .map(|field| field.name().clone()) .collect(); - let runtime_planner = Planner::new(runtime_schema); + let runtime_planner = session_planner(runtime_schema, session); let optimized = runtime_planner .optimize_expr(parsed) .map_err(|e| invalid(e.to_string()))?; - let physical = Planner::new(read_schema.clone()) + let physical = session_planner(read_schema.clone(), session) .create_physical_expr(&optimized) .map_err(|e| invalid(e.to_string()))?; - let data_type = physical - .data_type(read_schema.as_ref()) + let return_field = physical + .return_field(read_schema.as_ref()) .map_err(|e| invalid(e.to_string()))?; Ok(BoundExpression { inputs, roots, physical, - data_type, + data_type: return_field.data_type().clone(), blob_paths: blob_paths .iter() .map(|path| { @@ -2195,6 +2511,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< }) .collect(), projected_blob_field, + return_metadata: return_field.metadata().clone(), }) } @@ -2210,7 +2527,11 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< /// batch may declare `a` and then `b = a + 1` in one commit. Refresh order /// then matters, and refresh enforces it: `b` is refused while `a` still has /// unfilled rows. -fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result> { +fn plan_declarations( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result> { if columns.is_empty() { return Err(Error::InvalidInput { message: "at least one computed column is required".into(), @@ -2225,23 +2546,22 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< return Err(Error::ColumnAlreadyExists { name: name.clone() }); } - let bound = bind(schema.clone(), name, expression)?; + let bound = bind(schema.clone(), name, expression, session)?; // Declared columns start entirely null, so nullability is a property // of the declaration rather than of what the expression yields. let computed_metadata = computed_column_metadata(expression, &bound.inputs); - let field = match bound.projected_blob_field { - Some(source) => { - let mut metadata = source.metadata().clone(); - metadata.retain(|key, _| !is_declaration_key(key)); - metadata.extend(computed_metadata); - source - .with_name(name) - .with_nullable(true) - .with_metadata(metadata) + let projected = match bound.projected_blob_field { + Some(source) => source.with_name(name), + None => { + ArrowField::new(name, bound.data_type, true).with_metadata(bound.return_metadata) } - None => ArrowField::new(name, bound.data_type, true).with_metadata(computed_metadata), }; + // Keep the source's descriptive metadata, not its schema declarations. + let projected = without_declarations(&projected); + let mut metadata = projected.metadata().clone(); + metadata.extend(computed_metadata); + let field = projected.with_nullable(true).with_metadata(metadata); schema = Arc::new(ArrowSchema::new_with_metadata( schema .fields() @@ -2257,8 +2577,12 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< Ok(fields) } -pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result> { - plan_declarations(schema, columns) +pub(crate) fn plan( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result> { + plan_declarations(schema, columns, session) } /// Run the schema-level checks of @@ -2267,6 +2591,11 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result Result Result<()> { +pub fn validate_declarations( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result<()> { ensure_not_function_bound( schema.as_ref(), "schema evolution", columns.iter().map(|(name, _)| name), )?; - plan(schema, columns).map(drop) + plan(schema, columns, session).map(drop) } /// Build the transform that declares `columns` against `schema`. @@ -2302,8 +2635,9 @@ pub fn validate_declarations(schema: SchemaRef, columns: &[(String, String)]) -> pub(crate) fn declare( schema: SchemaRef, columns: &[(String, String)], + session: Option<&SessionContext>, ) -> Result { - let fields = plan_declarations(schema, columns)?; + let fields = plan_declarations(schema, columns, session)?; Ok(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( fields, )))) @@ -2334,9 +2668,10 @@ pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &st /// created. pub(crate) fn admit_create_source( batches: S, + session: Option<&SessionContext>, ) -> Result> { let schema = batches.arrow_schema(); - ensure_declarations_are_planned(&schema)?; + ensure_declarations_are_planned(&schema, session)?; let declared = computed_columns(&schema) .into_iter() .map(|c| c.name) @@ -2447,10 +2782,15 @@ pub(crate) mod test_support { )]) .await .unwrap(); - let inputs = ["title".to_string(), "body".to_string()]; + let schema = dataset.schema(); let outputs = bindings .iter() .flat_map(|binding| { + let inputs = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); let assignment = binding.assignment().map(|assignment| { ( assignment.output_name.clone(), @@ -2462,9 +2802,9 @@ pub(crate) mod test_support { .iter() .map(|output| (output.output_name.clone(), output.output_ordinal)) .chain(assignment) - .map(|(name, ordinal)| { + .map(move |(name, ordinal)| { ( - dataset.schema().field(&name).unwrap().id as u32, + schema.field(&name).unwrap().id as u32, function_computed_column_metadata( binding.binding_id(), ordinal, @@ -2483,6 +2823,133 @@ pub(crate) mod test_support { #[cfg(test)] mod tests { + use arrow_array::{RecordBatch, record_batch}; + use arrow_schema::{DataType, TimeUnit}; + use futures::TryStreamExt; + use lance::dataset::ColumnAlteration; + + use super::*; + use crate::connect; + use crate::query::{ExecutableQuery, QueryBase, Select}; + use crate::{Error, Table}; + + #[test] + fn gpu_worker_defaults_round_trip_independently_of_totals() { + let options = super::ComputedColumnOptions { + gpu_class: Some("any".into()), + gpu_count: Some(2), + total_gpu_count: Some(8), + ..Default::default() + }; + let metadata = options.metadata().unwrap(); + assert_eq!(metadata["computed_column.gpu_count"], "2"); + assert_eq!(metadata["computed_column.total_gpu_count"], "8"); + assert_eq!( + super::ComputedColumnOptions::from_metadata(&metadata).unwrap(), + options + ); + assert!( + super::ComputedColumnOptions { + gpu_count: Some(0), + ..Default::default() + } + .validate() + .is_err() + ); + assert!( + super::ComputedColumnOptions { + gpu_count: Some(4), + total_gpu_count: Some(2), + ..Default::default() + } + .validate() + .is_err() + ); + } + + #[test] + fn computed_default_resource_metadata_round_trips_partial_dimensions() { + let options = super::ComputedColumnOptions { + total_cpu_millis: Some(8000), + total_memory_bytes: None, + total_gpu_count: Some(0), + ..Default::default() + }; + let metadata = options.metadata().unwrap(); + assert_eq!(metadata["computed_column.total_cpu_millis"], "8000"); + assert_eq!(metadata["computed_column.total_gpu_count"], "0"); + assert!(!metadata.contains_key("computed_column.total_memory_bytes")); + assert_eq!( + super::ComputedColumnOptions::from_metadata(&metadata).unwrap(), + options + ); + for invalid in ["0", "-1", "1.5", "18446744073709551616"] { + let malformed = + HashMap::from([("computed_column.total_cpu_millis".into(), invalid.into())]); + assert!(super::ComputedColumnOptions::from_metadata(&malformed).is_err()); + } + } + + #[test] + fn computed_auto_refresh_resource_budget_applies_to_function_outputs() { + let function_field = |name: &str, ordinal: u32| { + ArrowField::new(name, DataType::Int32, true).with_metadata(HashMap::from([ + ( + super::COMPUTED_COLUMN_META_KEY.to_string(), + "true".to_string(), + ), + ( + super::KIND_META_KEY.to_string(), + super::FUNCTION_KIND.to_string(), + ), + ( + super::FUNCTION_BINDING_ID_META_KEY.to_string(), + "binding-1".to_string(), + ), + ( + super::FUNCTION_OUTPUT_ORDINAL_META_KEY.to_string(), + ordinal.to_string(), + ), + ("custom".to_string(), "preserved".to_string()), + ])) + }; + let schema = ArrowSchema::new(vec![ + ArrowField::new("input", DataType::Int32, true), + function_field("first", 0), + function_field("second", 1), + function_field("assignment", super::FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL), + ]); + let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) + .with_total_gpu_count(2); + let updated = super::ComputedColumnOptions { + total_cpu_millis: Some((budget).total_cpu_millis), + total_memory_bytes: Some((budget).total_memory_bytes), + total_gpu_count: Some((budget).total_gpu_count), + ..Default::default() + } + .apply_to_schema(&schema) + .unwrap(); + + for name in ["first", "second"] { + let metadata = updated.field_with_name(name).unwrap().metadata(); + assert_eq!( + metadata.get("computed_column.total_cpu_millis"), + Some(&"8000".to_string()) + ); + assert_eq!( + metadata.get("custom").map(String::as_str), + Some("preserved") + ); + } + assert!( + !updated + .field_with_name("assignment") + .unwrap() + .metadata() + .contains_key("computed_column.total_cpu_millis") + ); + } + /// The gate's reproducer: the validator applies the same schema-level /// guard declaring does, so a staging caller is refused before it commits /// anything else. @@ -2496,7 +2963,7 @@ mod tests { )]), )); let declarations = vec![("a".to_string(), "x + 1".to_string())]; - assert!(super::validate_declarations(schema, &declarations).is_err()); + assert!(super::validate_declarations(schema, &declarations, None).is_err()); } #[test] @@ -2564,10 +3031,8 @@ mod tests { #[test] fn output_arrow_type_grammar_matches_the_shared_golden() { - let golden: serde_json::Value = serde_json::from_str(include_str!( - "../../tests/fixtures/first_class_functions/v1/arrow_types.json" - )) - .unwrap(); + let golden: serde_json::Value = + serde_json::from_str(crate::test_fixtures::FUNCTION_ARROW_TYPES_JSON).unwrap(); let valid = golden["valid"].as_array().unwrap().iter(); for case in valid.chain(golden["server_only"].as_array().unwrap()) { let raw = case["arrow_type"].as_str().unwrap(); @@ -2588,16 +3053,6 @@ mod tests { } } - use arrow_array::record_batch; - use arrow_schema::{DataType, TimeUnit}; - use futures::TryStreamExt; - use lance::dataset::ColumnAlteration; - - use super::*; - use crate::connect; - use crate::query::{ExecutableQuery, QueryBase, Select}; - use crate::{Error, Table}; - async fn table_with_ints(name: &str) -> Table { let conn = connect("memory://").execute().await.unwrap(); let batch = record_batch!(("x", Int32, [1, 2, 3])).unwrap(); @@ -2618,6 +3073,137 @@ mod tests { computed_columns(table.schema().await.unwrap().as_ref()) } + /// Echoes an Int32 and tags its return field, like a function with a + /// logical type. + #[derive(Debug, PartialEq, Eq, Hash)] + struct Tagged(datafusion_expr::Signature); + + impl datafusion_expr::ScalarUDFImpl for Tagged { + fn name(&self) -> &str { + "tagged" + } + + fn signature(&self) -> &datafusion_expr::Signature { + &self.0 + } + + fn return_type(&self, _: &[DataType]) -> datafusion_common::Result { + Ok(DataType::Int32) + } + + fn return_field_from_args( + &self, + _: datafusion_expr::ReturnFieldArgs, + ) -> datafusion_common::Result { + Ok(Arc::new( + ArrowField::new("tagged", DataType::Int32, true) + .with_metadata(HashMap::from([("tag".into(), "yes".into())])), + )) + } + + fn invoke_with_args( + &self, + args: datafusion_expr::ScalarFunctionArgs, + ) -> datafusion_common::Result { + Ok(args.args[0].clone()) + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_declarations_plan_against_the_session_functions() { + let functions = SessionContext::new(); + functions.register_udf(datafusion_expr::ScalarUDF::new_from_impl(Tagged( + datafusion_expr::Signature::exact( + vec![DataType::Int32], + datafusion_expr::Volatility::Immutable, + ), + ))); + let session = + Arc::new(lance::session::Session::default().with_datafusion_session(functions)); + let conn = connect("memory://") + .session(session) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1, 2, 3]), ("y", Int32, [4, 5, 6])).unwrap(); + let table = conn + .create_table("session_functions", batch) + .execute() + .await + .unwrap(); + + add_computed(&table, &[("t".into(), "tagged(x)".into())]) + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + assert_eq!( + schema.field_with_name("t").unwrap().metadata().get("tag"), + Some(&"yes".to_string()) + ); + table.refresh_column("t").await.unwrap(); + // Dropping a column re-plans every declaration on the table. + table.drop_columns(&["y"]).await.unwrap(); + + let batches = table + .query() + .select(Select::columns(&["t"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let expected = record_batch!(("t", Int32, [1, 2, 3])).unwrap(); + assert_eq!(batches[0].column(0).as_ref(), expected.column(0).as_ref()); + + let plain = table_with_ints("no_session").await; + let err = add_computed(&plain, &[("t".into(), "tagged(x)".into())]) + .await + .unwrap_err(); + assert!(err.to_string().contains("tagged"), "{err}"); + } + + /// A projection keeps its source's descriptive metadata, not its schema + /// declarations: a copy of the primary key is not a primary key. + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_projecting_the_primary_key_drops_its_declaration() { + let conn = connect("memory://").execute().await.unwrap(); + let ints = record_batch!(("x", Int32, [1, 2, 3])).unwrap(); + let schema = ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, false) + .with_metadata(HashMap::from([("note".into(), "kept".into())])), + ]); + let batch = RecordBatch::try_new(Arc::new(schema), ints.columns().to_vec()).unwrap(); + let table = conn + .create_table("key_projection", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + + add_computed(&table, &[("copy".into(), "x".into())]) + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + let copy = schema.field_with_name("copy").unwrap(); + assert!( + !copy + .metadata() + .keys() + .any(|key| key.starts_with("lance-schema:")), + "{copy:?}" + ); + assert_eq!(copy.metadata().get("note"), Some(&"kept".to_string())); + } + #[tokio::test] #[cfg_attr( not(feature = "experimental-functions"), @@ -2658,6 +3244,7 @@ mod tests { ("first".to_string(), "image".to_string()), ("second".to_string(), "first".to_string()), ], + None, ) .unwrap(); @@ -2680,6 +3267,7 @@ mod tests { let fields = plan( schema, &[("payload".to_string(), "coalesce(image, image)".to_string())], + None, ) .unwrap(); @@ -2914,7 +3502,8 @@ mod tests { assert!( validate_declarations( table.schema().await.unwrap(), - &[("e".into(), "random()".into())] + &[("e".into(), "random()".into())], + None, ) .is_err() ); @@ -3697,6 +4286,22 @@ mod tests { .unwrap() } + fn nullable_scalar_application() -> FunctionApplication { + FunctionApplication::from_json( + &serde_json::json!({ + "function": {"name": "nullable_scalar", "version": "1", "object_id": "fixture", "location": "memory:///fixture", "manifest_digest": "sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "inputs": [{ + "parameter": "value", + "kind": "column", + "value": {"path": "value"} + }], + "output": {"kind": "scalar", "arrow_type": "int64", "nullable": true} + }) + .to_string(), + ) + .unwrap() + } + fn binding_from_plan(plan: &FunctionDeclarationPlan) -> FunctionBinding { let inputs = plan .input_bindings @@ -3802,6 +4407,37 @@ mod tests { ArrowSchema::new(fields) } + #[test] + fn input_writes_preserve_the_assignment_column_guard() { + let mut raw: Value = serde_json::to_value(test_support::text_features_binding("")).unwrap(); + raw["assignment"] = serde_json::json!({ + "output_name": "__function_assignment_fb_01K3TEXT", "output_field_id": -1, + }); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["outputs"][1]["nullable"] = Value::Bool(true); + raw["output_schema"]["fields"].as_array_mut().unwrap().push(serde_json::json!({ + "name": "__function_assignment_fb_01K3TEXT", "nullable": true, "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let schema = ArrowSchema::new_with_metadata( + valid_function_binding_schema(true, true, &binding) + .fields() + .to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.into(), + function_bindings_metadata(&[binding]).unwrap(), + )]), + ); + ensure_not_written(&schema, ["title", "body"]).unwrap(); + for output in [ + "search_text", + "search_token_count", + "__function_assignment_fb_01K3TEXT", + ] { + assert!(ensure_not_written(&schema, [output]).is_err(), "{output}"); + } + } + #[test] fn test_non_nullable_function_inputs_can_bind_to_nullable_parameters() { let binding = FunctionBinding::from_json(include_str!( @@ -3975,6 +4611,259 @@ mod tests { )); } + #[test] + fn test_nullable_scalar_application_plans_one_nullable_output() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input]), + &nullable_scalar_application(), + Some("maybe"), + ) + .unwrap(); + + assert_eq!(plan.application.output().nullable, Some(true)); + assert_eq!(plan.outputs.len(), 1); + assert_eq!(plan.outputs[0].result_field, WHOLE_RESULT_FIELD); + assert_eq!(plan.outputs[0].output_name, "maybe"); + assert_eq!(plan.outputs[0].output_ordinal, 0); + assert_eq!(plan.output_schema.fields.len(), 1); + assert!(plan.output_schema.fields[0].nullable); + assert_eq!(plan.output_schema.fields[0].r#type.r#type, "int64"); + } + + #[test] + fn test_invalid_nullable_scalar_applications_fail_closed() { + let input = ArrowField::new("value", DataType::Int64, false); + let schema = ArrowSchema::new(vec![input]); + + let mut missing_nullability = serde_json::to_value(nullable_scalar_application()).unwrap(); + missing_nullability["output"] + .as_object_mut() + .unwrap() + .remove("nullable"); + let application = FunctionApplication::from_json(&missing_nullability.to_string()).unwrap(); + let err = plan_function_application(&schema, &application, Some("maybe")).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("declare nullability")), + "{err:?}" + ); + + let nullable_blob = + blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":true}"#); + let err = plan_function_application( + &ArrowSchema::new(vec![crate::blob("image", false)]), + &nullable_blob, + Some("copy"), + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("Blob v2") && message.contains("nullable")), + "{err:?}" + ); + } + + #[test] + fn test_nullable_scalar_binding_accepts_server_owned_assignment() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &nullable_scalar_application(), + Some("maybe"), + ) + .unwrap(); + let assignment_name = "__function_assignment_nullable_scalar"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = ArrowField::new("maybe", DataType::Int64, true).with_metadata( + function_computed_column_metadata(binding.binding_id(), 0, &["value".into()]), + ); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["value".into()], + ), + ); + + let schema = ArrowSchema::new(vec![input.clone(), output.clone(), assignment]); + ensure_binding_matches_schema(&schema, &binding).unwrap(); + let hidden = ArrowSchema::new(vec![input, output]); + ensure_binding_matches_schema(&hidden, &binding).unwrap(); + + let schema = ArrowSchema::new_with_metadata( + schema.fields().to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + function_bindings_metadata(std::slice::from_ref(&binding)).unwrap(), + )]), + ); + ensure_supported_function_metadata(&schema).unwrap(); + } + + #[test] + fn test_non_nullable_scalar_binding_rejects_server_owned_assignment() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &single_input_application("value"), + Some("maybe"), + ) + .unwrap(); + let assignment_name = "__function_assignment_non_nullable_scalar"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = ArrowField::new("maybe", DataType::Int64, true).with_metadata( + function_computed_column_metadata(binding.binding_id(), 0, &["value".into()]), + ); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["value".into()], + ), + ); + + let err = ensure_binding_matches_schema( + &ArrowSchema::new(vec![input, output, assignment]), + &binding, + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + + #[test] + fn test_named_struct_whole_binding_rejects_server_owned_assignment() { + let plan = plan_function_application( + &function_input_schema(), + &named_struct_application("{}"), + Some("features"), + ) + .unwrap(); + let assignment_name = "__function_assignment_whole_struct"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = + lance_namespace::schema::convert_json_arrow_field(&plan.output_schema.fields[0]) + .unwrap() + .with_metadata(function_computed_column_metadata( + binding.binding_id(), + 0, + &["title".into(), "body".into()], + )); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["title".into(), "body".into()], + ), + ); + let mut fields = function_input_schema() + .fields() + .iter() + .map(|field| field.as_ref().clone()) + .collect::>(); + fields.push(output); + fields.push(assignment); + + let err = ensure_binding_matches_schema(&ArrowSchema::new(fields), &binding).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + + #[test] + fn test_blob_whole_binding_rejects_server_owned_assignment() { + let input = crate::blob("image", false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#), + Some("thumbnail"), + ) + .unwrap(); + let assignment_name = "__function_assignment_whole_blob"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let mut metadata = full_blob_field("thumbnail", true).metadata().clone(); + metadata.extend(function_computed_column_metadata( + binding.binding_id(), + 0, + &["image".into()], + )); + let output = full_blob_field("thumbnail", true).with_metadata(metadata); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["image".into()], + ), + ); + + let err = ensure_binding_matches_schema( + &ArrowSchema::new(vec![input, output, assignment]), + &binding, + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + #[test] fn test_nullable_function_input_cannot_bind_to_non_nullable_parameter() { let mut raw_binding: Value = serde_json::from_str(include_str!( @@ -4062,6 +4951,129 @@ mod tests { ensure_binding_matches_schema(&ArrowSchema::new(fields), &binding).unwrap(); } + #[test] + fn test_literal_function_application_keeps_only_column_dependencies() { + let mut value = serde_json::to_value(single_input_application("title")).unwrap(); + value["inputs"] = serde_json::json!([ + {"parameter": "count", "kind": "literal", "value": 16}, + {"parameter": "text", "kind": "column", "value": {"path": "title"}}, + {"parameter": "optional", "kind": "literal", "value": null} + ]); + let application = FunctionApplication::from_json(&value.to_string()).unwrap(); + let plan = + plan_function_application(&function_input_schema(), &application, Some("result")) + .unwrap(); + assert_eq!(plan.binding_metadata_version, 2); + assert_eq!(plan.input_bindings.len(), 1); + assert_eq!(plan.input_bindings[0].parameter, "text"); + assert_eq!(plan.input_bindings[0].field_path, "title"); + assert_eq!(plan.input_schema.fields.len(), 1); + assert_eq!(plan.input_schema.fields[0].name, "text"); + assert_eq!( + serde_json::to_value(plan.application).unwrap()["inputs"], + value["inputs"] + ); + value["inputs"][0]["parameter"] = serde_json::json!("text"); + let duplicate = FunctionApplication::from_json(&value.to_string()).unwrap(); + assert!( + plan_function_application(&function_input_schema(), &duplicate, Some("result")) + .unwrap_err() + .to_string() + .contains("duplicate Function parameter") + ); + } + + #[test] + fn test_literal_function_metadata_survives_schema_mutation_guards() { + let legacy = FunctionBinding::from_json(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + let legacy_envelope: Value = serde_json::from_str( + &function_bindings_metadata(std::slice::from_ref(&legacy)).unwrap(), + ) + .unwrap(); + assert_eq!(legacy_envelope["version"], 1); + let mut value = serde_json::to_value(&legacy).unwrap(); + value["inputs"].as_array_mut().unwrap().pop(); + value["literal_inputs"] = serde_json::json!([{"parameter": "body", "value": null}]); + let binding = FunctionBinding::from_json(&value.to_string()).unwrap(); + let raw = function_bindings_metadata(std::slice::from_ref(&binding)).unwrap(); + let mut envelope: Value = serde_json::from_str(&raw).unwrap(); + assert_eq!(envelope["version"], 2); + assert_eq!( + envelope["bindings"][0]["literal_inputs"], + value["literal_inputs"] + ); + let schema = valid_function_binding_schema(true, true, &binding); + let schema = schema.with_metadata(HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + raw.clone(), + )])); + ensure_supported_function_metadata(&schema).unwrap(); + let decoded = function_bindings(&schema).unwrap(); + assert_eq!(decoded.as_slice(), std::slice::from_ref(&binding)); + assert_eq!(function_bindings_metadata(&decoded).unwrap(), raw); + assert!(!protected_roots(&decoded).unwrap().contains("body")); + + envelope["version"] = serde_json::json!(1); + let downgraded = schema.clone().with_metadata(HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + envelope.to_string(), + )])); + assert!( + function_bindings(&downgraded) + .unwrap_err() + .to_string() + .contains("require metadata version 2") + ); + + value["literal_inputs"][0]["parameter"] = serde_json::json!("title"); + assert!( + FunctionBinding::from_json(&value.to_string()) + .unwrap_err() + .to_string() + .contains("duplicate Function parameter") + ); + } + + #[test] + fn test_literal_function_binding_requires_complete_input_schema() { + let mut value: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + value["inputs"].as_array_mut().unwrap().pop(); + value["literal_inputs"] = serde_json::json!([{"parameter": "body", "value": null}]); + value["input_schema"]["fields"][1]["nullable"] = serde_json::json!(false); + let binding = FunctionBinding::from_json(&value.to_string()).unwrap(); + let schema = valid_function_binding_schema(true, true, &binding); + assert!( + ensure_binding_matches_schema(&schema, &binding) + .unwrap_err() + .to_string() + .contains("invalid literal") + ); + value["input_schema"]["fields"] + .as_array_mut() + .unwrap() + .pop(); + let missing = FunctionBinding::from_json(&value.to_string()).unwrap(); + assert!( + ensure_binding_matches_schema(&schema, &missing) + .unwrap_err() + .to_string() + .contains("missing bound parameters") + ); + value["literal_inputs"][0]["value"] = serde_json::json!(1.5); + assert!( + FunctionBinding::from_json(&value.to_string()) + .unwrap_err() + .to_string() + .contains("floating-point Function literals") + ); + } + #[test] fn test_function_binding_metadata_survives_schema_round_trip() { let binding = FunctionBinding::from_json(include_str!( @@ -4246,17 +5258,53 @@ mod tests { #[test] fn test_blob_function_plans_semantic_input_and_scalar_output() { let schema = ArrowSchema::new(vec![crate::blob("image", false)]); - let application = - blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#); - let plan = plan_function_application(&schema, &application, Some("thumbnail")).unwrap(); + for output in [ + r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#, + r#"{"kind":"scalar_blob_writer","arrow_type":"blob_v2","nullable":false,"blob_writer_paths":[[]]}"#, + ] { + let application = blob_application(output); + let plan = plan_function_application(&schema, &application, Some("thumbnail")).unwrap(); - assert_eq!(plan.input_bindings[0].arrow_type, FUNCTION_BLOB_V2_TYPE); - let input_schema = - lance_namespace::schema::convert_json_arrow_schema(&plan.input_schema).unwrap(); - assert!(input_schema.field(0).is_blob_v2()); - let output_schema = - lance_namespace::schema::convert_json_arrow_schema(&plan.output_schema).unwrap(); - assert!(output_schema.field(0).is_blob_v2()); + assert_eq!(plan.input_bindings[0].arrow_type, FUNCTION_BLOB_V2_TYPE); + let input_schema = + lance_namespace::schema::convert_json_arrow_schema(&plan.input_schema).unwrap(); + assert!(input_schema.field(0).is_blob_v2()); + let output_schema = + lance_namespace::schema::convert_json_arrow_schema(&plan.output_schema).unwrap(); + assert!(output_schema.field(0).is_blob_v2()); + } + } + + #[test] + fn test_named_blob_writer_plan_preserves_logical_output_columns() { + let schema = ArrowSchema::new(vec![crate::blob("image", false)]); + let application = blob_application( + r#"{ + "kind":"named_struct_blob_writer", + "fields":[ + {"name":"item","arrow_type":"blob_v2","nullable":true}, + {"name":"checksum","arrow_type":"binary","nullable":false} + ], + "blob_writer_paths":[[{"field":"item"}]] + }"#, + ); + let expanded = plan_function_application(&schema, &application, None).unwrap(); + let expanded_schema = + lance_namespace::schema::convert_json_arrow_schema(&expanded.output_schema).unwrap(); + assert_eq!(expanded_schema.field(0).name(), "item"); + assert!(expanded_schema.field(0).is_blob_v2()); + assert_eq!(expanded_schema.field(1).data_type(), &DataType::Binary); + + let whole = plan_function_application(&schema, &application, Some("rendered")).unwrap(); + let whole_schema = + lance_namespace::schema::convert_json_arrow_schema(&whole.output_schema).unwrap(); + let DataType::Struct(fields) = whole_schema.field(0).data_type() else { + panic!("named writer output must bind as a struct"); + }; + assert!(fields[0].is_blob_v2()); + assert!(fields[0].is_nullable()); + assert_eq!(fields[1].data_type(), &DataType::Binary); + assert!(!fields[1].is_nullable()); } #[test] @@ -4715,7 +5763,7 @@ mod tests { function_input_schema().fields().to_vec(), HashMap::from([( FUNCTION_BINDINGS_META_KEY.to_string(), - r#"{"version":2,"bindings":[]}"#.to_string(), + r#"{"version":3,"bindings":[]}"#.to_string(), )]), ); let err = plan_function_application(&mixed_schema, &named_struct_application("{}"), None) @@ -4803,7 +5851,7 @@ mod tests { let schema = declare_plan(&schema, &downstream, "fb_downstream"); ensure_supported_function_metadata(&schema).unwrap(); - ensure_declarations_are_planned(&schema).unwrap(); + ensure_declarations_are_planned(&schema, None).unwrap(); let bindings = function_bindings(&schema).unwrap(); assert!( computed_function_inputs(&schema, &bindings[0]) @@ -4868,7 +5916,7 @@ mod tests { let base = ArrowSchema::new(vec![ArrowField::new("x", DataType::Int32, true)]); let mut fields = base.fields().to_vec(); fields.extend( - plan(Arc::new(base), &[("doubled".into(), "x * 2".into())]) + plan(Arc::new(base), &[("doubled".into(), "x * 2".into())], None) .unwrap() .into_iter() .map(Arc::new), @@ -4887,7 +5935,7 @@ mod tests { .is_none_or(|metadata| !metadata.keys().any(|key| is_declaration_key(key))) ); let schema = Arc::new(declare_plan(&schema, &downstream, "fb_downstream")); - ensure_declarations_are_planned(&schema).unwrap(); + ensure_declarations_are_planned(&schema, None).unwrap(); let batch = RecordBatch::try_new( schema, vec![ diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 5f9ae13b4..79d7ed198 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -115,14 +115,24 @@ impl NativeTable { pub(super) async fn prepare_index( &self, opts: &crate::index::IndexBuilder, - ) -> Result { + ) -> Result> { + self.dataset.ensure_mutable()?; + let dataset = self.dataset.get().await?; + if opts.exist_ok + && let Some(name) = &opts.name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(None); + } if opts.columns.len() != 1 { return Err(Error::Schema { message: "Multi-column (composite) indices are not yet supported".to_string(), }); } - self.dataset.ensure_mutable()?; - let dataset = self.dataset.get().await?; let (column, field) = if let Index::FTS(params) = &opts.index { let resolved = resolve_lance_fts_field_path(dataset.schema(), &opts.columns[0])?; if params.get_document_granularity().is_list_element() && resolved.list_depth == 0 { @@ -137,9 +147,48 @@ impl NativeTable { } else { Self::resolve_index_field(dataset.schema(), &opts.columns[0])? }; + if let Some(name) = Self::guarded_index_name(opts, &column)? + && dataset + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(None); + } let params = self.make_index_params(&field, opts.index.clone()).await?; let index_type = self.get_index_type_for_field(&field, &opts.index); - Ok((column, params, index_type)) + Ok(Some((column, params, index_type))) + } + + fn guarded_index_name( + opts: &crate::index::IndexBuilder, + column: &str, + ) -> Result> { + let name = if opts.exist_ok { + Some(if let Some(name) = &opts.name { + name.clone() + } else { + let names = lance_core::datatypes::parse_field_path(column)?; + let default_name = if matches!(&opts.index, Index::FTS(_)) + || names.iter().any(|name| name.contains('.')) + { + column.to_string() + } else { + names.join(".") + }; + let suffix = if matches!(&opts.index, Index::FTS(params) if params.get_document_granularity().is_list_element()) + { + "_list_element_idx" + } else { + "_idx" + }; + format!("{default_name}{suffix}") + }) + } else { + None + }; + Ok(name) } /// Builds a prepared index and publishes the new dataset version. @@ -150,16 +199,42 @@ impl NativeTable { ) -> Result<()> { let (column, lance_idx_params, index_type) = prepared; let mut dataset = (*self.dataset.get().await?).clone(); + let guarded_name = Self::guarded_index_name(&opts, &column)?; + if let Some(name) = &guarded_name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(()); + } let columns = [column.as_str()]; let mut builder = dataset .create_index_builder(&columns, index_type, lance_idx_params.as_ref()) .train(opts.train) - .replace(opts.replace); + .replace(opts.replace && !opts.exist_ok); - if let Some(name) = opts.name { + if let Some(name) = guarded_name.clone().or(opts.name) { builder = builder.name(name); } - builder.await?; + if let Err(error) = builder.await { + if let Some(name) = guarded_name { + self.dataset.reload().await?; + if self + .dataset + .get() + .await? + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(()); + } + } + return Err(error.into()); + } // A writer already open was built before this index existed, so it has // to pick it up here or a read needing it is refused until it reopens. self.dataset @@ -291,6 +366,15 @@ impl NativeTable { ScalarIndexParams::for_builtin(BuiltinIndexType::RTree).with_params(¶ms), )) } + // Lance resolves the plugin by name and the plugin checks the column + // and the parameters, so there is nothing to validate here. + Index::Plugin(plugin) => { + let mut params = ScalarIndexParams::new(plugin.index_type); + params.params = plugin + .params + .map(|params| serde_json::Value::Object(params).to_string()); + Ok(Box::new(params)) + } Index::FTS(fts_opts) => { validate_fts_field(field)?; Ok(Box::new(fts_opts)) @@ -457,6 +541,7 @@ impl NativeTable { Index::NGram(_) => IndexType::NGram, Index::BloomFilter(_) => IndexType::BloomFilter, Index::RTree(_) => IndexType::RTree, + Index::Plugin(_) => IndexType::Scalar, Index::FTS(_) => IndexType::Inverted, Index::IvfFlat(_) | Index::IvfSq(_) @@ -568,6 +653,63 @@ mod tests { Ok(FixedSizeListArray::from(data)) } + #[tokio::test] + async fn test_concurrent_index_exist_ok_preserves_single_identity() { + let dir = tempdir().unwrap(); + let db = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("id", Int32, (0..512).collect::>())).unwrap(); + let table = db.create_table("t", batch).execute().await.unwrap(); + let second = db.open_table("t").execute().await.unwrap(); + let (left, right) = tokio::join!( + table + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute(), + second + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute() + ); + left.unwrap(); + right.unwrap(); + table.checkout_latest().await.unwrap(); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices.len(), 1); + let original_uuid = indices[0].uuid; + let version = table.version().await.unwrap(); + table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), version); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices[0].uuid, original_uuid); + } + #[tokio::test] async fn test_create_index() { use std::iter::repeat_with; @@ -1532,6 +1674,74 @@ mod tests { assert_eq!(null_count, 1); } + #[tokio::test] + async fn test_create_btree_index_on_large_utf8() { + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("explicit", DataType::LargeUtf8, true), + Field::new("auto", DataType::LargeUtf8, true), + ])); + let values = || { + Arc::new(LargeStringArray::from(vec![ + Some("alpha"), + None, + Some("omega"), + Some("alpha"), + ])) as ArrayRef + }; + let batch = RecordBatch::try_new(schema, vec![values(), values()]).unwrap(); + let table = conn + .create_table("large_utf8_btree_table", batch) + .execute() + .await + .unwrap(); + + table + .create_index(&["explicit"], Index::BTree(BTreeIndexBuilder::default())) + .execute() + .await + .unwrap(); + // Auto picks BTree for string columns, so LargeUtf8 must get one too. + table + .create_index(&["auto"], Index::Auto) + .execute() + .await + .unwrap(); + table + .wait_for_index(&["explicit_idx", "auto_idx"], Duration::from_millis(10)) + .await + .unwrap(); + + let index_configs = table.list_indices().await.unwrap(); + assert_eq!(index_configs.len(), 2); + for index in index_configs { + assert_eq!(index.index_type, crate::index::IndexType::BTree); + } + + for column in ["explicit", "auto"] { + for (filter, expected_rows) in [ + (format!("{column} = 'alpha'"), 2), + (format!("{column} > 'beta'"), 1), + (format!("{column} IS NULL"), 1), + ] { + let query = table.query().only_if(filter.as_str()); + let plan = query.explain_plan(false).await.unwrap(); + assert!(plan.contains("ScalarIndexQuery"), "{filter}: {plan}"); + let num_rows = query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + .iter() + .map(|b| b.num_rows()) + .sum::(); + assert_eq!(num_rows, expected_rows, "{filter}"); + } + } + } + #[tokio::test] async fn test_create_builtin_scalar_index() { for (index, index_type, predicate, invalid_column) in [ @@ -1650,6 +1860,191 @@ mod tests { } } + /// Lance's built-in plugins, created by name through the generic path, are + /// listed with the same type as their dedicated builders and serve filters. + #[tokio::test] + async fn test_create_plugin_index() { + use crate::index::IndexType; + use crate::index::scalar::PluginIndexBuilder; + + for (name, params, column, index_type, predicate, expected_rows) in [ + ( + "ZoneMap", + None, + "id", + IndexType::ZoneMap, + "id >= 2 AND id < 4", + 2, + ), + ( + "bloomfilter", + Some(serde_json::json!({"number_of_items": 2, "probability": 0.01})), + "text", + IndexType::BloomFilter, + "text = 'abc'", + 1, + ), + ("BTREE", None, "id", IndexType::BTree, "id = 3", 1), + ] { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!( + ("id", Int32, [1, 2, 3, 4]), + ("text", Utf8, [Some("abc"), Some("xyz"), None, Some("")]) + ) + .unwrap(); + let table = conn.create_table("plugin", batch).execute().await.unwrap(); + + let mut plugin = PluginIndexBuilder::new(name).unwrap(); + if let Some(params) = params.clone() { + plugin = plugin.params(params).unwrap(); + } + table + .create_index(&[column], Index::Plugin(plugin)) + .name("plugin_idx".into()) + .execute() + .await + .unwrap(); + + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!(indices[0].index_type, index_type, "{name}"); + assert_eq!(indices[0].columns, [column]); + let stats = table.index_stats("plugin_idx").await.unwrap().unwrap(); + assert_eq!(stats.index_type, index_type); + assert_eq!(stats.num_indexed_rows, 4); + + // Lance trained the plugin with the given params, not its defaults. + if let Some(params) = params { + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let stats: serde_json::Value = + serde_json::from_str(&dataset.index_statistics("plugin_idx").await.unwrap()) + .unwrap(); + for (key, value) in params.as_object().unwrap() { + assert_eq!(&stats["indices"][0][key], value, "{key}"); + } + } + + let query = table.query().only_if(predicate); + let plan = query.explain_plan(false).await.unwrap(); + assert!(plan.contains("ScalarIndexQuery"), "{name}: {plan}"); + let batches = query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + expected_rows, + "{name}" + ); + } + } + + /// A plugin LanceDB has no type for is listed as `Custom` with the name + /// the plugin reports. + #[tokio::test] + async fn test_create_plugin_index_without_lancedb_type_is_listed_as_custom() { + use crate::index::IndexType; + use crate::index::scalar::PluginIndexBuilder; + + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(( + "value", + Utf8, + ["alpha beta", "beta gamma", "gamma delta", "delta alpha"] + )) + .unwrap(); + let table = conn.create_table("custom", batch).execute().await.unwrap(); + table + .create_index( + &["value"], + Index::Plugin(PluginIndexBuilder::new("MinHashLSH").unwrap()), + ) + .execute() + .await + .unwrap(); + + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!( + indices[0].index_type, + IndexType::Custom("MinHashLsh".into()) + ); + assert_eq!(indices[0].index_type.to_string(), "MinHashLsh"); + assert_eq!(indices[0].columns, ["value"]); + } + + /// Lance's errors for an unknown plugin, a column the plugin cannot index + /// and params the plugin rejects reach the caller, through both execute + /// paths, and leave no index behind. + #[tokio::test] + async fn test_create_plugin_index_errors() { + use crate::index::scalar::PluginIndexBuilder; + + let conn = connect("memory://").execute().await.unwrap(); + let batch = + record_batch!(("id", Int32, [1, 2, 3]), ("text", Utf8, ["a", "b", "c"])).unwrap(); + let table = conn.create_table("errors", batch).execute().await.unwrap(); + + let plugin = |name: &str| PluginIndexBuilder::new(name).unwrap(); + for (column, index, expected) in [ + ( + "id", + plugin("NoSuchPlugin"), + "No scalar index plugin found for name 'nosuchplugin'", + ), + ("id", plugin("ngram"), "ngram"), + ( + "text", + plugin("bloomfilter") + .params(serde_json::json!({"number_of_items": "many"})) + .unwrap(), + "invalid type: string \"many\", expected u64", + ), + ] { + let error = table + .create_index(&[column], Index::Plugin(index.clone())) + .execute() + .await + .unwrap_err(); + assert!( + error + .to_string() + .to_lowercase() + .contains(&expected.to_lowercase()), + "{error}" + ); + + let error = table + .create_index(&[column], Index::Plugin(index)) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap_err(); + assert!( + error + .to_string() + .to_lowercase() + .contains(&expected.to_lowercase()), + "{error}" + ); + } + assert!(table.list_indices().await.unwrap().is_empty()); + + // A missing column is still caught before any build starts. + assert!( + table + .create_index(&["missing"], Index::Plugin(plugin("zonemap"))) + .execute_async() + .await + .is_err() + ); + } + #[cfg(feature = "geo")] #[tokio::test] async fn test_create_rtree_index() { diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 81df7d300..22ec5caeb 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -4,6 +4,7 @@ //! This module contains adapters to allow LanceDB tables to be used as DataFusion table providers. mod blob_coerce; +mod blob_materialize; mod blob_nulls; pub mod cast; pub mod insert; @@ -31,7 +32,7 @@ use lance_core::{ datatypes::{Projection, Schema as LanceSchema}, }; -use super::{AnyQuery, BaseTable}; +use super::{AnyQuery, BaseTable, NativeTableExt}; use crate::{ Error, Result, query::{QueryExecutionOptions, QueryFilter, QueryRequest, Select}, @@ -199,7 +200,8 @@ impl ExecutionPlan for MetadataEraserExec { pub enum BlobSchema { /// Expose Blob v2 descriptors (`kind`, `position`, `size`, `blob_id`, `blob_uri`) /// and legacy v1 descriptors (`position`, `size`). Scans support all blob fields; - /// SQL INSERT into Blob v2 tables is unsupported. + /// SQL INSERT SELECT materializes descriptors from a single native-table + /// snapshot; remote and Realtime/MemWAL sources are not supported. #[default] Read, /// Expose Blob v2 write inputs (`data`, `uri`, `position`, `size`) and legacy @@ -213,9 +215,33 @@ pub enum BlobSchema { /// /// Defaults to [`BlobSchema::Read`], matching the descriptor schema produced by /// scans without fetching blob bytes. Use [`Self::with_blob_schema`] to enable -/// SQL INSERT into blob columns. Legacy v1 blobs expose descriptors in read mode -/// and `LargeBinary` inputs in write mode; write-mode descriptor scans fail with -/// a schema mismatch. Tables without blob columns behave the same in both modes. +/// SQL INSERT with logical blob inputs. In read mode, INSERT SELECT can copy +/// Blob v2 descriptors from a single native-table snapshot into target-owned +/// payloads, including projections, filters, sorting, and limits. JOIN, UNION, +/// aggregation, and computed descriptors fail during planning because their +/// source row addresses cannot be established safely. Legacy v1 blobs expose +/// descriptors in read mode and `LargeBinary` inputs in write mode; write-mode +/// descriptor scans fail with a schema mismatch. Tables without blob columns +/// behave the same in both modes. +/// Descriptor copying requires a native source table; remote and Realtime/MemWAL +/// sources are not supported by this materialization path. +/// +/// With read adapters registered as `source` and `target`, copying blobs needs +/// no payload UDF or explicit system columns: +/// +/// ```sql +/// INSERT INTO target SELECT * FROM source WHERE id > 10; +/// ``` +/// +/// The target owns the copied payloads independently of subsequent source +/// compaction or deletion. External URI references retain their external +/// storage semantics and remain subject to the target's registered external +/// bases; copying a descriptor does not authorize a new external location. +/// +/// Materialization allocates payload bytes for each input batch outside the +/// DataFusion memory pool. For large blobs, configure a conservative +/// `SessionConfig::with_batch_size`; the pool limit alone does not bound these +/// allocations, and a single blob can still exceed that limit. #[derive(Debug)] pub struct BaseTableAdapter { table: Arc, @@ -440,13 +466,55 @@ impl TableProvider for BaseTableAdapter { ..Default::default() }; - let plan = self - .table - .create_plan(&AnyQuery::Query(query), options) + // The scan and any later INSERT rewrite must use the same snapshot, + // even if the live table advances between planning and execution. + let projects_descriptors = match projection { + Some(indices) => indices + .iter() + .any(|index| blob_nulls::has_descriptor(provider_schema.field(*index))), + None => provider_schema + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)), + }; + let snapshot = if self.blob_schema == BlobSchema::Read + && self.table.as_native().is_some() + && projects_descriptors + { + Some( + self.table + .query_snapshot() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?, + ) + } else { + None + }; + let source = snapshot.as_ref().unwrap_or(&self.table); + let plan = source + .create_plan(&AnyQuery::Query(query.clone()), options.clone()) .map_err(|err| DataFusionError::External(err.into())) .await?; let plan = blob_nulls::mask_plan(plan)?; - let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let mut plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + if let Some(snapshot) = snapshot + && plan + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + let dataset = snapshot + .as_native() + .unwrap() + .dataset + .get() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + plan = Arc::new(blob_materialize::BlobScanExec::new( + plan, snapshot, dataset, query, options, + )); + } if self.blob_schema == BlobSchema::Write { let schema = match projection { Some(projection) => Arc::new(provider_schema.project(projection)?), @@ -509,17 +577,30 @@ impl TableProvider for BaseTableAdapter { input: Arc, insert_op: InsertOp, ) -> DataFusionResult> { + let has_descriptors = input + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + || (blob_materialize::has_source_scan(&input) + && input + .schema() + .fields() + .iter() + .any(|field| blob_materialize::has_descriptor(field))); if self.blob_schema == BlobSchema::Read && self .schema .fields() .iter() .any(|field| blob_nulls::has_descriptor(field)) + && !has_descriptors { return Err(DataFusionError::NotImplemented( "SQL INSERT into Blob v2 tables requires BlobSchema::Write".into(), )); } + let input = blob_materialize::materialize(input, self.write_schema.as_ref()).await?; let mode = match insert_op { InsertOp::Append => WriteMode::Append, InsertOp::Overwrite => WriteMode::Overwrite, diff --git a/rust/lancedb/src/table/datafusion/blob_materialize.rs b/rust/lancedb/src/table/datafusion/blob_materialize.rs new file mode 100644 index 000000000..22d0a023d --- /dev/null +++ b/rust/lancedb/src/table/datafusion/blob_materialize.rs @@ -0,0 +1,615 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Preserve scan provenance until INSERT can materialize source-owned blobs. +//! +//! External descriptors remain references and must satisfy the destination's +//! existing external-base policy; source authorization grants no target trust. + +use std::fmt; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use datafusion_common::{DataFusionError, Result, tree_node::TreeNodeRecursion}; +use datafusion_execution::{SendableRecordBatchStream, TaskContext}; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::{ + PhysicalExpr, ScalarFunctionExpr, + expressions::{CastExpr, Column, Literal}, +}; +use datafusion_physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, + coalesce_partitions::CoalescePartitionsExec, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + filter::FilterExec, + limit::{GlobalLimitExec, LocalLimitExec}, + projection::ProjectionExec, + repartition::RepartitionExec, + sorts::{sort::SortExec, sort_preserving_merge::SortPreservingMergeExec}, + stream::RecordBatchStreamAdapter, +}; +use futures::{FutureExt, TryStreamExt, future::BoxFuture}; +use lance::{Dataset, dataset::BlobV2BatchRewritePlan}; +use lance_core::{ + ROW_ADDR, + datatypes::{BlobV2Layout, Schema as LanceSchema}, +}; + +use super::{BaseTable, MetadataEraserExec, blob_nulls}; +use crate::{ + query::{QueryExecutionOptions, QueryRequest, Select}, + table::AnyQuery, +}; + +const HIDDEN_ROW_ADDR: &str = "__lancedb_blob_rowaddr"; + +// Expressions such as CASE can retain the descriptor layout while dropping +// extension metadata. They still require proven provenance before writing. +pub(super) fn has_descriptor(field: &Field) -> bool { + contains_layout(field.data_type(), BlobV2Layout::Descriptor) +} + +fn descriptor_for_target(input: &Field, target: &Field) -> bool { + if crate::blob::is_blob(target) { + return matches!(input.data_type(), DataType::Struct(fields) + if BlobV2Layout::classify(fields) == Some(BlobV2Layout::Descriptor)); + } + match (input.data_type(), target.data_type()) { + (DataType::Struct(input), DataType::Struct(target)) => target.iter().any(|target| { + input + .find(target.name()) + .is_some_and(|(_, input)| descriptor_for_target(input, target)) + }), + ( + DataType::List(input) | DataType::LargeList(input) | DataType::FixedSizeList(input, _), + DataType::List(target) + | DataType::LargeList(target) + | DataType::FixedSizeList(target, _), + ) => descriptor_for_target(input, target), + _ => false, + } +} + +fn contains_layout(data_type: &DataType, layout: BlobV2Layout) -> bool { + match data_type { + DataType::Struct(fields) => { + BlobV2Layout::classify(fields) == Some(layout) + || fields + .iter() + .any(|field| contains_layout(field.data_type(), layout)) + } + DataType::List(item) | DataType::LargeList(item) | DataType::FixedSizeList(item, _) => { + contains_layout(item.data_type(), layout) + } + _ => false, + } +} + +pub(super) fn has_source_scan(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.children().iter().any(|child| has_source_scan(child)) +} + +#[expect( + deprecated, + reason = "DataFusion 55 still accepts CoalesceBatchesExec plans" +)] +fn preserves_row_identity(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input + .downcast_ref::() + .is_some() + || input.downcast_ref::().is_some() +} + +fn provenance_error(detail: impl fmt::Display) -> DataFusionError { + DataFusionError::Plan(format!( + "Blob INSERT SELECT requires descriptors from one source table snapshot with an \ + unambiguous row address; {detail}. JOIN, UNION, aggregation, and computed blob \ + descriptors are not supported" + )) +} + +/// A transparent scan boundary. It retains the snapshot and scan request, rather +/// than exposing a system column to SELECT * or fetching any payloads on reads. +#[derive(Debug)] +pub(super) struct BlobScanExec { + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, +} + +impl BlobScanExec { + pub(super) fn new( + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, + ) -> Self { + Self { + input, + source, + dataset, + query, + options, + } + } + + async fn with_row_address(&self) -> Result { + let mut query = self.query.clone(); + let Select::Columns(columns) = &mut query.select else { + return Err(provenance_error( + "source scan has no explicit column projection", + )); + }; + if !columns.iter().any(|name| name == ROW_ADDR) { + columns.push(ROW_ADDR.to_owned()); + } + let plan = self + .source + .create_plan(&AnyQuery::Query(query), self.options.clone()) + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + let plan = blob_nulls::mask_plan(plan)?; + let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let schema = plan.schema(); + let mut projection: Vec<(Arc, String)> = self + .input + .schema() + .fields() + .iter() + .map(|field| { + Ok(( + Arc::new(Column::new(field.name(), schema.index_of(field.name())?)) as _, + field.name().clone(), + )) + }) + .collect::>()?; + projection.push(( + Arc::new(Column::new(ROW_ADDR, schema.index_of(ROW_ADDR)?)), + HIDDEN_ROW_ADDR.into(), + )); + Ok(Provenance { + plan: Arc::new(ProjectionExec::try_new(projection, plan)?), + dataset: self.dataset.clone(), + fields: self + .input + .schema() + .fields() + .iter() + .map(|field| Some(field.name().clone())) + .collect(), + }) + } +} + +impl DisplayAs for BlobScanExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "BlobScanExec: version={}", + self.dataset.version().version + ) + } +} + +impl ExecutionPlan for BlobScanExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "BlobScanExec" + } + fn properties(&self) -> &Arc { + self.input.properties() + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid scan children"))?; + Ok(Arc::new(Self::new( + input, + self.source.clone(), + self.dataset.clone(), + self.query.clone(), + self.options.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + self.input.execute(partition, context) + } +} + +struct Provenance { + plan: Arc, + dataset: Arc, + // Source field path for each output column, before the hidden address. + fields: Vec>, +} + +fn source_field(expr: &Arc, fields: &[Option]) -> Option { + if let Some(column) = expr.downcast_ref::() { + return fields.get(column.index()).cloned().flatten(); + } + let call = expr.downcast_ref::()?; + call.fun().inner().downcast_ref::()?; + let (root, path) = call.args().split_first()?; + let mut source = source_field(root, fields)?; + for component in path { + let name = component + .downcast_ref::()? + .value() + .try_as_str() + .flatten()?; + source.push('.'); + source.push_str(name); + } + Some(source) +} + +fn with_provenance(input: Arc) -> BoxFuture<'static, Result> { + async move { + if let Some(scan) = input.downcast_ref::() { + return scan.with_row_address().await; + } + let children = input.children(); + // An explicit allowlist keeps row identity from silently propagating + // through a future operator that changes cardinality or column meaning. + if children.len() != 1 || !preserves_row_identity(&input) { + return Err(provenance_error(format!( + "cannot establish provenance through {}", + input.name() + ))); + } + let mut provenance = with_provenance(children[0].clone()).await?; + if let Some(projection) = input.downcast_ref::() { + let fields = projection + .expr() + .iter() + .map(|expr| source_field(&expr.expr, &provenance.fields)) + .collect(); + let mut expressions: Vec<(Arc, String)> = projection + .expr() + .iter() + .map(|expr| (expr.expr.clone(), expr.alias.clone())) + .collect(); + expressions.push(( + Arc::new(Column::new( + HIDDEN_ROW_ADDR, + provenance.plan.schema().fields().len() - 1, + )), + HIDDEN_ROW_ADDR.into(), + )); + provenance.plan = Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + provenance.fields = fields; + } else { + if input.schema() != children[0].schema() { + return Err(provenance_error(format!( + "{} changes the source schema", + input.name() + ))); + } + provenance.plan = input.replace_children( + vec![provenance.plan], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + } + Ok(provenance) + } + .boxed() +} + +/// Defer only a container coercion whose Blob leaves retain their named paths. +/// Descriptor leaves are atomic: casting their members is never provenance. +fn can_defer_blob_cast(source: &Field, cast_type: &DataType, target: &Field) -> bool { + if crate::blob::is_blob(target) { + let (DataType::Struct(source), DataType::Struct(cast)) = (source.data_type(), cast_type) + else { + return false; + }; + return BlobV2Layout::classify(source) == Some(BlobV2Layout::Descriptor) + && (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Logical) + || (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Descriptor) + && source.len() == cast.len() + && source.iter().zip(cast).all(|(source, cast)| { + source.name() == cast.name() && source.data_type() == cast.data_type() + }))); + } + match (source.data_type(), cast_type, target.data_type()) { + (DataType::Struct(source), DataType::Struct(cast), DataType::Struct(target)) => { + source.len() == cast.len() + && source.len() == target.len() + && target.iter().all(|target| { + source + .find(target.name()) + .zip(cast.find(target.name())) + .is_some_and(|((_, source), (_, cast))| { + can_defer_blob_cast(source, cast.data_type(), target) + }) + }) + } + (DataType::List(source), DataType::List(cast), DataType::List(target)) + | (DataType::LargeList(source), DataType::LargeList(cast), DataType::LargeList(target)) => { + can_defer_blob_cast(source, cast.data_type(), target) + } + ( + DataType::FixedSizeList(source, source_len), + DataType::FixedSizeList(cast, cast_len), + DataType::FixedSizeList(target, target_len), + ) => { + source_len == cast_len + && source_len == target_len + && can_defer_blob_cast(source, cast.data_type(), target) + } + _ => !has_descriptor(source) && cast_type == target.data_type(), + } +} + +pub(super) async fn materialize( + input: Arc, + target_schema: &Schema, +) -> Result> { + if !target_schema + .fields() + .iter() + .any(|field| crate::blob::field_tree_has_blob_v2(field)) + { + return Ok(input); + } + // INSERT may cast containers for metadata, field order, scalar siblings, + // or a Write adapter's logical layout. Bind the original Blob leaves and + // materialize before applying the target coercion. Other expressions still + // have to pass the Column/GetField provenance checks below. + let input = if let Some(projection) = input.downcast_ref::() { + let mut changed = false; + let expressions = projection + .expr() + .iter() + .map(|projected| { + let mut expr = projected.expr.clone(); + if let Some(cast) = expr.downcast_ref::() + && let Ok(target) = target_schema.field_with_name(&projected.alias) + && crate::blob::field_tree_has_blob_v2(target) + && let source = cast + .expr() + .return_field(projection.input().schema().as_ref())? + && has_descriptor(&source) + { + if !can_defer_blob_cast( + &source, + &cast.data_type(projection.input().schema().as_ref())?, + target, + ) { + return Err(provenance_error(format!( + "cast of column '{}' does not preserve Blob leaf identity", + projected.alias + ))); + } + expr = cast.expr().clone(); + changed = true; + } + Ok((expr, projected.alias.clone())) + }) + .collect::>>()?; + if changed { + Arc::new(ProjectionExec::try_new( + expressions, + projection.input().clone(), + )?) as Arc + } else { + input + } + } else { + input + }; + let rewrite_columns: Vec = input + .schema() + .fields() + .iter() + .map(|field| { + target_schema + .field_with_name(field.name()) + .is_ok_and(|target| descriptor_for_target(field, target)) + }) + .collect(); + if !rewrite_columns.iter().any(|rewrite| *rewrite) { + return Ok(input); + } + let provenance = with_provenance(input.clone()).await?; + let mut source_schema = LanceSchema::default(); + let mut expressions: Vec<(Arc, String)> = Vec::new(); + for (index, (field, source)) in input + .schema() + .fields() + .iter() + .zip(&provenance.fields) + .enumerate() + { + let name = format!("__lancedb_blob_column_{index}"); + if rewrite_columns[index] { + let source = source.as_ref().ok_or_else(|| { + provenance_error(format!("column '{}' has no source", field.name())) + })?; + let mut source_field = provenance + .dataset + .schema() + .field(source) + .ok_or_else(|| provenance_error(format!("source field '{source}' is missing")))? + .clone(); + if !crate::blob::field_tree_has_blob_v2(&Field::from(&source_field)) { + return Err(provenance_error(format!( + "source field '{source}' is not a Blob v2 column" + ))); + } + source_field.name = name.clone(); + source_schema.fields.push(source_field); + } + expressions.push((Arc::new(Column::new(field.name(), index)), name)); + } + expressions.push(( + Arc::new(Column::new(HIDDEN_ROW_ADDR, provenance.fields.len())), + ROW_ADDR.into(), + )); + let plan: Arc = + Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + // preserve_managed=false forces even managed source payloads to become + // target-owned bytes instead of retaining source storage references. + let rewrite = Arc::new(BlobV2BatchRewritePlan::try_new( + &source_schema, + plan.schema().as_ref(), + false, + false, + )?); + let schema = Arc::new(Schema::new( + rewrite + .output_schema() + .fields() + .iter() + .zip(input.schema().fields()) + .map(|(rewritten, original)| rewritten.as_ref().clone().with_name(original.name())) + .collect::>(), + )); + let plan = Arc::new(MaterializeBlobsExec::new( + plan, + provenance.dataset, + rewrite, + schema, + )); + super::cast::cast_to_table_schema(plan, target_schema) + .map_err(|error| DataFusionError::External(Box::new(error))) +} + +struct MaterializeBlobsExec { + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + properties: Arc, +} + +impl fmt::Debug for MaterializeBlobsExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MaterializeBlobsExec") + .field("input", &self.input) + .finish_non_exhaustive() + } +} + +impl MaterializeBlobsExec { + fn new( + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + ) -> Self { + // Rewriting changes column types; descriptor equivalences/orderings do + // not describe the resulting payload structs. + let properties = Arc::new(PlanProperties::new( + datafusion_physical_expr::EquivalenceProperties::new(schema.clone()), + datafusion_physical_expr::Partitioning::UnknownPartitioning( + input.output_partitioning().partition_count(), + ), + input.properties().emission_type, + input.properties().boundedness, + )); + Self { + input, + dataset, + rewrite, + schema, + properties, + } + } +} + +impl DisplayAs for MaterializeBlobsExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "MaterializeBlobsExec") + } +} + +impl ExecutionPlan for MaterializeBlobsExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "MaterializeBlobsExec" + } + fn properties(&self) -> &Arc { + &self.properties + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid rewrite children"))?; + Ok(Arc::new(Self::new( + input, + self.dataset.clone(), + self.rewrite.clone(), + self.schema.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + let dataset = self.dataset.clone(); + let rewrite = self.rewrite.clone(); + let schema = self.schema.clone(); + let stream = self + .input + .execute(partition, context)? + .and_then(move |batch| { + let dataset = dataset.clone(); + let rewrite = rewrite.clone(); + let schema = schema.clone(); + async move { + let batch = rewrite.transform_batch(&dataset, batch).await?; + Ok(RecordBatch::try_new(schema, batch.columns().to_vec())?) + } + }); + Ok(Box::pin(RecordBatchStreamAdapter::new( + self.schema.clone(), + stream, + ))) + } +} diff --git a/rust/lancedb/src/table/datafusion/insert.rs b/rust/lancedb/src/table/datafusion/insert.rs index ec1e603d2..a2d5f34c9 100644 --- a/rust/lancedb/src/table/datafusion/insert.rs +++ b/rust/lancedb/src/table/datafusion/insert.rs @@ -195,6 +195,7 @@ impl ExecutionPlan for InsertExec { context: Arc, ) -> DataFusionResult { let input_stream = self.input.execute(partition, context)?; + let input_plan = self.input.clone(); let dataset = self.dataset.clone(); let mut write_params = self.write_params.clone(); let partial_transactions = self.partial_transactions.clone(); @@ -227,6 +228,9 @@ impl ExecutionPlan for InsertExec { )); let stream = futures::stream::once(async move { + // Source blob snapshots must outlive the final target commit, not + // only the consumption of the input stream. + let _input_plan = input_plan; if let Some(tracker) = tracker && write_params.write_progress.is_none() { diff --git a/rust/lancedb/src/table/delta.rs b/rust/lancedb/src/table/delta.rs new file mode 100644 index 000000000..6b2bff241 --- /dev/null +++ b/rust/lancedb/src/table/delta.rs @@ -0,0 +1,969 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Streaming row changes between two persisted table versions. + +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_schema::{Schema as ArrowSchema, SchemaRef}; +use datafusion_common::DataFusionError; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use futures::stream; +use lance::Dataset; +use lance::dataset::delta::{DatasetDelta, DatasetDeltaBuilder}; +use lance::dataset::scanner::DatasetRecordBatchStream; +use lance::dataset::transaction::{Operation, Transaction}; +use lance_core::{ROW_CREATED_AT_VERSION_FIELD, ROW_ID_FIELD, ROW_LAST_UPDATED_AT_VERSION_FIELD}; + +use crate::error::{Error, Result}; + +/// A version or tag that identifies one end of a [`TableDelta`]. +/// +/// Version numbers start at 1. Tags are resolved on the table handle's current +/// branch; a tag that belongs to another branch is rejected instead of being +/// followed to that branch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeltaRef { + /// A persisted table version on the current branch. + Version(u64), + /// A tag that points at a version on the current branch. + Tag(String), +} + +impl From for DeltaRef { + fn from(version: u64) -> Self { + Self::Version(version) + } +} + +impl From<&str> for DeltaRef { + fn from(tag: &str) -> Self { + Self::Tag(tag.to_string()) + } +} + +impl From for DeltaRef { + fn from(tag: String) -> Self { + Self::Tag(tag) + } +} + +/// Streaming row changes between two versions of an embedded LanceDB table. +/// +/// A delta is created by [`crate::Table::delta`]. The two endpoints are +/// resolved when the delta is created, so moving a tag or advancing the table +/// afterwards does not change what the delta compares. +/// +/// Row-level readers require stable row ids at both endpoints. Tables created +/// with the default local settings do not enable them; create the table with +/// `storage_options={"new_table_enable_stable_row_ids": "true"}` to use +/// [`Self::inserted_rows`], [`Self::updated_rows`], [`Self::upserted_rows`], +/// and [`Self::deleted_row_ids`]. [`Self::list_transactions`] works without +/// stable row ids. +/// +/// A nonempty range that contains a `Restore` rejects the row-level readers, +/// because a restored snapshot can retain older row-version metadata that the +/// delta readers would omit. The same happens when transaction history in the +/// range is incomplete. Recompute the checkpoint with a full rescan and +/// reinitialize it at the end version; [`Self::list_transactions`] remains +/// available. +pub struct TableDelta { + /// The resolved start endpoint. Kept alongside the numeric version so the + /// handle remains pinned even if the source table is checked out or moves + /// forward later. + begin: Dataset, + /// The resolved end endpoint. Kept for schema construction and to pin the + /// endpoint independently of the table handle. + end: Dataset, + begin_version: u64, + end_version: u64, + delta: DatasetDelta, + transactions: Vec, + row_change_error: Option, + row_schema: SchemaRef, + deleted_schema: SchemaRef, +} + +impl std::fmt::Debug for TableDelta { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TableDelta") + .field("begin_version", &self.begin_version) + .field("end_version", &self.end_version) + .finish_non_exhaustive() + } +} + +impl TableDelta { + /// Resolve both endpoints from the snapshot currently visible through + /// `visible`. The table wrapper is not touched, so its checkout state and + /// version stay exactly as they were. + pub(crate) async fn from_visible_snapshot( + visible: &Dataset, + from_version: DeltaRef, + to_version: Option, + ) -> Result { + let begin = resolve_endpoint(visible, from_version, "from_version").await?; + let end = match to_version { + Some(to_version) => resolve_endpoint(visible, to_version, "to_version").await?, + // The visible snapshot is the implicit target, including when the + // table handle is in time-travel mode. + None => visible.clone(), + }; + + let begin_version = begin.version().version; + let end_version = end.version().version; + if begin_version > end_version { + return Err(Error::InvalidInput { + message: format!( + "delta begin version {begin_version} is newer than end version {end_version}; \ + from_version must be less than or equal to to_version" + ), + }); + } + + let delta = DatasetDeltaBuilder::new(end.clone()) + .with_begin_version(begin_version) + .with_end_version(end_version) + .build()?; + + // Read the pinned range once so every row reader shares the same + // Restore/history check instead of scanning it again. Use the end + // dataset because its branch is the one the delta is pinned to. + let (transactions, row_change_error) = if begin_version == end_version { + (Vec::new(), None) + } else { + read_range_history(&end, begin_version, end_version).await? + }; + + Ok(Self { + row_schema: row_change_schema(&end), + deleted_schema: deleted_row_ids_schema(), + begin, + end, + begin_version, + end_version, + delta, + transactions, + row_change_error, + }) + } + + /// The version this delta starts from (exclusive). + pub fn begin_version(&self) -> u64 { + self.begin_version + } + + /// The version this delta ends at (inclusive). + pub fn end_version(&self) -> u64 { + self.end_version + } + + /// Stream rows inserted in `(begin_version, end_version]`. + /// + /// Each batch carries the table columns plus `_rowid`, + /// `_row_created_at_version`, and `_row_last_updated_at_version`, read as + /// of the end version. + pub async fn inserted_rows(&self) -> Result { + self.scan_rows(DeltaRowChange::Inserted).await + } + + /// Stream rows updated in `(begin_version, end_version]`. + /// + /// Newly inserted rows are excluded; see [`Self::upserted_rows`] for both. + /// Each batch carries the table columns plus `_rowid`, + /// `_row_created_at_version`, and `_row_last_updated_at_version`, read as + /// of the end version. + pub async fn updated_rows(&self) -> Result { + self.scan_rows(DeltaRowChange::Updated).await + } + + /// Stream inserted and updated rows in `(begin_version, end_version]`. + /// + /// Each batch carries the table columns plus `_rowid`, + /// `_row_created_at_version`, and `_row_last_updated_at_version`, read as + /// of the end version. + pub async fn upserted_rows(&self) -> Result { + self.scan_rows(DeltaRowChange::Upserted).await + } + + /// Stream the ids of rows deleted in `(begin_version, end_version]`. + /// + /// Each batch carries one `_rowid` column of type `UInt64`. Deleted rows + /// are not reconstructed from earlier versions. + pub async fn deleted_row_ids(&self) -> Result { + if self.begin_version == self.end_version { + return Ok(empty_stream(self.deleted_schema.clone())); + } + self.ensure_row_changes_allowed()?; + Ok(self.delta.get_deleted_row_ids().await?) + } + + /// List the transactions committed in `(begin_version, end_version]`. + /// + /// Unlike the row readers, this does not require stable row ids. A version + /// with no readable transaction entry is skipped; the returned list keeps + /// any transactions that are available. + pub async fn list_transactions(&self) -> Result> { + Ok(self.transactions.clone()) + } + + async fn scan_rows(&self, change: DeltaRowChange) -> Result { + if self.begin_version == self.end_version { + return Ok(empty_stream(self.row_schema.clone())); + } + self.ensure_row_changes_allowed()?; + let rows = match change { + DeltaRowChange::Inserted => self.delta.get_inserted_rows().await?, + DeltaRowChange::Updated => self.delta.get_updated_rows().await?, + DeltaRowChange::Upserted => self.delta.get_upserted_rows().await?, + }; + Ok(rows) + } + + fn ensure_row_changes_allowed(&self) -> Result<()> { + if let Some(message) = &self.row_change_error { + return Err(Error::InvalidInput { + message: message.clone(), + }); + } + self.ensure_stable_row_ids() + } + + fn ensure_stable_row_ids(&self) -> Result<()> { + if self.begin.manifest().uses_stable_row_ids() && self.end.manifest().uses_stable_row_ids() + { + return Ok(()); + } + Err(Error::InvalidInput { + message: format!( + "row-level delta requires stable row ids at both endpoints (versions {} and {}); \ + create the table with storage_options={{\"new_table_enable_stable_row_ids\": \"true\"}} \ + to use inserted_rows(), updated_rows(), upserted_rows(), or deleted_row_ids(). \ + list_transactions() is available without stable row ids", + self.begin_version, self.end_version + ), + }) + } +} + +/// Read the pinned range's transactions through Lance's lineage-aware, +/// cache-bypassing path. This matters when a table is dropped and recreated at +/// the same URI in the same session: `read_transaction()` can return the old +/// incarnation's transaction for a version number. +async fn read_range_history( + end: &Dataset, + begin_version: u64, + end_version: u64, +) -> Result<(Vec, Option)> { + let mut transactions = Vec::new(); + let mut missing_transactions = 0u64; + let mut has_restore = false; + + for version in (begin_version + 1)..=end_version { + let record = end.read_version_transaction(version).await?; + match record.transaction { + Some(transaction) => { + if matches!(&transaction.operation, Operation::Restore { .. }) { + has_restore = true; + } + transactions.push(transaction); + } + // A missing entry is readable as a gap for list_transactions(), but + // it cannot prove the version was not a Restore. + None => missing_transactions += 1, + } + } + + let row_change_error = row_change_error( + begin_version, + end_version, + has_restore, + missing_transactions, + ); + Ok((transactions, row_change_error)) +} + +fn row_change_error( + begin_version: u64, + end_version: u64, + has_restore: bool, + missing_transactions: u64, +) -> Option { + if begin_version == end_version { + return None; + } + if has_restore { + return Some(format!( + "row-level table.delta cannot verify versions ({begin_version}, {end_version}] \ + because the range contains a Restore; a restore can reintroduce rows with older \ + row-version metadata that the delta readers omit. Recompute the checkpoint with a \ + full rescan and reinitialize it at version {end_version}, or use \ + list_transactions() to inspect the range" + )); + } + + if missing_transactions > 0 { + let expected_transactions = end_version - begin_version; + return Some(format!( + "row-level table.delta cannot verify versions ({begin_version}, {end_version}] \ + because transaction history is missing for {missing_transactions} of \ + {expected_transactions} versions; a Restore may be hidden. Recompute the checkpoint \ + with a full rescan and reinitialize it at version {end_version}, or use \ + list_transactions() to inspect the available history" + )); + } + None +} + +#[derive(Clone, Copy)] +enum DeltaRowChange { + Inserted, + Updated, + Upserted, +} + +async fn resolve_endpoint(visible: &Dataset, endpoint: DeltaRef, field: &str) -> Result { + let current_branch = visible.manifest().branch.clone(); + match endpoint { + DeltaRef::Version(version) => { + if version == 0 { + return Err(Error::InvalidInput { + message: format!( + "{field} version 0 is not a persisted table version; delta versions start at 1" + ), + }); + } + visible + .checkout_version(version) + .await + .map_err(|error| endpoint_error(error, field, current_branch.as_deref())) + } + DeltaRef::Tag(tag) => { + let tag_contents = visible + .tags() + .get(&tag) + .await + .map_err(|error| endpoint_error(error, field, current_branch.as_deref()))?; + if tag_contents.version == 0 { + return Err(Error::InvalidInput { + message: format!( + "{field} tag '{tag}' points at version 0, which is not a persisted table version" + ), + }); + } + let tag_branch = normalize_branch(tag_contents.branch.as_deref()); + if tag_branch != current_branch { + return Err(Error::InvalidInput { + message: format!( + "{field} tag '{tag}' belongs to branch '{}', but this table is on branch '{}'; \ + table.delta only compares endpoints on the current branch", + branch_label(tag_branch.as_deref()), + branch_label(current_branch.as_deref()) + ), + }); + } + visible + .checkout_version(tag_contents.version) + .await + .map_err(|error| endpoint_error(error, field, current_branch.as_deref())) + } + } +} + +fn endpoint_error(error: lance::Error, field: &str, branch: Option<&str>) -> Error { + match error { + lance::Error::VersionNotFound { message } => Error::InvalidInput { + message: format!( + "{field} does not exist on branch '{}': {message}", + branch_label(branch) + ), + }, + lance::Error::DatasetNotFound { source, .. } => Error::InvalidInput { + message: format!( + "{field} does not exist on branch '{}': {source}", + branch_label(branch) + ), + }, + lance::Error::RefNotFound { message } => Error::InvalidInput { + message: format!("{field} tag does not exist: {message}"), + }, + other => other.into(), + } +} + +fn normalize_branch(branch: Option<&str>) -> Option { + match branch { + None | Some("main") => None, + Some(name) => Some(name.to_string()), + } +} + +fn branch_label(branch: Option<&str>) -> &str { + branch.unwrap_or("main") +} + +fn row_change_schema(end: &Dataset) -> SchemaRef { + let base = ArrowSchema::from(end.schema()); + let mut fields = base.fields().to_vec(); + fields.push(Arc::new((*ROW_ID_FIELD).clone())); + fields.push(Arc::new((*ROW_CREATED_AT_VERSION_FIELD).clone())); + fields.push(Arc::new((*ROW_LAST_UPDATED_AT_VERSION_FIELD).clone())); + Arc::new(ArrowSchema::new_with_metadata( + fields, + base.metadata().clone(), + )) +} + +fn deleted_row_ids_schema() -> SchemaRef { + Arc::new(ArrowSchema::new(vec![Arc::new((*ROW_ID_FIELD).clone())])) +} + +fn empty_stream(schema: SchemaRef) -> DatasetRecordBatchStream { + let batches = stream::empty::>(); + DatasetRecordBatchStream::new(Box::pin(RecordBatchStreamAdapter::new(schema, batches))) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{Array, Int32Array, RecordBatch, UInt64Array}; + use arrow_schema::{DataType, Field, Schema as ArrowSchema}; + use futures::TryStreamExt; + use lance::dataset::WriteParams; + use lance::io::RecordBatchStream; + use lance_file::format::{MAGIC, MAJOR_VERSION, MINOR_VERSION}; + use lance_io::object_writer::ObjectWriter; + use lance_io::traits::{WriteExt, Writer}; + use lance_table::format::pb; + use tempfile::tempdir; + + use super::*; + use crate::connect; + use crate::query::{ExecutableQuery, QueryBase}; + use crate::table::{BaseTable, NativeTable, WriteOptions}; + + fn rows(ids: &[i32]) -> RecordBatch { + let schema = Arc::new(ArrowSchema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("value", DataType::Int32, false), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from(ids.to_vec())), + Arc::new(Int32Array::from(vec![0; ids.len()])), + ], + ) + .unwrap() + } + + async fn collect(stream: DatasetRecordBatchStream) -> Vec { + stream.try_collect().await.unwrap() + } + + fn i32_column(batches: &[RecordBatch], name: &str) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column_by_name(name) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + + fn u64_column(batches: &[RecordBatch], name: &str) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column_by_name(name) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + + fn schema_names(schema: &ArrowSchema) -> Vec { + schema + .fields() + .iter() + .map(|field| field.name().clone()) + .collect() + } + + fn stable_row_ids() -> WriteOptions { + WriteOptions { + lance_write_params: Some(WriteParams { + enable_stable_row_ids: true, + ..Default::default() + }), + } + } + + #[tokio::test] + async fn test_delta_streams_versions_tags_and_checkout() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()); + let conn = conn.execute().await.unwrap(); + + let table = conn + .create_table("t", rows(&[0, 1])) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), 1); + + table.add(rows(&[2])).execute().await.unwrap(); + assert_eq!(table.version().await.unwrap(), 2); + let mut tags = table.tags().await.unwrap(); + tags.create("baseline", 2).await.unwrap(); + + table + .update() + .column("value", "value + 10") + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), 3); + + // Remember the stable row id before deletion so the deleted reader can + // be checked against a value derived from the table, not the delta. + let row_id_batches = table + .query() + .only_if("id = 1") + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let deleted_row_id = u64_column(&row_id_batches, ROW_ID_FIELD.name())[0]; + + table.delete("id = 1").await.unwrap(); + assert_eq!(table.version().await.unwrap(), 4); + + let delta = table.delta(DeltaRef::Version(1), None).await.unwrap(); + assert_eq!(delta.begin_version(), 1); + assert_eq!(delta.end_version(), 4); + + let inserted = collect(delta.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![2]); + assert_eq!( + schema_names(&inserted[0].schema()), + vec![ + "id".to_string(), + "value".to_string(), + "_rowid".to_string(), + "_row_created_at_version".to_string(), + "_row_last_updated_at_version".to_string(), + ] + ); + + let updated = collect(delta.updated_rows().await.unwrap()).await; + assert_eq!(i32_column(&updated, "id"), vec![0]); + + let upserted = collect(delta.upserted_rows().await.unwrap()).await; + let mut upserted_ids = i32_column(&upserted, "id"); + upserted_ids.sort_unstable(); + assert_eq!(upserted_ids, vec![0, 2]); + + let deleted = collect(delta.deleted_row_ids().await.unwrap()).await; + assert_eq!( + u64_column(&deleted, ROW_ID_FIELD.name()), + vec![deleted_row_id] + ); + assert_eq!( + schema_names(&deleted[0].schema()), + vec!["_rowid".to_string()] + ); + assert_eq!( + deleted[0] + .column_by_name(ROW_ID_FIELD.name()) + .unwrap() + .data_type(), + &DataType::UInt64 + ); + + let transactions = delta.list_transactions().await.unwrap(); + assert_eq!( + transactions + .iter() + .map(|transaction| transaction.operation.name()) + .collect::>(), + vec!["Append", "Update", "Delete"] + ); + + // A tag is resolved on the current branch and can be either endpoint. + let from_tag = table.delta("baseline", None).await.unwrap(); + assert_eq!(from_tag.begin_version(), 2); + assert_eq!(from_tag.end_version(), 4); + let mut updated_ids = + i32_column(&collect(from_tag.updated_rows().await.unwrap()).await, "id"); + updated_ids.sort_unstable(); + // Row 2 was created exactly at the baseline, so the later update to it + // counts as an update in this range. + assert_eq!(updated_ids, vec![0, 2]); + + let to_tag = table + .delta(1u64, Some(DeltaRef::Tag("baseline".to_string()))) + .await + .unwrap(); + assert_eq!(to_tag.end_version(), 2); + let inserted = collect(to_tag.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![2]); + + // Moving a tag does not change an existing delta; a new delta sees the + // new target. + tags.update("baseline", 3).await.unwrap(); + assert_eq!(from_tag.begin_version(), 2); + assert_eq!(to_tag.end_version(), 2); + let moved_tag = table.delta("baseline", None).await.unwrap(); + assert_eq!(moved_tag.begin_version(), 3); + + // Equal endpoints are empty but keep the reader schemas, without + // needing to scan or require stable row ids again. + let equal = table.delta(2u64, Some(DeltaRef::Version(2))).await.unwrap(); + let inserted = collect(equal.inserted_rows().await.unwrap()).await; + assert!(inserted.is_empty()); + let inserted_schema = equal.inserted_rows().await.unwrap().schema(); + assert_eq!( + schema_names(&inserted_schema), + vec![ + "id".to_string(), + "value".to_string(), + "_rowid".to_string(), + "_row_created_at_version".to_string(), + "_row_last_updated_at_version".to_string(), + ] + ); + let deleted = collect(equal.deleted_row_ids().await.unwrap()).await; + assert!(deleted.is_empty()); + assert_eq!( + schema_names(&equal.deleted_row_ids().await.unwrap().schema()), + vec!["_rowid".to_string()] + ); + + // Invalid and reversed endpoints are actionable input errors. + for result in [ + table.delta(0u64, None).await, + table.delta(1u64, Some(DeltaRef::Version(0))).await, + table.delta(4u64, Some(DeltaRef::Version(2))).await, + table.delta(999u64, None).await, + table.delta(1u64, Some(DeltaRef::Version(999))).await, + table.delta("missing-tag", None).await, + table + .delta(1u64, Some(DeltaRef::Tag("missing-tag".to_string()))) + .await, + ] { + assert!( + matches!(result, Err(Error::InvalidInput { .. })), + "expected an invalid input error, got {result:?}" + ); + } + + // An omitted target follows the visible checkout and leaves the shared + // table checkout exactly where it was. + table.checkout(2).await.unwrap(); + let checked_out = table.delta(1u64, None).await.unwrap(); + assert_eq!(checked_out.end_version(), 2); + let inserted = collect(checked_out.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![2]); + assert_eq!(table.version().await.unwrap(), 2); + + // An explicit target still works from a pinned handle without moving it. + let explicit = table.delta(1u64, Some(DeltaRef::Version(3))).await.unwrap(); + let mut updated_ids = + i32_column(&collect(explicit.updated_rows().await.unwrap()).await, "id"); + updated_ids.sort_unstable(); + assert_eq!(updated_ids, vec![0, 1]); + assert_eq!(table.version().await.unwrap(), 2); + table.checkout_latest().await.unwrap(); + assert_eq!(table.version().await.unwrap(), 4); + } + + #[tokio::test] + async fn test_delta_resolves_endpoints_on_the_current_branch() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .read_consistency_interval(std::time::Duration::ZERO) + .execute() + .await + .unwrap(); + + let main = conn + .create_table("t", rows(&[0])) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + let fork = main.version().await.unwrap(); + let branch = main.create_branch("exp", fork).await.unwrap(); + + branch.add(rows(&[1])).execute().await.unwrap(); + main.add(rows(&[100, 101, 102])).execute().await.unwrap(); + assert_eq!( + branch.version().await.unwrap(), + main.version().await.unwrap(), + "branch and main must share a version number for this test" + ); + + let mut main_tags = main.tags().await.unwrap(); + main_tags + .create("main-tag", main.version().await.unwrap()) + .await + .unwrap(); + let mut branch_tags = branch.tags().await.unwrap(); + branch_tags + .create("exp-tag", branch.version().await.unwrap()) + .await + .unwrap(); + + // The same-branch tag resolves through the branch, not main's data at + // the same version number. + let branch_delta = branch + .delta(1u64, Some(DeltaRef::Tag("exp-tag".to_string()))) + .await + .unwrap(); + let inserted = collect(branch_delta.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![1]); + + // A tag from another branch is rejected even though its version number + // also exists on this branch. + let wrong_branch = branch.delta("main-tag", None).await; + match wrong_branch { + Err(Error::InvalidInput { message }) => { + assert!(message.contains("main-tag"), "{message}"); + assert!(message.contains("exp"), "{message}"); + assert!(message.contains("main"), "{message}"); + } + other => panic!("expected cross-branch tag rejection, got {other:?}"), + } + + let wrong_branch = main.delta("exp-tag", None).await; + assert!( + matches!(wrong_branch, Err(Error::InvalidInput { .. })), + "main must reject a branch tag" + ); + } + + #[tokio::test] + async fn test_delta_rejects_restore_ranges() { + for mutation in ["update", "delete"] { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table("t", rows(&[0])) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), 1); + + if mutation == "update" { + table.update().column("value", "1").execute().await.unwrap(); + } else { + table.delete("id = 0").await.unwrap(); + } + assert_eq!(table.version().await.unwrap(), 2); + + table.checkout(1).await.unwrap(); + table.restore().await.unwrap(); + assert_eq!(table.version().await.unwrap(), 3); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + + let restore_range = table.delta(2u64, Some(DeltaRef::Version(3))).await.unwrap(); + assert_eq!( + restore_range + .list_transactions() + .await + .unwrap() + .iter() + .map(|transaction| transaction.operation.name()) + .collect::>(), + vec!["Restore"] + ); + for result in [ + restore_range.inserted_rows().await, + restore_range.updated_rows().await, + restore_range.upserted_rows().await, + restore_range.deleted_row_ids().await, + ] { + match result { + Err(Error::InvalidInput { message }) => { + assert!(message.contains("Restore"), "{mutation}: {message}"); + assert!(message.contains("full rescan"), "{mutation}: {message}"); + assert!(message.contains("reinitialize"), "{mutation}: {message}"); + } + Ok(_) => panic!("{mutation}: restore range must be rejected"), + Err(other) => panic!("{mutation}: expected invalid input, got {other:?}"), + } + } + + // A restore in the middle of the range is still unverifiable. + table.add(rows(&[1])).execute().await.unwrap(); + assert_eq!(table.version().await.unwrap(), 4); + match table + .delta(2u64, Some(DeltaRef::Version(4))) + .await + .unwrap() + .upserted_rows() + .await + { + Err(Error::InvalidInput { message }) => { + assert!(message.contains("Restore"), "{mutation}: {message}"); + } + Ok(_) => panic!("{mutation}: restore inside the range must be rejected"), + Err(other) => panic!("{mutation}: expected invalid input, got {other:?}"), + } + + // A restore at the exclusive boundary is the base snapshot, so + // changes after it are usable. + let after_restore = table.delta(3u64, Some(DeltaRef::Version(4))).await.unwrap(); + let inserted = collect(after_restore.inserted_rows().await.unwrap()).await; + assert_eq!(i32_column(&inserted, "id"), vec![1]); + assert_eq!( + after_restore + .list_transactions() + .await + .unwrap() + .iter() + .map(|transaction| transaction.operation.name()) + .collect::>(), + vec!["Append"] + ); + + // Equal endpoints remain empty and do not run the restore guard. + let equal = table.delta(3u64, Some(DeltaRef::Version(3))).await.unwrap(); + assert!( + collect(equal.upserted_rows().await.unwrap()) + .await + .is_empty() + ); + } + } + + #[tokio::test] + async fn test_delta_rejects_missing_transaction_history() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table("t", rows(&[0])) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + table.add(rows(&[1])).execute().await.unwrap(); + let uri = table.uri().await.unwrap(); + + // Simulate a supported dataset whose latest version has no transaction + // entry. Lance cannot then tell us whether that version was a Restore, + // so row readers must fail closed instead of treating it as restore-free. + let dataset = Dataset::open(&uri).await.unwrap(); + let manifest_path = dataset.manifest_location().path.clone(); + let store = dataset.object_store(None).await.unwrap(); + let mut writer = ObjectWriter::new(store.as_ref(), &manifest_path) + .await + .unwrap(); + let mut manifest = pb::Manifest::from(dataset.manifest()); + manifest.transaction_section = None; + manifest.transaction_section_deprecated = None; + manifest.transaction_file = String::new(); + let pos = writer.write_protobuf(&manifest).await.unwrap(); + writer + .write_magics(pos, MAJOR_VERSION, MINOR_VERSION, MAGIC) + .await + .unwrap(); + Writer::shutdown(&mut writer).await.unwrap(); + drop(dataset); + drop(table); + + let table = NativeTable::open(&uri).await.unwrap(); + let delta = table.delta(DeltaRef::Version(1), None).await.unwrap(); + assert!(delta.list_transactions().await.unwrap().is_empty()); + match delta.inserted_rows().await { + Err(Error::InvalidInput { message }) => { + assert!( + message.contains("transaction history is missing"), + "{message}" + ); + assert!(message.contains("full rescan"), "{message}"); + } + Ok(_) => panic!("missing transaction history must fail closed"), + Err(other) => panic!("expected invalid input, got {other:?}"), + } + } + + #[tokio::test] + async fn test_delta_without_stable_row_ids_guides_but_lists_transactions() { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let table = conn.create_table("t", rows(&[0])).execute().await.unwrap(); + table.add(rows(&[1])).execute().await.unwrap(); + let delta = table.delta(1u64, None).await.unwrap(); + + for result in [ + delta.inserted_rows().await, + delta.updated_rows().await, + delta.upserted_rows().await, + delta.deleted_row_ids().await, + ] { + match result { + Err(Error::InvalidInput { message }) => { + assert!( + message.contains("new_table_enable_stable_row_ids"), + "{message}" + ); + assert!(message.contains("list_transactions"), "{message}"); + } + Ok(_) => panic!("row-level delta must require stable row ids"), + Err(other) => panic!("expected invalid input, got {other:?}"), + } + } + + // Transactions remain available without stable row ids. + let transactions = delta.list_transactions().await.unwrap(); + assert_eq!(transactions.len(), 1); + assert_eq!(transactions[0].operation.name(), "Append"); + + // Equal endpoints need no row lineage, so their readers are empty. + let version = table.version().await.unwrap(); + let equal = table + .delta(version, Some(DeltaRef::Version(version))) + .await + .unwrap(); + assert!( + collect(equal.inserted_rows().await.unwrap()) + .await + .is_empty() + ); + assert!( + collect(equal.deleted_row_ids().await.unwrap()) + .await + .is_empty() + ); + } +} diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 021abe5a9..e1c896e9f 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -21,14 +21,16 @@ //! removed by [`prune_sidecars`]. use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt; use std::io::{Cursor, Read}; use std::ops::Range; use arrow_array::{Array, UInt64Array}; +use arrow_schema::{DataType, Schema as ArrowSchema}; use futures::TryStreamExt; use lance::Dataset; use lance::dataset::refs::Ref; -use lance::dataset::transaction::Operation; +use lance::dataset::transaction::{Operation, UpdateMode}; use lance_core::ROW_ADDR; use lance_core::datatypes::{Field as LanceField, Schema as LanceSchema}; use lance_io::object_store::{ObjectStore, uri_to_url}; @@ -40,7 +42,8 @@ use sha2::{Digest, Sha256}; use uuid::Uuid; use crate::table::computed_columns::{ - DEFINITION_VERSION_META_KEY, RECORDED_AT_VERSION_META_KEY, SOURCE_SIGNATURE_META_KEY, + DEFINITION_VERSION_META_KEY, FUNCTION_BINDINGS_META_KEY, PENDING_FILL_SIGNATURE_META_KEY, + RECORDED_AT_VERSION_META_KEY, SOURCE_SIGNATURE_META_KEY, field_root, function_bindings, }; use crate::{Error, Result}; @@ -96,6 +99,56 @@ impl DirtyRows { /// `{fragment id -> row-level dirty state}`. A missing fragment is clean. pub type RowStateMap = BTreeMap; +/// Physical rows whose latest Function outcome is an unresolved failure. +pub type FailureRows = BTreeMap; + +/// Evidence for rows whose latest Function outcome is known. +/// +/// `known_rows` includes both successful and failed observations. +/// `failed_rows` is the failure subset. A missing row is unknown, not clean. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FailureEvidence { + pub known_rows: FailureRows, + pub failed_rows: FailureRows, +} + +impl FailureEvidence { + fn is_empty(&self) -> bool { + self.known_rows.is_empty() && self.failed_rows.is_empty() + } + + fn validate(&self) -> Result<()> { + if self.failed_rows.iter().any(|(fragment_id, failed)| { + !self + .known_rows + .get(fragment_id) + .is_some_and(|known| failed.is_subset(known)) + }) { + return Err(invalid( + "failed rows are not covered by the failure evidence update".to_string(), + )); + } + Ok(()) + } + + fn for_fragments(&self, fragments: &HashSet) -> Self { + Self { + known_rows: self + .known_rows + .iter() + .filter(|(fragment_id, _)| fragments.contains(fragment_id)) + .map(|(fragment_id, rows)| (*fragment_id, rows.clone())) + .collect(), + failed_rows: self + .failed_rows + .iter() + .filter(|(fragment_id, _)| fragments.contains(fragment_id)) + .map(|(fragment_id, rows)| (*fragment_id, rows.clone())) + .collect(), + } + } +} + /// The single owning value of the freshness sidecar. /// /// `SignatureMap` remains the public facade for callers that only need input @@ -105,6 +158,13 @@ pub type RowStateMap = BTreeMap; struct FreshnessState { signatures: SignatureMap, row_state: RowStateMap, + /// Physical offsets with an exact current-generation outcome. + failure_coverage: FailureRows, + /// The failed subset of `failure_coverage`. + failed_rows: FailureRows, + /// Whether the decoded source used the v3 sidecar format that carries + /// failure evidence. Older formats leave failure rows unclassified. + failure_evidence_recorded: bool, basis: String, // A fresh identity for each begin, even when the basis and dirty rows repeat. intent_id: Uuid, @@ -113,6 +173,8 @@ struct FreshnessState { impl FreshnessState { fn normalize(mut self) -> Result { self.row_state.retain(|_, rows| !rows.is_explicitly_empty()); + self.failure_coverage.retain(|_, rows| !rows.is_empty()); + self.failed_rows.retain(|_, rows| !rows.is_empty()); if self .row_state .keys() @@ -122,6 +184,26 @@ impl FreshnessState { "row state names a fragment without a signature".to_string(), )); } + if self + .failure_coverage + .keys() + .chain(self.failed_rows.keys()) + .any(|fragment_id| !self.signatures.contains_key(fragment_id)) + { + return Err(invalid( + "failure evidence names a fragment without a signature".to_string(), + )); + } + if self.failed_rows.iter().any(|(fragment_id, failed)| { + !self + .failure_coverage + .get(fragment_id) + .is_some_and(|covered| failed.is_subset(covered)) + }) { + return Err(invalid( + "failed rows are not covered by failure evidence".to_string(), + )); + } if self .signatures .values() @@ -136,6 +218,38 @@ impl FreshnessState { } Ok(self) } + + fn invalidate_failure_evidence(&mut self, fragments: impl IntoIterator) { + for fragment_id in fragments { + self.failure_coverage.remove(&fragment_id); + self.failed_rows.remove(&fragment_id); + } + } + + fn invalidate_failure_rows(&mut self, rows: &BTreeMap) { + for (fragment_id, rows) in rows { + if let Some(covered) = self.failure_coverage.get_mut(fragment_id) { + *covered -= rows; + } + if self + .failure_coverage + .get(fragment_id) + .is_some_and(RoaringBitmap::is_empty) + { + self.failure_coverage.remove(fragment_id); + } + if let Some(failed) = self.failed_rows.get_mut(fragment_id) { + *failed -= rows; + } + if self + .failed_rows + .get(fragment_id) + .is_some_and(RoaringBitmap::is_empty) + { + self.failed_rows.remove(fragment_id); + } + } + } } /// Opaque accepted-basis evidence returned by [`begin_row_repair`] and required by @@ -396,7 +510,8 @@ const SIDECAR_DIR: &str = "_computed"; const SIDECAR_REF: &str = "sidecar:"; const SIDECAR_MAGIC: &[u8; 4] = b"CSIG"; const SIDECAR_FORMAT_V1: u8 = 1; -const SIDECAR_FORMAT: u8 = 2; +const SIDECAR_FORMAT_V2: u8 = 2; +const SIDECAR_FORMAT: u8 = 3; /// How long an unreferenced sidecar is presumed to be a stamp in flight: /// lance's own threshold for unverified files, independent of how much /// version history a cleanup keeps. @@ -444,9 +559,85 @@ fn encode_legacy_sidecar(map: &SignatureMap) -> Result> { Ok(bytes) } +#[cfg(test)] +fn encode_v2_sidecar(state: &FreshnessState) -> Result> { + let state = state.clone().normalize()?; + let basis_len = u16::try_from(state.basis.len()) + .map_err(|_| invalid("freshness basis exceeds u16 bytes".to_string()))?; + let fragment_count = u32::try_from(state.signatures.len()) + .map_err(|_| invalid("too many fragments for a freshness sidecar".to_string()))?; + let mut bytes = Vec::new(); + bytes.extend_from_slice(SIDECAR_MAGIC); + bytes.push(SIDECAR_FORMAT_V2); + bytes.extend_from_slice(state.intent_id.as_bytes()); + bytes.extend_from_slice(&basis_len.to_le_bytes()); + bytes.extend_from_slice(state.basis.as_bytes()); + bytes.extend_from_slice(&fragment_count.to_le_bytes()); + for (fragment_id, signature) in &state.signatures { + let hash = u64::from_str_radix(signature, 16).map_err(|_| { + invalid(format!( + "signature '{signature}' is not a 64-bit hex digest" + )) + })?; + let rows = state + .row_state + .get(fragment_id) + .cloned() + .unwrap_or_else(|| DirtyRows::Rows(RoaringBitmap::new())); + let (kind, bitmap) = match rows { + DirtyRows::Rows(bitmap) => (0u8, bitmap), + DirtyRows::AllExcept(clean) => (1u8, clean), + }; + bytes.extend_from_slice(&fragment_id.to_le_bytes()); + bytes.extend_from_slice(&hash.to_le_bytes()); + bytes.push(kind); + encode_bitmap(&mut bytes, Some(&bitmap))?; + } + Ok(bytes) +} + +fn encode_bitmap(bytes: &mut Vec, bitmap: Option<&RoaringBitmap>) -> Result<()> { + let Some(bitmap) = bitmap.filter(|bitmap| !bitmap.is_empty()) else { + bytes.extend_from_slice(&0u32.to_le_bytes()); + return Ok(()); + }; + let mut encoded = Vec::with_capacity(bitmap.serialized_size()); + bitmap + .serialize_into(&mut encoded) + .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; + let bitmap_len = u32::try_from(encoded.len()) + .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; + bytes.extend_from_slice(&bitmap_len.to_le_bytes()); + bytes.extend_from_slice(&encoded); + Ok(()) +} + +fn decode_bitmap( + cursor: &mut Cursor<&[u8]>, + malformed: &impl Fn() -> Error, +) -> Result> { + let mut bitmap_len = [0u8; 4]; + cursor + .read_exact(&mut bitmap_len) + .map_err(|_| malformed())?; + let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; + if bitmap_len == 0 { + return Ok(None); + } + let mut encoded = vec![0u8; bitmap_len]; + cursor.read_exact(&mut encoded).map_err(|_| malformed())?; + let mut bitmap_reader = Cursor::new(encoded.as_slice()); + let bitmap = RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; + if bitmap_reader.position() != bitmap_len as u64 { + return Err(malformed()); + } + Ok(Some(bitmap)) +} + /// `CSIG`, format byte, 16-byte intent UUID, basis, entry count, then for each fragment its id, -/// 8-byte signature, dirty-row mode and serialized bitmap. All integers are -/// little-endian. Format 1 remains readable as clean row state. +/// 8-byte signature, dirty-row mode and serialized bitmap. Format 3 appends +/// failure-coverage and failed-row bitmaps. All integers are little-endian. +/// Format 1 remains readable as clean row state. fn encode_sidecar(state: &FreshnessState) -> Result> { let state = state.clone().normalize()?; let basis_len = u16::try_from(state.basis.len()) @@ -475,17 +666,12 @@ fn encode_sidecar(state: &FreshnessState) -> Result> { DirtyRows::Rows(bitmap) => (0u8, bitmap), DirtyRows::AllExcept(clean) => (1u8, clean), }; - let mut encoded = Vec::with_capacity(bitmap.serialized_size()); - bitmap - .serialize_into(&mut encoded) - .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; - let bitmap_len = u32::try_from(encoded.len()) - .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; bytes.extend_from_slice(&fragment_id.to_le_bytes()); bytes.extend_from_slice(&hash.to_le_bytes()); bytes.push(kind); - bytes.extend_from_slice(&bitmap_len.to_le_bytes()); - bytes.extend_from_slice(&encoded); + encode_bitmap(&mut bytes, Some(&bitmap))?; + encode_bitmap(&mut bytes, state.failure_coverage.get(fragment_id))?; + encode_bitmap(&mut bytes, state.failed_rows.get(fragment_id))?; } Ok(bytes) } @@ -501,7 +687,9 @@ fn decode_legacy_sidecar(bytes: &[u8]) -> Result { return Err(malformed()); } let signatures = body - .chunks_exact(12) + .as_chunks::<12>() + .0 + .iter() .map(|entry| { let fragment_id = u32::from_le_bytes(entry[..4].try_into().unwrap()); let hash = u64::from_le_bytes(entry[4..].try_into().unwrap()); @@ -524,7 +712,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { cursor.read_exact(&mut magic).map_err(|_| malformed())?; let mut format = [0u8; 1]; cursor.read_exact(&mut format).map_err(|_| malformed())?; - if &magic != SIDECAR_MAGIC || format[0] != SIDECAR_FORMAT { + if &magic != SIDECAR_MAGIC || !matches!(format[0], SIDECAR_FORMAT_V2 | SIDECAR_FORMAT) { return Err(malformed()); } let mut intent_id = [0u8; 16]; @@ -540,6 +728,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { let mut state = FreshnessState { basis, intent_id: Uuid::from_bytes(intent_id), + failure_evidence_recorded: format[0] == SIDECAR_FORMAT, ..Default::default() }; for _ in 0..count { @@ -552,19 +741,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { cursor.read_exact(&mut signature).map_err(|_| malformed())?; let mut kind = [0u8; 1]; cursor.read_exact(&mut kind).map_err(|_| malformed())?; - let mut bitmap_len = [0u8; 4]; - cursor - .read_exact(&mut bitmap_len) - .map_err(|_| malformed())?; - let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; - let mut encoded = vec![0u8; bitmap_len]; - cursor.read_exact(&mut encoded).map_err(|_| malformed())?; - let mut bitmap_reader = Cursor::new(encoded.as_slice()); - let bitmap = - RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; - if bitmap_reader.position() != bitmap_len as u64 { - return Err(malformed()); - } + let bitmap = decode_bitmap(&mut cursor, &malformed)?.unwrap_or_default(); let dirty = match kind[0] { 0 => DirtyRows::Rows(bitmap), 1 => DirtyRows::AllExcept(bitmap), @@ -580,6 +757,14 @@ fn decode_sidecar(bytes: &[u8]) -> Result { if !dirty.is_explicitly_empty() { state.row_state.insert(fragment_id, dirty); } + if format[0] == SIDECAR_FORMAT { + if let Some(covered) = decode_bitmap(&mut cursor, &malformed)? { + state.failure_coverage.insert(fragment_id, covered); + } + if let Some(failed) = decode_bitmap(&mut cursor, &malformed)? { + state.failed_rows.insert(fragment_id, failed); + } + } } if cursor.position() != bytes.len() as u64 { return Err(malformed()); @@ -738,12 +923,14 @@ async fn referenced_digests(dataset: &Dataset, into: &mut HashSet) -> Re for version in dataset.versions().await? { let at = dataset.checkout_version(version.version).await?; for field in at.schema().fields_pre_order() { - if let Some(digest) = field - .metadata - .get(SOURCE_SIGNATURE_META_KEY) - .and_then(|value| value.strip_prefix(SIDECAR_REF)) - { - into.insert(digest.to_string()); + for key in [SOURCE_SIGNATURE_META_KEY, PENDING_FILL_SIGNATURE_META_KEY] { + if let Some(digest) = field + .metadata + .get(key) + .and_then(|value| value.strip_prefix(SIDECAR_REF)) + { + into.insert(digest.to_string()); + } } } } @@ -759,12 +946,15 @@ enum StoredFreshnessState { Unreadable, } -async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { +async fn load_freshness_state( + dataset: &Dataset, + column: &str, +) -> Result)>> { let Some(encoded) = field_meta(dataset, column, SOURCE_SIGNATURE_META_KEY) else { - return StoredFreshnessState::Absent; + return Ok(None); }; // Inline JSON is the declaration's empty seed and the pre-sidecar form. - let (read, digest) = match encoded.strip_prefix(SIDECAR_REF) { + let read = match encoded.strip_prefix(SIDECAR_REF) { Some(digest) => ( read_sidecar(dataset, digest).await, Some(digest.to_string()), @@ -779,8 +969,14 @@ async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshn None, ), }; - match read { - Ok(state) => StoredFreshnessState::Present { state, digest }, + let (state, digest) = read; + Ok(Some((state?, digest))) +} + +async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { + match load_freshness_state(dataset, column).await { + Ok(Some((state, digest))) => StoredFreshnessState::Present { state, digest }, + Ok(None) => StoredFreshnessState::Absent, Err(error) => { log::warn!( "computed column '{column}' freshness state is unreadable ({error}); every fragment will be recomputed" @@ -820,6 +1016,10 @@ pub struct StalenessPlan { pub dirty: HashSet, /// Current-signature fragments with only some rows dirty. pub row_dirty: RowStateMap, + /// Retained values are current, but unassigned inserted rows need filling. + /// These signatures become completed stamps only after a full null-fill. + #[serde(default)] + pub pending_fill: SignatureMap, /// Fragments a compaction produced from fresh ones, at their current /// signature: not dirty, and for the seal to record. pub inherited: SignatureMap, @@ -845,6 +1045,38 @@ impl StalenessPlan { } } +/// Strict, internally consistent evidence for a Function-column status read. +/// +/// Unlike [`staleness_against`], this value never converts an unreadable +/// sidecar into a conservative recompute plan. Failure coverage may be +/// partial: the caller combines it with live-row freshness and value evidence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StrictFreshness { + /// No freshness certificate is recorded on this dataset version. + /// + /// This does not prove that no refresh was ever attempted; older failed + /// attempts may be untracked. Assignment and value evidence still decide + /// stale versus never computed. + Absent, + /// The sidecar predates failure evidence. Its staleness plan is still + /// usable; row classification may use freshness, values, and assignment + /// evidence outside this sidecar. + Uncertified { staleness: StalenessPlan }, + /// Exact staleness and current-generation failed rows. + Certified { + staleness: StalenessPlan, + failures: FailureEvidence, + }, +} + +fn incomplete_certificate(column: &str, reason: impl fmt::Display) -> Error { + Error::Runtime { + message: format!( + "computed column '{column}' has no complete freshness certificate: {reason}" + ), + } +} + /// A version of the log since the stamp that bears on carrying freshness /// forward: an append, whose fragments hold no computed value yet, or a /// compaction's rewrite groups, consumed and produced fragment ids. @@ -1150,6 +1382,16 @@ pub async fn staleness_against( } StoredFreshnessState::Present { state: stored, .. } => stored, }; + staleness_from_state(dataset, column, definition_version, inputs, stored).await +} + +async fn staleness_from_state( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + stored: FreshnessState, +) -> Result { let stored_version = field_meta(dataset, column, DEFINITION_VERSION_META_KEY); if stored_version.is_some_and(|version| version != definition_version) { return Ok(StalenessPlan { @@ -1174,13 +1416,29 @@ pub async fn staleness_against( let mut inherited = carried.inherited; let mut dirty = carried.dirty_products; let mut row_dirty = RowStateMap::new(); + let pending = match field_meta(dataset, column, PENDING_FILL_SIGNATURE_META_KEY) { + Some(reference) if unrecorded => { + let state = match reference.strip_prefix(SIDECAR_REF) { + Some(digest) => read_sidecar(dataset, digest).await.ok(), + None => None, + }; + state + .filter(|state| state.row_state.is_empty() && state.basis.is_empty()) + .map(|state| state.signatures) + .unwrap_or_default() + } + _ => SignatureMap::new(), + }; + let mut pending_fill = SignatureMap::new(); let mut live = HashSet::new(); let bases = Bases::of(dataset)?; for fragment in dataset.get_fragments() { let id = fragment.id() as u32; live.insert(id); let current = fragment_input_signature(&bases, fragment.metadata(), inputs)?; - if stored.get(&id).or_else(|| inherited.get(&id)) != Some(¤t) { + if !stored.contains_key(&id) && !dirty.contains(&id) && pending.get(&id) == Some(¤t) { + pending_fill.insert(id, current); + } else if stored.get(&id).or_else(|| inherited.get(&id)) != Some(¤t) { dirty.insert(id); } else if let Some(rows) = row_state.get(&id) { row_dirty.insert(id, rows.clone()); @@ -1192,10 +1450,76 @@ pub async fn staleness_against( recompute_all: false, dirty, row_dirty, + pending_fill, inherited, }) } +/// Read exact status evidence without the planner's conservative fallback. +/// +/// A missing metadata key returns [`StrictFreshness::Absent`]. A referenced +/// sidecar that cannot be read or decoded propagates the existing error. The +/// returned plan is certified when the sidecar records a definition and can be +/// decoded. Failure coverage is returned only for live fragments whose stored +/// input signature still matches; stale evidence is omitted. The status +/// provider remains responsible for classifying uncovered live rows as fresh, +/// stale, or never computed, and for reporting an error only when a row is +/// genuinely ambiguous. +pub async fn strict_freshness_against( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, +) -> Result { + let Some((stored, _)) = load_freshness_state(dataset, column).await? else { + return Ok(StrictFreshness::Absent); + }; + let Some(stored_definition) = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) else { + return Err(incomplete_certificate( + column, + "the recorded definition is missing", + )); + }; + let staleness = + staleness_from_state(dataset, column, definition_version, inputs, stored.clone()).await?; + if !stored.failure_evidence_recorded { + return Ok(StrictFreshness::Uncertified { staleness }); + } + if stored_definition != definition_version { + return Ok(StrictFreshness::Certified { + staleness, + failures: FailureEvidence::default(), + }); + } + let mut failures = FailureEvidence::default(); + for fragment in dataset.get_fragments() { + let fragment_id = fragment.id() as u32; + let current = signature_of(dataset, fragment_id, inputs)?.ok_or_else(|| { + incomplete_certificate(column, format!("fragment {fragment_id} is not live")) + })?; + if stored.signatures.get(&fragment_id) != Some(¤t) { + // The old generation's failure evidence no longer describes this + // fragment. Its live rows are stale or never computed, not + // ambiguously failed. + continue; + } + if let Some(covered) = stored.failure_coverage.get(&fragment_id) + && !covered.is_empty() + { + failures.known_rows.insert(fragment_id, covered.clone()); + } + if let Some(failed) = stored.failed_rows.get(&fragment_id) + && !failed.is_empty() + { + failures.failed_rows.insert(fragment_id, failed.clone()); + } + } + Ok(StrictFreshness::Certified { + staleness, + failures, + }) +} + /// What [`record_freshness`] wrote: the table version the stamp landed at, /// if it wrote one, and the entries recorded and dropped for having moved. #[derive(Debug, Default, PartialEq, Eq)] @@ -1226,6 +1550,55 @@ pub async fn record_freshness( definition_version: &str, inputs: &InputFields, computed: SignatureMap, +) -> Result { + record_freshness_impl( + latest, + pinned, + column, + definition_version, + inputs, + computed, + None, + ) + .await +} + +/// Record signatures and an explicit current-generation failure outcome in one +/// immutable sidecar transition. +/// +/// `failures.known_rows` must include only physical offsets whose final +/// outcome is known. `failures.failed_rows` is the failed subset. Rows omitted +/// from coverage remain unknown to failure classification; freshness, values, +/// and assignment evidence may still classify them. +pub async fn record_freshness_with_failures( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, + failures: &FailureEvidence, +) -> Result { + record_freshness_impl( + latest, + pinned, + column, + definition_version, + inputs, + computed, + Some(failures), + ) + .await +} + +async fn record_freshness_impl( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, + failures: Option<&FailureEvidence>, ) -> Result { let absent = matches!( stored_signatures(latest, column).await, @@ -1245,7 +1618,7 @@ pub async fn record_freshness( } } entries.extend(computed); - if entries.is_empty() && !absent { + if entries.is_empty() && !absent && failures.is_none_or(FailureEvidence::is_empty) { return Ok(FreshnessRecord::default()); } let fragments: Vec = entries.keys().copied().collect(); @@ -1255,7 +1628,19 @@ pub async fn record_freshness( .filter(|(fragment_id, signature)| current.get(fragment_id) == Some(signature)) .collect(); let recorded = verified.len(); - let version = write_signatures(latest, column, definition_version, verified).await?; + let verified_fragments: HashSet = verified.keys().copied().collect(); + let scoped_failures = failures + .map(|failures| failures.for_fragments(&verified_fragments)) + .filter(|failures| !failures.is_empty()); + let version = write_signatures_impl( + latest, + column, + definition_version, + Some(inputs), + verified, + scoped_failures.as_ref(), + ) + .await?; Ok(FreshnessRecord { version: Some(version), recorded, @@ -1263,18 +1648,323 @@ pub async fn record_freshness( }) } +/// The source of a just-committed write whose retained Function values may +/// still be fresh. The fields must describe the actual write, including its +/// join keys; they must not be inferred from a later table snapshot. +pub enum FunctionWrite<'a> { + /// Assignments executed by Lance's update builder. + Update { columns: &'a [String] }, + /// The source schema and join columns executed by Lance's merge builder. + Merge { + source_schema: &'a ArrowSchema, + on: &'a [String], + /// The insertion count from the same committed merge result. + num_inserted_rows: u64, + }, +} + +impl FunctionWrite<'_> { + fn writes_root(&self, root: &str) -> Result { + match self { + Self::Update { columns } => columns.iter().try_fold(false, |found, column| { + Ok(found || field_root(column)? == root) + }), + Self::Merge { source_schema, .. } => Ok(source_schema.field_with_name(root).is_ok()), + } + } + + fn preserves_input(&self, path: &str, schema: &ArrowSchema) -> Result { + let parts = lance_core::datatypes::parse_field_path(path)?; + let root = field_root(path)?; + if !self.writes_root(&root)? { + return Ok(true); + } + let Self::Merge { + source_schema, on, .. + } = self + else { + return Ok(false); + }; + if parts.len() != 1 || !on.contains(&root) { + return Ok(false); + } + let target = schema.field_with_name(&root)?; + let source = source_schema.field_with_name(&root)?; + // Join equality must preserve the Function's exact input. In particular, + // floating-point joins can equate different signed zeros or NaN payloads. + // Extension types can also define equality over a decoded representation. + Ok(source.data_type() == target.data_type() + && !source + .metadata() + .contains_key(lance_arrow::ARROW_EXT_NAME_KEY) + && !target + .metadata() + .contains_key(lance_arrow::ARROW_EXT_NAME_KEY) + && matches!( + target.data_type(), + DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Binary + | DataType::LargeBinary + | DataType::FixedSizeBinary(_) + )) + } +} + +/// Preserve Function freshness after an input-preserving update or merge. +/// +/// Call this on the exact dataset returned by the write, before any subsequent +/// operation. `write` must describe that write's real assignments or source. +/// The successful transaction's read version supplies the source freshness, +/// including when the write retried. Only fresh source fragments are carried; +/// partial repairs and unknown input equality remain stale. Inserted rows keep +/// NULL outputs and carry a pending-fill signature instead of a completed stamp. +/// +/// All siblings are stamped in one version-fenced metadata commit. Failure is +/// an optimization miss: callers must retain the successful data-write result, +/// rather than report a failed write that a client might repeat. +/// +/// ``` +/// use lance::Dataset; +/// use lancedb::table::freshness::{FunctionWrite, preserve_function_freshness}; +/// # async fn after_label_update(dataset: &mut Dataset) { +/// let columns = vec!["label".to_string()]; +/// if let Err(error) = preserve_function_freshness( +/// dataset, FunctionWrite::Update { columns: &columns }, +/// ).await { +/// log::warn!("freshness preservation skipped: {error}"); +/// } +/// # } +/// ``` +pub async fn preserve_function_freshness( + dataset: &mut Dataset, + write: FunctionWrite<'_>, +) -> Result<()> { + let schema = ArrowSchema::from(dataset.schema()); + let bindings = function_bindings(&schema)?; + if bindings.is_empty() { + return Ok(()); + } + let committed_version = dataset.version().version; + let Some(transaction) = dataset + .read_transaction_by_version(committed_version) + .await? + else { + return Ok(()); + }; + let Operation::Update { + removed_fragment_ids, + updated_fragments, + new_fragments, + update_mode: Some(UpdateMode::RewriteRows), + .. + } = &transaction.operation + else { + return Ok(()); + }; + if new_fragments.is_empty() { + return Ok(()); + } + let before = dataset.checkout_version(transaction.read_version).await?; + if before.schema().metadata.get(FUNCTION_BINDINGS_META_KEY) + != dataset.schema().metadata.get(FUNCTION_BINDINGS_META_KEY) + { + return Ok(()); + } + let before_schema = ArrowSchema::from(before.schema()); + let sources = removed_fragment_ids + .iter() + .copied() + .chain(updated_fragments.iter().map(|fragment| fragment.id)) + .collect::>(); + // Commit assigns fragment IDs. Match only this transaction's files, not + // unrelated appends that may have committed while it was being written. + let live_fragments = dataset.get_fragments(); + let produced = new_fragments + .iter() + .map(|fragment| { + live_fragments + .iter() + .find(|live| live.metadata().files == fragment.files) + .map(|live| live.id() as u32) + .ok_or_else(|| { + invalid("written Function fragment is missing from its commit".into()) + }) + }) + .collect::>>()?; + let live = live_fragments + .iter() + .map(|fragment| fragment.id() as u32) + .collect::>(); + let mut pending = Vec::new(); + for binding in bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let mut preserved = true; + for path in &paths { + preserved &= write.preserves_input(path, &before_schema)?; + } + // Even a join-key output can supply a non-NULL value to an insert. + // Those values were not computed under this binding. + for name in binding + .outputs() + .iter() + .map(|output| output.output_name.as_str()) + .chain( + binding + .assignment() + .map(|assignment| assignment.output_name.as_str()), + ) + { + preserved &= !write.writes_root(name)?; + } + if !preserved { + continue; + } + let old_inputs = fields_for_paths(before.schema(), &paths)?; + let new_inputs = fields_for_paths(dataset.schema(), &paths)?; + for output in binding.outputs() { + let column = &output.output_name; + let (Some(old_field), Some(new_field)) = ( + before.schema().field(column), + dataset.schema().field(column), + ) else { + continue; + }; + if old_field.metadata != new_field.metadata { + continue; + } + let StoredFreshnessState::Present { mut state, .. } = + stored_freshness_state(&before, column).await + else { + continue; + }; + let stale = + staleness_against(&before, column, binding.binding_id(), &old_inputs).await?; + if stale.recompute_all + || sources.iter().any(|id| { + before.get_fragment(*id as usize).is_none() || stale.needs_recompute(*id as u32) + }) + { + continue; + } + // Advancing recorded_at must also carry unrelated compactions + // already proven fresh at the write's source version. + for (id, signature) in stale.inherited { + if signature_of(dataset, id, &new_inputs)?.as_ref() == Some(&signature) { + state.signatures.insert(id, signature); + } + } + let needs_fill = matches!(write, FunctionWrite::Merge { num_inserted_rows, .. } if num_inserted_rows > 0) + || sources + .iter() + .any(|id| stale.pending_fill.contains_key(&(*id as u32))); + let mut pending_fill = stale.pending_fill; + let produced_signatures = signatures_for(dataset, &produced, &new_inputs)?; + if needs_fill { + pending_fill.extend(produced_signatures); + } else { + state.signatures.extend(produced_signatures); + } + pending_fill.retain(|id, _| live.contains(id)); + state.signatures.retain(|id, _| live.contains(id)); + state.row_state.retain(|id, _| live.contains(id)); + state.failure_coverage.retain(|id, _| live.contains(id)); + state.failed_rows.retain(|id, _| live.contains(id)); + state.basis.clear(); + let reference = write_sidecar(dataset, &state.normalize()?).await?; + let fill_reference = if pending_fill.is_empty() { + None + } else { + Some( + write_sidecar( + dataset, + &FreshnessState { + signatures: pending_fill, + ..Default::default() + }, + ) + .await?, + ) + }; + pending.push(( + column.clone(), + binding.binding_id().to_string(), + reference, + fill_reference, + )); + } + } + if pending.is_empty() { + return Ok(()); + } + let mut metadata = dataset.update_field_metadata(); + for (column, definition, reference, fill_reference) in pending { + metadata = metadata.update( + &column, + [ + (SOURCE_SIGNATURE_META_KEY.to_string(), Some(reference)), + (PENDING_FILL_SIGNATURE_META_KEY.to_string(), fill_reference), + (DEFINITION_VERSION_META_KEY.to_string(), Some(definition)), + ( + RECORDED_AT_VERSION_META_KEY.to_string(), + Some(committed_version.to_string()), + ), + ], + )?; + } + metadata + .with_expected_latest_version(committed_version) + .await?; + Ok(()) +} + /// Merge `entries` into the column's stored map and stamp the definition and /// the version the map now describes. Merges rather than replaces: the /// entries cover only the fragments this refresh wrote, and every fragment it /// skipped keeps the entry an earlier one left. Entries for fragments no /// longer in the manifest are dropped, so compaction cannot grow the map -/// without bound. Returns the version the stamp landed at. +/// without bound. When the definition changes, only the newly computed entries +/// are trusted. Returns the version the stamp landed at. pub async fn write_signatures( dataset: &mut Dataset, column: &str, definition_version: &str, entries: SignatureMap, ) -> Result { + write_signatures_impl(dataset, column, definition_version, None, entries, None).await +} + +async fn write_signatures_impl( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: Option<&InputFields>, + entries: SignatureMap, + failures: Option<&FailureEvidence>, +) -> Result { + if let Some(failures) = failures { + failures.validate()?; + if inputs.is_none() { + return Err(invalid( + "failure evidence requires input fields for signature validation".to_string(), + )); + } + } + let definition_changed = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) + .is_some_and(|version| version != definition_version); let live: HashSet = dataset .get_fragments() .iter() @@ -1291,6 +1981,9 @@ pub async fn write_signatures( FreshnessState::default() } }; + if definition_changed { + state = FreshnessState::default(); + } let recomputed: HashSet = entries.keys().copied().collect(); let signatures_changed = entries .iter() @@ -1307,17 +2000,40 @@ pub async fn write_signatures( } // A signature entry written through this API means the fragment was // recomputed in full. Whole callers keep their old semantics while - // clearing any partial retry state left by a previous publication. + // clearing any partial retry state left by a previous publication. The + // old failure outcome is also unknown unless the failure-aware wrapper + // supplies it below. for fragment_id in &recomputed { state.row_state.remove(fragment_id); } - state.signatures.extend(entries); + state.invalidate_failure_evidence(recomputed.iter().copied()); + state.signatures.extend( + entries + .iter() + .map(|(fragment_id, signature)| (*fragment_id, signature.clone())), + ); state .signatures .retain(|fragment_id, _| live.contains(fragment_id)); state .row_state .retain(|fragment_id, _| live.contains(fragment_id)); + state + .failure_coverage + .retain(|fragment_id, _| live.contains(fragment_id)); + state + .failed_rows + .retain(|fragment_id, _| live.contains(fragment_id)); + if let Some(failures) = failures { + apply_failure_evidence( + dataset, + inputs.expect("failure evidence requires input fields"), + &entries, + &mut state, + failures, + ) + .await?; + } if state.row_state.is_empty() || state_unreadable || signatures_changed { state.basis.clear(); } @@ -1333,6 +2049,70 @@ struct FreshnessWrite { intent_digest: Option, } +async fn apply_failure_evidence( + dataset: &Dataset, + inputs: &InputFields, + accepted: &SignatureMap, + state: &mut FreshnessState, + update: &FailureEvidence, +) -> Result<()> { + update.validate()?; + let physical_rows: BTreeMap = { + let mut rows = BTreeMap::new(); + for fragment in dataset.get_fragments() { + rows.insert(fragment.id() as u32, fragment.physical_rows().await? as u64); + } + rows + }; + let mut applied = HashSet::new(); + for (fragment_id, covered) in &update.known_rows { + let Some(rows) = physical_rows.get(fragment_id) else { + continue; + }; + let Some(current) = signature_of(dataset, *fragment_id, inputs)? else { + continue; + }; + // Evidence belongs to the attempt that produced this accepted + // signature. A concurrent attempt may have stamped a newer signature + // into `state`; that does not make this attempt's rows valid for it. + if accepted.get(fragment_id) != Some(¤t) { + continue; + } + if state.signatures.get(fragment_id) != Some(¤t) { + continue; + } + if covered + .max() + .is_some_and(|offset| u64::from(offset) >= *rows) + { + return Err(invalid(format!( + "failure evidence for fragment {fragment_id} exceeds its {rows} physical rows" + ))); + } + if let Some(failed) = state.failed_rows.get_mut(fragment_id) { + *failed -= covered; + } + let coverage = state.failure_coverage.entry(*fragment_id).or_default(); + *coverage |= covered; + applied.insert(*fragment_id); + } + for (fragment_id, failed) in &update.failed_rows { + if !applied.contains(fragment_id) { + continue; + } + if !update.known_rows.contains_key(fragment_id) { + return Err(invalid(format!( + "failed rows for fragment {fragment_id} have no coverage update" + ))); + } + let current = state.failed_rows.entry(*fragment_id).or_default(); + *current |= failed; + } + state.failed_rows.retain(|_, rows| !rows.is_empty()); + state.failure_coverage.retain(|_, rows| !rows.is_empty()); + Ok(()) +} + async fn write_freshness_state( dataset: &mut Dataset, column: &str, @@ -1344,6 +2124,8 @@ async fn write_freshness_state( let state = state.normalize()?; let inline_empty = state.signatures.is_empty() && state.row_state.is_empty() + && state.failure_coverage.is_empty() + && state.failed_rows.is_empty() && state.basis.is_empty() && !retain_empty_sidecar; // The sidecar is durable before the metadata commit references it. @@ -1359,7 +2141,7 @@ async fn write_freshness_state( (reference, Some(digest)) }; let describes = dataset.version().version; - let updates = vec![ + let mut updates = vec![ (SOURCE_SIGNATURE_META_KEY.to_string(), Some(signature_ref)), ( DEFINITION_VERSION_META_KEY.to_string(), @@ -1370,6 +2152,13 @@ async fn write_freshness_state( Some(describes.to_string()), ), ]; + // Pending-fill proofs vouch for retained outputs under the old definition. + // A partial publication must not make them valid under its new stamp. + if field_meta(dataset, column, DEFINITION_VERSION_META_KEY) + .is_some_and(|version| version != definition_version) + { + updates.push((PENDING_FILL_SIGNATURE_META_KEY.to_string(), None)); + } let builder = dataset.update_field_metadata().update(column, updates)?; match expected_latest_version { Some(expected) => builder.with_expected_latest_version(expected).await?, @@ -1498,6 +2287,8 @@ pub async fn begin_row_repair( freshness.signatures = signatures_for(dataset, &live.iter().copied().collect::>(), inputs)?; freshness.row_state.clear(); + freshness.failure_coverage.clear(); + freshness.failed_rows.clear(); freshness.basis.clear(); } if state_unreadable || definition_changed { @@ -1507,6 +2298,8 @@ pub async fn begin_row_repair( .iter() .map(|id| (*id, DirtyRows::AllExcept(RoaringBitmap::new()))) .collect(); + freshness.failure_coverage.clear(); + freshness.failed_rows.clear(); } for (fragment_id, repair) in repairs { @@ -1523,6 +2316,9 @@ pub async fn begin_row_repair( let preserve = !state_unreadable && !definition_changed && freshness.signatures.get(fragment_id) == Some(¤t); + if !preserve { + freshness.invalidate_failure_evidence([*fragment_id]); + } let dirty = if preserve { freshness .row_state @@ -1546,6 +2342,12 @@ pub async fn begin_row_repair( freshness .row_state .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .failure_coverage + .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .failed_rows + .retain(|fragment_id, _| live.contains(fragment_id)); freshness.basis = basis.clone(); freshness.intent_id = Uuid::new_v4(); @@ -1639,6 +2441,66 @@ pub async fn finish_row_repair( filled_rows: &BTreeMap, skipped_rows: &BTreeMap, verified_version: Option, +) -> Result { + finish_row_repair_impl( + dataset, + column, + definition_version, + inputs, + token, + filled_rows, + skipped_rows, + None, + verified_version, + ) + .await +} + +/// Finalize a row repair together with the exact failure evidence observed for +/// those rows. +/// +/// `failures.known_rows` must be a subset of the rows assigned either a +/// value or an explicit skipped outcome. This permits a deferral to become +/// known non-failed without turning it into a failure. `failed_rows` must be a +/// subset of `known_rows`. The same token, input-signature and version +/// fences as [`finish_row_repair`] apply. +#[allow(clippy::too_many_arguments)] +pub async fn finish_row_repair_with_failures( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + failures: &FailureEvidence, + verified_version: Option, +) -> Result { + finish_row_repair_impl( + dataset, + column, + definition_version, + inputs, + token, + filled_rows, + skipped_rows, + Some(failures), + verified_version, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn finish_row_repair_impl( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + failures: Option<&FailureEvidence>, + verified_version: Option, ) -> Result { if !is_sha256_hex(&token.intent_digest) { return Err(invalid("row repair token is malformed".to_string())); @@ -1652,6 +2514,36 @@ pub async fn finish_row_repair( "row repair result names a fragment outside its token".to_string(), )); } + if let Some(failures) = failures { + failures.validate()?; + for (fragment_id, covered) in &failures.known_rows { + let selected = token.selected_rows.get(fragment_id).ok_or_else(|| { + invalid(format!( + "failure evidence names fragment {fragment_id} outside its token" + )) + })?; + let mut known = filled_rows.get(fragment_id).cloned().unwrap_or_default(); + if let Some(skipped) = skipped_rows.get(fragment_id) { + known |= skipped; + } + if !covered.is_subset(selected) || !covered.is_subset(&known) { + return Err(invalid(format!( + "failure evidence for fragment {fragment_id} covers rows without a final outcome" + ))); + } + } + for (fragment_id, failed) in &failures.failed_rows { + if !failures.known_rows.contains_key(fragment_id) + || skipped_rows + .get(fragment_id) + .is_none_or(|skipped| !failed.is_subset(skipped)) + { + return Err(invalid(format!( + "failed rows for fragment {fragment_id} must be an explicit skipped subset" + ))); + } + } + } dataset.checkout_latest().await?; if verified_version.is_some_and(|version| dataset.version().version != version) { return Err(invalid( @@ -1696,14 +2588,32 @@ pub async fn finish_row_repair( ))); } } - let before = state.row_state.clone(); + let before = state.clone(); + state.invalidate_failure_rows(&token.selected_rows); apply_row_repair( &mut state.row_state, &token.selected_rows, filled_rows, skipped_rows, )?; - if state.row_state == before { + if let Some(failures) = failures { + let accepted = token + .selected_rows + .keys() + .map(|fragment_id| { + state + .signatures + .get(fragment_id) + .cloned() + .map(|signature| (*fragment_id, signature)) + }) + .collect::>() + .ok_or_else(|| { + invalid("row repair failure evidence lost an accepted signature".to_string()) + })?; + apply_failure_evidence(dataset, inputs, &accepted, &mut state, failures).await?; + } + if state == before { return Ok(dataset.version().version); } if current_digest != token.intent_digest.as_str() { @@ -1738,9 +2648,1101 @@ mod tests { use lance_file::version::ConcreteFileVersion; use lance_table::format::overlay::{DataOverlayFile, OverlayCoverage}; + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + const COLUMN: &str = "doubled"; const EXPRESSION: &str = "value * 2"; + async fn fresh_function_table() -> crate::Table { + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, [Some("x"), None, Some("z"), Some("w")]), + ("search_text", Utf8, ["a x", "b", "c z", "d w"]), + ("search_token_count", Int64, [2, 1, 2, 2]), + ("spare", Int32, [0, 0, 0, 0]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("fresh_functions", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let binding = text_features_binding(""); + stamp_bindings(&table, std::slice::from_ref(&binding)).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + native.dataset.update(dataset); + table + } + + async fn function_plan(dataset: &Dataset, column: &str) -> StalenessPlan { + staleness_against( + dataset, + column, + "fb_01K3TEXT", + &fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(), + ) + .await + .unwrap() + } + + #[rstest::rstest] + #[case::nullable_text("text")] + #[case::nested_text("nested")] + #[case::blob("blob")] + #[tokio::test] + async fn function_write_preserves_complex_omitted_inputs( + #[case] kind: &str, + #[values(false, true)] merge: bool, + ) { + use arrow_array::{ + ArrayRef, Int32Array, Int64Array, RecordBatch, StringArray, StructArray, + }; + + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + + let texts = Arc::new(StringArray::from(vec![ + Some("alpha"), + None, + Some(""), + Some("delta"), + ])); + let (body_field, body): (ArrowField, ArrayRef) = match kind { + "text" => (ArrowField::new("body", DataType::Utf8, true), texts), + "nested" => { + let fields = vec![ArrowField::new("text", DataType::Utf8, true)].into(); + let body = StructArray::new( + fields, + vec![texts], + Some(arrow_buffer::NullBuffer::from(vec![ + true, false, true, true, + ])), + ); + ( + ArrowField::new("body", body.data_type().clone(), true), + Arc::new(body), + ) + } + "blob" => { + let mut builder = lance::blob::BlobArrayBuilder::new(4); + builder.push_bytes(b"alpha").unwrap(); + builder.push_null().unwrap(); + builder.push_bytes(b"").unwrap(); + builder.push_bytes(b"delta").unwrap(); + ( + lance::blob::blob_field("body", true), + builder.finish().unwrap(), + ) + } + _ => unreachable!(), + }; + let batch = RecordBatch::try_new( + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("title", DataType::Utf8, false), + body_field.clone(), + ArrowField::new("search_text", DataType::Utf8, true), + ArrowField::new("search_token_count", DataType::Int64, true), + ArrowField::new("spare", DataType::Int32, false), + ])), + vec![ + Arc::new(StringArray::from(vec!["a", "b", "c", "d"])), + body, + Arc::new(StringArray::from(vec!["alpha", "null", "empty", "delta"])), + Arc::new(Int64Array::from(vec![5, 0, 0, 5])), + Arc::new(Int32Array::from(vec![0; 4])), + ], + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("complex_function_inputs", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + data_storage_version: Some(lance_file::version::LanceFileVersion::V2_2), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut raw = serde_json::to_value(text_features_binding("")).unwrap(); + let json_field = + lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![body_field])) + .unwrap() + .fields + .remove(0); + raw["input_schema"]["fields"][1] = serde_json::to_value(&json_field).unwrap(); + raw["inputs"][1]["arrow_type"] = serde_json::Value::String(match kind { + "text" => "utf8".into(), + "blob" => crate::function::FUNCTION_BLOB_V2_TYPE.into(), + _ => serde_json::to_string(&json_field.r#type).unwrap(), + }); + let binding = serde_json::from_value(raw).unwrap(); + stamp_bindings(&table, std::slice::from_ref(&binding)).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + native.dataset.update(dataset); + if merge { + let source = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("spare", Int32, [1, 1, 1, 1]) + ) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + } else { + table.update().column("spare", "1").execute().await.unwrap(); + } + let dataset = native.dataset.get().await.unwrap(); + for column in ["search_text", "search_token_count"] { + let plan = function_plan(&dataset, column).await; + assert!( + !plan.recompute_all && plan.dirty.is_empty() && plan.pending_fill.is_empty(), + "{plan:?}" + ); + } + let mut scan = dataset.scan(); + scan.with_row_address(); + scan.project(&["title", "search_text", "search_token_count", "body"]) + .unwrap(); + let mut actual = BTreeMap::new(); + for batch in scan + .try_into_stream() + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + { + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let text = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + let lengths = batch + .column(2) + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + assert!(!text.is_null(row) && !lengths.is_null(row)); + let body = batch.column_by_name("body").unwrap(); + let input = if kind == "blob" { + let addresses = batch + .column_by_name(ROW_ADDR) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + match dataset + .take_blobs_by_addresses(&[addresses.value(row)], "body") + .await + .unwrap() + .pop() + .unwrap() + { + Some(file) => Some(file.read().await.unwrap().to_vec()), + None => None, + } + } else { + let leaf = if kind == "nested" { + body.as_any() + .downcast_ref::() + .unwrap() + .column(0) + } else { + body + }; + let leaf = leaf.as_any().downcast_ref::().unwrap(); + (!body.is_null(row) && !leaf.is_null(row)) + .then(|| leaf.value(row).as_bytes().to_vec()) + }; + let expected_input = match titles.value(row) { + "a" => Some(b"alpha".to_vec()), + "b" => None, + "c" => Some(vec![]), + "d" => Some(b"delta".to_vec()), + _ => unreachable!(), + }; + assert_eq!(input, expected_input); + actual.insert( + titles.value(row).to_string(), + (text.value(row).to_string(), lengths.value(row)), + ); + } + } + assert_eq!( + actual, + BTreeMap::from([ + ("a".into(), ("alpha".into(), 5)), + ("b".into(), ("null".into(), 0)), + ("c".into(), ("empty".into(), 0)), + ("d".into(), ("delta".into(), 5)), + ]) + ); + } + + #[rstest::rstest] + #[case::label_update(false, 1, false)] + #[case::label_merge(true, 1, false)] + #[case::identical_merge(true, 0, false)] + #[case::mixed_update_insert(true, 1, true)] + #[tokio::test] + async fn function_write_preserves_unchanged_inputs( + #[case] merge: bool, + #[case] spare: i32, + #[case] insert: bool, + ) { + use crate::query::ExecutableQuery; + + let table = fresh_function_table().await; + let version = if merge { + let titles = if insert { + vec!["a", "c", "e"] + } else { + vec!["a", "c"] + }; + let batch = arrow_array::record_batch!( + ("title", Utf8, titles.clone()), + ("spare", Int32, vec![spare; titles.len()]) + ) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + if insert { + merge.when_not_matched_insert_all(); + } + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap() + .version + } else { + table + .update() + .only_if("title IN ('a', 'c')") + .column("spare", spare.to_string()) + .execute() + .await + .unwrap() + .version + }; + assert_eq!(version, table.version().await.unwrap()); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for column in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, column).await; + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + assert_eq!(stale.pending_fill.is_empty(), !insert, "{stale:?}"); + } + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut values = BTreeMap::new(); + for batch in batches { + let titles = batch + .column_by_name("title") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let outputs = batch + .column_by_name("search_text") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..batch.num_rows() { + values.insert( + titles.value(i).to_string(), + (!outputs.is_null(i)).then(|| outputs.value(i).to_string()), + ); + } + } + for (title, output) in [("a", "a x"), ("b", "b"), ("c", "c z"), ("d", "d w")] { + assert_eq!(values[title].as_deref(), Some(output)); + } + assert_eq!(values.len(), if insert { 5 } else { 4 }); + if insert { + assert_eq!(values["e"], None, "new rows still need Function evaluation"); + prune_sidecars(&dataset, true).await.unwrap(); + assert!( + !function_plan(&dataset, "search_text") + .await + .pending_fill + .is_empty() + ); + } + } + + #[tokio::test] + async fn function_write_prunes_outcomes_for_replaced_fragments() { + let table = fresh_function_table().await; + let mut dataset = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .as_ref() + .clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + let failures = FailureEvidence { + known_rows: BTreeMap::from([ + (0, RoaringBitmap::from_iter([0, 1])), + (1, RoaringBitmap::from_iter([0, 1])), + ]), + failed_rows: BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]), + }; + for column in ["search_text", "search_token_count"] { + record_freshness_with_failures( + &mut dataset, + None, + column, + "fb_01K3TEXT", + &inputs, + signatures.clone(), + &failures, + ) + .await + .unwrap(); + } + + // Replace all of fragment 0, insert one uncomputed row, and leave + // fragment 1 (including its retained failure evidence) untouched. + let source = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "e"]), + ("spare", Int32, [1, 1, 1]) + ) + .unwrap(); + let mut merge = + MergeInsertBuilder::try_new(Arc::new(dataset), vec!["title".into()]).unwrap(); + merge.when_matched(WhenMatched::UpdateAll); + merge.when_not_matched(WhenNotMatched::InsertAll); + let (merged, stats) = merge + .try_build() + .unwrap() + .execute_reader(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + let mut dataset = merged.as_ref().clone(); + assert!(!dataset.get_fragments().iter().any(|f| f.id() == 0)); + assert!(dataset.get_fragments().iter().any(|f| f.id() == 1)); + preserve_function_freshness( + &mut dataset, + FunctionWrite::Merge { + source_schema: &source.schema(), + on: &["title".into()], + num_inserted_rows: stats.num_inserted_rows, + }, + ) + .await + .unwrap(); + + let reopened = dataset + .checkout_version(dataset.version().version) + .await + .unwrap(); + for column in ["search_text", "search_token_count"] { + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&reopened, column, "fb_01K3TEXT", &inputs) + .await + .unwrap() + else { + panic!("the preserved sidecar should retain failure evidence"); + }; + assert_eq!( + failures.known_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([0, 1]))]) + ); + assert_eq!( + failures.failed_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]) + ); + assert_eq!(staleness.pending_fill.len(), 1); + } + } + + #[tokio::test] + async fn input_update_dirties_only_the_updated_rows_and_retains_outputs() { + let table = fresh_function_table().await; + let result = table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + assert_eq!(result.rows_updated, 1); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for output in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, output).await; + let mut dirty_rows = 0; + for fragment in dataset.get_fragments() { + if stale.needs_recompute(fragment.id() as u32) { + let batch = fragment + .scan() + .project(&["title"]) + .unwrap() + .try_into_batch() + .await + .unwrap(); + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}"); + dirty_rows += batch.num_rows(); + } + } + assert_eq!(dirty_rows, 1, "{stale:?}"); + } + assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1); + } + + #[tokio::test] + async fn input_update_keeps_an_independent_function_binding_fresh() { + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, ["x", "y", "z", "w"]), + ("search_text", Utf8, ["a x", "b y", "c z", "d w"]), + ("search_token_count", Int64, [2, 2, 2, 2]), + ("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]), + ("search_token_count_other", Int64, [2, 2, 2, 2]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("independent_functions", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut other = serde_json::to_value(text_features_binding("_other")).unwrap(); + other["inputs"][1]["field_path"] = serde_json::json!("title"); + other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone(); + let bindings = [ + text_features_binding(""), + serde_json::from_value(other).unwrap(), + ]; + stamp_bindings(&table, &bindings).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + for binding in &bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let inputs = fields_for_paths(dataset.schema(), &paths).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + } + native.dataset.update(dataset); + table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .needs_recompute(2) + ); + let other = &bindings[1]; + let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap(); + for output in other.outputs() { + let stale = + staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs) + .await + .unwrap(); + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + } + } + + #[tokio::test] + async fn input_merge_dirties_only_the_updated_rows_and_retains_outputs() { + let table = fresh_function_table().await; + let source = + arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + let result = merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + assert_eq!(result.num_updated_rows, 1); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for output in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, output).await; + let mut dirty_rows = 0; + for fragment in dataset.get_fragments() { + if stale.needs_recompute(fragment.id() as u32) { + let batch = fragment + .scan() + .project(&["title"]) + .unwrap() + .try_into_batch() + .await + .unwrap(); + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}"); + dirty_rows += batch.num_rows(); + } + } + assert_eq!(dirty_rows, 1, "{stale:?}"); + } + assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1); + } + + #[tokio::test] + async fn input_merge_keeps_an_independent_function_binding_fresh() { + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, ["x", "y", "z", "w"]), + ("search_text", Utf8, ["a x", "b y", "c z", "d w"]), + ("search_token_count", Int64, [2, 2, 2, 2]), + ("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]), + ("search_token_count_other", Int64, [2, 2, 2, 2]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("independent_merge", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut other = serde_json::to_value(text_features_binding("_other")).unwrap(); + other["inputs"][1]["field_path"] = serde_json::json!("title"); + other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone(); + let bindings = [ + text_features_binding(""), + serde_json::from_value(other).unwrap(), + ]; + stamp_bindings(&table, &bindings).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + for binding in &bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let inputs = fields_for_paths(dataset.schema(), &paths).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + } + native.dataset.update(dataset); + let source = + arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .needs_recompute(2) + ); + let other = &bindings[1]; + let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap(); + for output in other.outputs() { + let stale = + staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs) + .await + .unwrap(); + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + } + } + + #[rstest::rstest] + #[case::same_definition(false)] + #[case::changed_definition(true)] + #[tokio::test] + async fn partial_refresh_preserves_only_current_definition(#[case] changed: bool) { + let table = fresh_function_table().await; + let batch = + arrow_array::record_batch!(("title", Utf8, ["a", "e"]), ("spare", Int32, [1, 1])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge.when_not_matched_insert_all(); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap(); + let mut dataset = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .as_ref() + .clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let before = function_plan(&dataset, "search_text").await; + assert!(!before.pending_fill.is_empty()); + assert!(before.dirty.is_empty()); + // Refresh only the untouched fragment. Retained values elsewhere + // still belong to the old definition, even though their inputs match. + let definition = if changed { + "new-function-version" + } else { + "fb_01K3TEXT" + }; + let pinned = dataset.clone(); + let stale = staleness_against(&pinned, "search_text", definition, &inputs) + .await + .unwrap(); + let computed = signatures_for(&dataset, &[1], &inputs).unwrap(); + assert_eq!(computed.len(), 1); + record_freshness( + &mut dataset, + Some((&pinned, &stale)), + "search_text", + definition, + &inputs, + computed, + ) + .await + .unwrap(); + let after = staleness_against(&dataset, "search_text", definition, &inputs) + .await + .unwrap(); + assert!(!after.is_dirty(1), "{after:?}"); + if changed { + for fragment in dataset.get_fragments().iter().filter(|f| f.id() != 1) { + assert!(after.is_dirty(fragment.id() as u32), "{after:?}"); + } + assert!(after.pending_fill.is_empty(), "{after:?}"); + } else { + assert_eq!(after.pending_fill, before.pending_fill); + assert!(after.dirty.is_empty(), "{after:?}"); + } + } + + #[tokio::test] + async fn function_write_retains_pending_fill_across_another_update() { + let table = fresh_function_table().await; + let batch = + arrow_array::record_batch!(("title", Utf8, ["e"]), ("spare", Int32, [1])).unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_not_matched_insert_all(); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap(); + table + .update() + .only_if("title = 'e'") + .column("spare", "2") + .execute() + .await + .unwrap(); + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let stale = function_plan(&dataset, "search_text").await; + assert!(stale.dirty.is_empty(), "{stale:?}"); + assert_eq!( + stale.pending_fill.keys().copied().collect::>(), + vec![3] + ); + + write_signatures( + &mut dataset, + "search_text", + "fb_01K3TEXT", + stale.pending_fill, + ) + .await + .unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .pending_fill + .is_empty() + ); + // An older pending-fill reference must not override a later completed + // stamp or make a genuinely changed input fresh. + let changed = lance::dataset::UpdateBuilder::new(Arc::new(dataset)) + .update_where("title = 'e'") + .unwrap() + .set("body", "'changed'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + assert!( + function_plan(&changed.new_dataset, "search_text") + .await + .is_dirty(4) + ); + } + + #[rstest::rstest] + #[case::dirty_source("a", true)] + #[case::unrelated_dirty_fragment("c", false)] + #[tokio::test] + async fn function_write_preserves_pending_repairs( + #[case] title: &str, + #[case] dirty_product: bool, + ) { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signature = signatures_for(&dataset, &[0], &inputs).unwrap()[&0].clone(); + begin_row_repair( + &mut dataset, + "search_text", + "fb_01K3TEXT", + &inputs, + "pending-refresh", + &BTreeMap::from([( + 0, + RowRepair { + signature, + rows: RoaringBitmap::from_iter([0]), + }, + )]), + ) + .await + .unwrap(); + let prior = stored_row_states(&dataset, "search_text").await; + native.dataset.update(dataset); + table + .update() + .only_if(format!("title = '{title}'")) + .column("spare", "1") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + let stale = function_plan(&dataset, "search_text").await; + assert_eq!(stale.is_dirty(2), dirty_product, "{stale:?}"); + assert_eq!(stored_row_states(&dataset, "search_text").await, prior); + } + + #[rstest::rstest] + #[case::input("body", "'changed'")] + #[case::output("search_text", "'uncomputed'")] + #[tokio::test] + async fn function_write_does_not_certify_changed_values( + #[case] column: &str, + #[case] value: &str, + ) { + let table = fresh_function_table().await; + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let result = lance::dataset::UpdateBuilder::new(dataset) + .update_where("title = 'a'") + .unwrap() + .set(column, value) + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut after = result.new_dataset.as_ref().clone(); + let version = after.version().version; + preserve_function_freshness( + &mut after, + FunctionWrite::Update { + columns: &[column.into()], + }, + ) + .await + .unwrap(); + assert_eq!(after.version().version, version); + assert!(function_plan(&after, "search_text").await.is_dirty(2)); + } + + #[rstest::rstest] + #[case::input_same_rows("body", "a", true, 1)] + #[case::input_other_rows("body", "c", false, 1)] + #[case::input_no_rows("body", "missing", false, 0)] + #[case::output_same_rows("search_text", "a", true, 1)] + #[case::output_other_rows("search_text", "c", false, 1)] + #[case::output_no_rows("search_text", "missing", false, 0)] + #[tokio::test] + async fn function_write_preserves_prior_invalidation( + #[case] changed_column: &str, + #[case] title: &str, + #[case] dirty_product: bool, + #[case] expected_updated_rows: u64, + ) { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let result = lance::dataset::UpdateBuilder::new(native.dataset.get().await.unwrap()) + .update_where("title = 'a'") + .unwrap() + .set(changed_column, "'changed'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + assert!( + function_plan(&result.new_dataset, "search_text") + .await + .is_dirty(2) + ); + native.dataset.update(result.new_dataset.as_ref().clone()); + + let before_version = table.version().await.unwrap(); + let update = table + .update() + .only_if(format!("title = '{title}'")) + .column("spare", "1") + .execute() + .await + .unwrap(); + assert_eq!(update.rows_updated, expected_updated_rows); + let dataset = native.dataset.get().await.unwrap(); + if expected_updated_rows == 0 { + assert_eq!(update.version, before_version); + assert_eq!(dataset.version().version, before_version); + } + let stale = function_plan(&dataset, "search_text").await; + assert_eq!(stale.is_dirty(3), dirty_product, "{stale:?}"); + if !dirty_product { + assert!( + stale.is_dirty(2), + "the earlier invalidation was lost: {stale:?}" + ); + } + } + + #[tokio::test] + async fn function_write_keeps_a_changed_definition_stale() { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + dataset + .update_field_metadata() + .update( + "search_text", + [(DEFINITION_VERSION_META_KEY, Some("old-function-version"))], + ) + .unwrap() + .await + .unwrap(); + native.dataset.update(dataset); + table.update().column("spare", "1").execute().await.unwrap(); + assert!( + function_plan(native.dataset.get().await.unwrap().as_ref(), "search_text") + .await + .recompute_all + ); + } + + #[rstest::rstest] + #[case::delete(false)] + #[case::restore(true)] + #[tokio::test] + async fn function_write_cannot_stamp_over_a_concurrent_commit(#[case] restore: bool) { + let table = fresh_function_table().await; + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let before_version = dataset.version().version; + let result = lance::dataset::UpdateBuilder::new(dataset) + .update_where("title = 'a'") + .unwrap() + .set("spare", "1") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut staged = result.new_dataset.as_ref().clone(); + let mut concurrent = staged.clone(); + if restore { + concurrent = concurrent.checkout_version(before_version).await.unwrap(); + concurrent.restore().await.unwrap(); + } else { + concurrent.delete("title = 'd'").await.unwrap(); + } + let current_version = concurrent.version().version; + let before = field_meta(&concurrent, "search_text", SOURCE_SIGNATURE_META_KEY); + assert!( + preserve_function_freshness( + &mut staged, + FunctionWrite::Update { + columns: &["spare".into()] + } + ) + .await + .is_err() + ); + concurrent.checkout_latest().await.unwrap(); + assert_eq!(concurrent.version().version, current_version); + assert_eq!( + field_meta(&concurrent, "search_text", SOURCE_SIGNATURE_META_KEY), + before + ); + } + + #[tokio::test] + async fn function_write_retains_inherited_compaction_freshness() { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + compact(&mut dataset).await; + assert!( + !function_plan(&dataset, "search_text") + .await + .inherited + .is_empty() + ); + native.dataset.update(dataset); + table + .update() + .only_if("title = 'a'") + .column("spare", "1") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + let stale = function_plan(&dataset, "search_text").await; + assert!(stale.dirty.is_empty(), "{stale:?}"); + assert_eq!(dataset.get_fragments().len(), 2); + } + /// Two fragments of 50 rows, `id` and `value`, with `doubled` declared /// all-null against `value`, tracked from birth. async fn table(uri: &str) -> Dataset { @@ -1813,6 +3815,41 @@ mod tests { .unwrap(); } + async fn stamp_v2( + dataset: &mut Dataset, + column: &str, + definition: &str, + entries: SignatureMap, + ) { + let reference = write_sidecar_bytes( + dataset, + encode_v2_sidecar(&FreshnessState { + signatures: entries, + ..Default::default() + }) + .unwrap(), + ) + .await + .unwrap(); + let describes = dataset.version().version.to_string(); + dataset + .update_field_metadata() + .update( + column, + [ + (SOURCE_SIGNATURE_META_KEY.to_string(), reference), + ( + DEFINITION_VERSION_META_KEY.to_string(), + definition.to_string(), + ), + (RECORDED_AT_VERSION_META_KEY.to_string(), describes), + ], + ) + .unwrap() + .await + .unwrap(); + } + fn fragment_signature(dataset: &Dataset, fragment_id: u32) -> String { signature_of(dataset, fragment_id, &inputs(dataset)) .unwrap() @@ -1839,6 +3876,15 @@ mod tests { (3, DirtyRows::Rows(RoaringBitmap::from_iter([1, 4, 9]))), (7, DirtyRows::AllExcept(RoaringBitmap::from_iter([0, 2]))), ]), + failure_coverage: FailureRows::from([ + (3, RoaringBitmap::from_iter([1, 2, 4, 9])), + (7, RoaringBitmap::from_iter([0, 1, 2, 3])), + ]), + failed_rows: FailureRows::from([ + (3, RoaringBitmap::from_iter([1])), + (7, RoaringBitmap::from_iter([1, 3])), + ]), + failure_evidence_recorded: true, }; let encoded = encode_sidecar(&state).unwrap(); assert_eq!(encoded[4], SIDECAR_FORMAT); @@ -1858,9 +3904,283 @@ mod tests { let state = decode_sidecar(&encode_legacy_sidecar(&signatures).unwrap()).unwrap(); assert_eq!(state.signatures, signatures); assert!(state.row_state.is_empty()); + assert!(state.failure_coverage.is_empty()); + assert!(state.failed_rows.is_empty()); + assert!(!state.failure_evidence_recorded); assert!(state.basis.is_empty()); } + #[test] + fn v2_sidecar_decodes_with_unknown_failure_evidence() { + let state = FreshnessState { + signatures: SignatureMap::from([(1, "0000000000000001".to_string())]), + row_state: RowStateMap::from([(1, DirtyRows::Rows(RoaringBitmap::from_iter([2, 3])))]), + basis: "legacy-intent".to_string(), + intent_id: Uuid::from_u128(1), + ..Default::default() + }; + let decoded = decode_sidecar(&encode_v2_sidecar(&state).unwrap()).unwrap(); + assert_eq!(decoded, state); + assert!(decoded.failure_coverage.is_empty()); + assert!(decoded.failed_rows.is_empty()); + assert!(!decoded.failure_evidence_recorded); + } + + #[tokio::test] + async fn a_first_partial_write_keeps_untouched_legacy_rows_unknown() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let entries = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + stamp_v2(&mut dataset, COLUMN, &definition, entries).await; + + let StrictFreshness::Uncertified { staleness } = + strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("the v2 sidecar should yield a readable uncertified plan"); + }; + assert_eq!(staleness, StalenessPlan::default()); + + let selected = RoaringBitmap::from_iter([1, 2]); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, selected.clone()))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "legacy-partial", + &repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, selected)]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + None, + ) + .await + .unwrap(); + + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("partial v3 evidence is still readable"); + }; + assert_eq!( + staleness.row_dirty.get(&0), + Some(&DirtyRows::Rows(RoaringBitmap::from_iter([1]))) + ); + assert_eq!( + failures.known_rows.get(&0), + Some(&RoaringBitmap::from_iter([1, 2])), + "only the rows this partial publication observed are covered" + ); + assert_eq!( + failures.failed_rows.get(&0), + Some(&RoaringBitmap::from_iter([1])) + ); + assert!( + !failures.known_rows.contains_key(&1), + "the untouched legacy fragment remains unknown" + ); + } + + #[tokio::test] + async fn a_successful_retry_clears_only_its_failed_rows() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let signatures = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + stamp_v2(&mut dataset, COLUMN, &definition, signatures).await; + + let first_selected = RoaringBitmap::from_iter([1, 2]); + let first_repairs = BTreeMap::from([(0, repair(&dataset, 0, first_selected.clone()))]); + let first = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "failed-wave", + &first_repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &first, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, first_selected)]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + None, + ) + .await + .unwrap(); + + let retry_selected = RoaringBitmap::from_iter([1]); + let retry_repairs = BTreeMap::from([(0, repair(&dataset, 0, retry_selected.clone()))]); + let retry = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "successful-retry", + &retry_repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &retry, + &BTreeMap::from([(0, retry_selected.clone())]), + &BTreeMap::new(), + &FailureEvidence { + known_rows: BTreeMap::from([(0, retry_selected)]), + failed_rows: BTreeMap::new(), + }, + None, + ) + .await + .unwrap(); + + let StrictFreshness::Certified { failures, .. } = + strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("status should remain readable"); + }; + assert!(!failures.failed_rows.contains_key(&0)); + assert_eq!( + failures.known_rows.get(&0), + Some(&RoaringBitmap::from_iter([1, 2])) + ); + } + + #[tokio::test] + async fn an_old_attempt_cannot_rewrite_a_newer_signature_evidence() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let old = dataset.clone(); + let old_inputs = ids.clone(); + let old_signature = signature_of(&old, 0, &old_inputs).unwrap().unwrap(); + + rewrite_value(&mut dataset, 0).await; + let new_signature = signature_of(&dataset, 0, &inputs(&dataset)) + .unwrap() + .unwrap(); + assert_ne!(old_signature, new_signature); + + let current_entries = signatures_for(&dataset, &[0, 1], &inputs(&dataset)).unwrap(); + write_signatures(&mut dataset, COLUMN, &definition, current_entries.clone()) + .await + .unwrap(); + let StoredFreshnessState::Present { + state: mut current_state, + .. + } = stored_freshness_state(&dataset, COLUMN).await + else { + panic!("new attempt state"); + }; + current_state + .failure_coverage + .insert(0, RoaringBitmap::from_iter([3, 4])); + current_state + .failed_rows + .insert(0, RoaringBitmap::from_iter([4])); + let write = write_freshness_state( + &mut dataset, + COLUMN, + &definition, + current_state.clone(), + false, + None, + ) + .await + .unwrap(); + assert!(write.version > 0); + let new_evidence = FailureEvidence { + known_rows: current_state.failure_coverage.clone(), + failed_rows: current_state.failed_rows.clone(), + }; + + let record = record_freshness_with_failures( + &mut dataset, + None, + COLUMN, + &definition, + &old_inputs, + SignatureMap::from([(0, old_signature)]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1, 2]))]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + ) + .await + .unwrap(); + assert_eq!((record.recorded, record.moved), (0, 1)); + + let StrictFreshness::Certified { failures, .. } = + strict_freshness_against(&dataset, COLUMN, &definition, &inputs(&dataset)) + .await + .unwrap() + else { + panic!("current signature evidence should remain readable"); + }; + assert_eq!(failures.known_rows, new_evidence.known_rows); + assert_eq!(failures.failed_rows, new_evidence.failed_rows); + assert_eq!( + failures.failed_rows.get(&0), + Some(&RoaringBitmap::from_iter([4])), + "old S1 failure must not replace the S2 failure" + ); + assert!(!failures.known_rows.contains_key(&1)); + } + + #[test] + fn failure_evidence_must_be_a_subset_of_coverage() { + let state = FreshnessState { + signatures: SignatureMap::from([(3, "0000000000000003".to_string())]), + failure_coverage: FailureRows::from([(3, RoaringBitmap::from_iter([1]))]), + failed_rows: FailureRows::from([(3, RoaringBitmap::from_iter([2]))]), + ..Default::default() + }; + let error = encode_sidecar(&state).unwrap_err(); + assert!( + error + .to_string() + .contains("failed rows are not covered by failure evidence"), + "{error}" + ); + } + #[tokio::test] async fn a_row_repair_clears_filled_rows_and_retains_skipped_rows() { let dir = tempfile::tempdir().unwrap(); diff --git a/rust/lancedb/src/table/function_column_status.rs b/rust/lancedb/src/table/function_column_status.rs new file mode 100644 index 000000000..15703f4e9 --- /dev/null +++ b/rust/lancedb/src/table/function_column_status.rs @@ -0,0 +1,339 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Read-only status for Function-backed table columns. + +use serde::{Deserialize, Serialize}; + +use crate::error::JobFailure; +use crate::function::FunctionVersionRef; +use crate::{Error, Result}; + +/// Stable HTTP error code for a status read waiting on its matching finalize. +pub const FINALIZATION_PENDING_ERROR_CODE: &str = "function_column_status_finalization_pending"; + +/// One exact immutable Function revision attached to a table output. +pub type FunctionColumnVersionStatus = FunctionVersionRef; + +/// Latest matching refresh Job projected for a Function output. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub automatic: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed_at_millis: Option, + /// Why this Job failed, when the server retained a structured failure. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure: Option, +} + +/// Automatic-refresh scheduling state that the server can prove. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionColumnAutoRefreshState { + Disabled, + Running, + Queued, + UpToDate, + Ready, + WaitingInterval, + WaitingBackoff, + Blocked, + Unobservable, +} + +impl FunctionColumnAutoRefreshState { + pub const fn as_str(self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Running => "running", + Self::Queued => "queued", + Self::UpToDate => "up_to_date", + Self::Ready => "ready", + Self::WaitingInterval => "waiting_interval", + Self::WaitingBackoff => "waiting_backoff", + Self::Blocked => "blocked", + Self::Unobservable => "unobservable", + } + } +} + +/// Why an enabled automatic refresh is not currently schedulable. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionColumnAutoRefreshBlockedReason { + TableHasMemWal, + InputsNotSettled, + DependencyInFlight, + TableCapacity, + Cancelled, + PreparationBackoff, + FailureThresholdReached, + BindingRevisionMissing, +} + +impl FunctionColumnAutoRefreshBlockedReason { + pub const fn as_str(self) -> &'static str { + match self { + Self::TableHasMemWal => "table_has_mem_wal", + Self::InputsNotSettled => "inputs_not_settled", + Self::DependencyInFlight => "dependency_in_flight", + Self::TableCapacity => "table_capacity", + Self::Cancelled => "cancelled", + Self::PreparationBackoff => "preparation_backoff", + Self::FailureThresholdReached => "failure_threshold_reached", + Self::BindingRevisionMissing => "binding_revision_missing", + } + } +} + +/// Automatic-refresh projection for a Function output. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub interval_seconds: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub active_job_id: Option, + pub state: FunctionColumnAutoRefreshState, + pub failure_streak: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effective_cooldown_millis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub blocked_reason: Option, + /// Null is intentional until the Lance Agent exposes its scheduler decision. + pub next_run_at_millis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_run_at_reason: Option, +} + +/// Exact status of one Function output at one table version. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: u64, + pub rows: u64, + pub fresh: u64, + pub stale: u64, + pub never_computed: u64, + pub failed: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_refresh_job: Option, + /// Newest failed refresh Job. Unlike `last_refresh_job`, this remains + /// visible when the latest attempt was cancelled. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_failure_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +impl FunctionColumnStatus { + /// Whether this status is safe to expose as an exact four-way count. + pub fn validate(&self) -> Result<()> { + let classified = self + .fresh + .checked_add(self.stale) + .and_then(|count| count.checked_add(self.never_computed)) + .and_then(|count| count.checked_add(self.failed)); + if classified != Some(self.rows) { + return Err(Error::Runtime { + message: format!( + "Function column '{}' status counts do not partition {} rows", + self.column, self.rows + ), + }); + } + if self.auto_refresh.state == FunctionColumnAutoRefreshState::Blocked + && self.auto_refresh.blocked_reason.is_none() + { + return Err(Error::Runtime { + message: format!( + "Function column '{}' reported a blocked scheduler state without a reason", + self.column + ), + }); + } + if self.auto_refresh.state == FunctionColumnAutoRefreshState::Unobservable + && self.auto_refresh.next_run_at_millis.is_none() + && self + .auto_refresh + .next_run_at_reason + .as_deref() + .is_none_or(str::is_empty) + { + return Err(Error::Runtime { + message: format!( + "Function column '{}' omitted a reason for an unavailable next run", + self.column + ), + }); + } + Ok(()) + } +} + +/// Validate one GET response, whose objects must all describe one snapshot. +pub fn validate_statuses(statuses: &[FunctionColumnStatus]) -> Result<()> { + let mut table_versions = statuses.iter().map(|status| status.table_version); + let Some(first) = table_versions.next() else { + return Ok(()); + }; + if table_versions.any(|version| version != first) { + return Err(Error::Runtime { + message: "Function column statuses came from different table versions".to_string(), + }); + } + statuses.iter().try_for_each(FunctionColumnStatus::validate) +} + +/// Whether an error is the typed transient response used while the data +/// version's matching freshness finalization is still in progress. +pub fn is_finalization_pending(error: &Error) -> bool { + #[cfg(feature = "remote")] + { + error.status_code() == Some(reqwest::StatusCode::SERVICE_UNAVAILABLE) + && error + .remote_error_metadata() + .and_then(|metadata| metadata.error_code.as_deref()) + == Some(FINALIZATION_PENDING_ERROR_CODE) + } + #[cfg(not(feature = "remote"))] + { + let _ = error; + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn status(column: &str, table_version: u64) -> FunctionColumnStatus { + FunctionColumnStatus { + column: column.to_string(), + binding_id: "fb_01".to_string(), + function: FunctionVersionRef { + name: "embed".to_string(), + namespace_path: Vec::new(), + object_id: "embed".to_string(), + location: "objects/embed".to_string(), + version: "7".to_string(), + manifest_digest: "sha256:abc".to_string(), + }, + table_version, + rows: 10, + fresh: 6, + stale: 2, + never_computed: 1, + failed: 1, + last_refresh_job: None, + last_failure_job: None, + auto_refresh: FunctionColumnAutoRefreshStatus { + enabled: true, + interval_seconds: Some(60), + active_job_id: None, + state: FunctionColumnAutoRefreshState::Unobservable, + failure_streak: 0, + effective_cooldown_millis: None, + blocked_reason: None, + next_run_at_millis: None, + next_run_at_reason: Some( + "authoritative_scheduler_projection_unavailable".to_string(), + ), + }, + } + } + + #[test] + fn validates_a_single_version_and_four_way_partition() { + validate_statuses(&[status("a", 42), status("b", 42)]).unwrap(); + + let error = validate_statuses(&[status("a", 42), status("b", 43)]).unwrap_err(); + assert!(error.to_string().contains("different table versions")); + + let mut invalid = status("a", 42); + invalid.fresh += 1; + let error = validate_statuses(&[invalid]).unwrap_err(); + assert!(error.to_string().contains("do not partition 10 rows")); + } + + #[test] + fn wire_keeps_job_and_auto_refresh_metadata() { + let mut value = status("a", 42); + value.last_refresh_job = Some(FunctionColumnLastRefreshJob { + job_id: "job-7".to_string(), + state: "finished".to_string(), + automatic: Some(true), + completed_at_millis: Some(1_790_000_000_000), + failure: None, + }); + let encoded = serde_json::to_value(value).unwrap(); + assert_eq!(encoded["last_refresh_job"]["job_id"], "job-7"); + assert_eq!(encoded["auto_refresh"]["enabled"], true); + assert_eq!( + encoded["auto_refresh"]["next_run_at_reason"], + "authoritative_scheduler_projection_unavailable" + ); + } + + #[test] + fn scheduler_wire_names_are_stable() { + for (state, expected) in [ + (FunctionColumnAutoRefreshState::Queued, "queued"), + (FunctionColumnAutoRefreshState::UpToDate, "up_to_date"), + ] { + assert_eq!( + serde_json::to_string(&state).unwrap(), + format!("\"{expected}\"") + ); + } + for (reason, expected) in [ + ( + FunctionColumnAutoRefreshBlockedReason::FailureThresholdReached, + "failure_threshold_reached", + ), + ( + FunctionColumnAutoRefreshBlockedReason::BindingRevisionMissing, + "binding_revision_missing", + ), + ] { + assert_eq!( + serde_json::to_string(&reason).unwrap(), + format!("\"{expected}\"") + ); + } + } + + #[test] + fn blocked_auto_refresh_wire_keeps_its_reason() { + let mut value = status("a", 42); + value.auto_refresh.state = FunctionColumnAutoRefreshState::Blocked; + value.auto_refresh.failure_streak = 3; + value.auto_refresh.effective_cooldown_millis = Some(8000); + value.auto_refresh.blocked_reason = + Some(FunctionColumnAutoRefreshBlockedReason::PreparationBackoff); + value.auto_refresh.next_run_at_reason = None; + + let encoded = serde_json::to_value(&value).unwrap(); + assert_eq!(encoded["auto_refresh"]["state"], "blocked"); + assert_eq!( + encoded["auto_refresh"]["blocked_reason"], + "preparation_backoff" + ); + assert_eq!(encoded["auto_refresh"]["failure_streak"], 3); + assert_eq!(encoded["auto_refresh"]["effective_cooldown_millis"], 8000); + value.validate().unwrap(); + + value.auto_refresh.blocked_reason = None; + assert!( + value + .validate() + .unwrap_err() + .to_string() + .contains("blocked scheduler state without a reason") + ); + } +} diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 1f0b80829..79c724f3e 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -75,6 +75,7 @@ pub struct MergeInsertBuilder { pub(crate) when_not_matched_by_source_delete: bool, pub(crate) when_not_matched_by_source_delete_filt: Option, pub(crate) timeout: Option, + pub(crate) retries: Option, pub(crate) use_index: bool, pub(crate) use_rte: Option, pub(crate) validate_single_shard: bool, @@ -91,12 +92,21 @@ impl MergeInsertBuilder { when_not_matched_by_source_delete: false, when_not_matched_by_source_delete_filt: None, timeout: None, + retries: None, use_index: true, use_rte: None, validate_single_shard: true, } } + /// Override the remote transport retry budget for this operation. `0` + /// disables retries. Ambiguous write results are never replayed. This is + /// independent of local transaction conflict retries. + pub fn retries(&mut self, retries: u8) -> &mut Self { + self.retries = Some(retries); + self + } + /// Rows that exist in both the source table (new data) and /// the target table (old data) will be updated, replacing /// the old row with the corresponding matching row. @@ -239,11 +249,13 @@ impl MergeInsertBuilder { Ok(()) } - /// The existing columns a matched row takes from `source`: every source - /// column but the join keys, which a match leaves equal. An insert-only - /// merge rewrites none; its new rows get Function outputs from the next - /// refresh, as appended rows do. - pub(crate) fn function_guarded_columns(&self, source: &Fields) -> Vec { + /// The source columns a matched row writes: every column but the join + /// keys, which a match leaves equal. Function inputs stay writable; the + /// merge records their changed signatures so the next refresh recomputes + /// the affected rows. Computed outputs and assignment columns remain + /// protected by the direct-write guard. An insert-only merge writes none; + /// its new rows get Function outputs from the next refresh. + pub(crate) fn matched_source_columns(&self, source: &Fields) -> Vec { if !self.when_matched_update_all { return Vec::new(); } @@ -341,10 +353,10 @@ pub(crate) async fn execute_merge_insert( ) -> Result { params.canonicalize_filters()?; let schema = table.schema().await?; - super::computed_columns::ensure_not_function_bound( + let matched_columns = params.matched_source_columns(new_data.schema().fields()); + super::computed_columns::ensure_not_written( schema.as_ref(), - "merge_insert", - params.function_guarded_columns(new_data.schema().fields()), + matched_columns.iter().map(String::as_str), )?; // Normalize blob layouts and JSON extension metadata just as on append. // Keep arrow.json text labelled until Lance encodes it as JSONB. @@ -385,6 +397,8 @@ pub(crate) async fn execute_merge_insert( } let dataset = table.dataset.get().await?; + let source_schema = source.schema(); + let on = params.on.clone(); let mut builder = LanceMergeInsertBuilder::try_new(dataset.clone(), params.on)?; match ( params.when_matched_update_all, @@ -432,8 +446,21 @@ pub(crate) async fn execute_merge_insert( Either::Right(job.execute(source).map_err(|e| e.into())) }; let (new_dataset, stats) = future.await?; + let mut new_dataset = new_dataset.as_ref().clone(); + if let Err(error) = super::freshness::preserve_function_freshness( + &mut new_dataset, + super::freshness::FunctionWrite::Merge { + source_schema: &source_schema, + on: &on, + num_inserted_rows: stats.num_inserted_rows, + }, + ) + .await + { + log::warn!("merge committed but Function freshness could not be preserved: {error}"); + } let version = new_dataset.manifest().version; - table.dataset.update(new_dataset.as_ref().clone()); + table.dataset.update(new_dataset); Ok(MergeResult { version, num_updated_rows: stats.num_updated_rows, @@ -945,10 +972,11 @@ mod tests { assert_eq!(table.count_rows(None).await.unwrap(), 2); } - /// A matched row takes every non-key source column, so the merge is - /// refused only when one of those is a binding's input or output. + /// A matched row takes every non-key source column. Function inputs are + /// writable and become stale for the next refresh; computed outputs stay + /// protected, and a mixed input/output source is rejected before commit. #[tokio::test] - async fn merge_update_on_a_function_table_refuses_only_bound_columns() { + async fn merge_update_allows_function_inputs_but_protects_outputs() { let table = crate::table::computed_columns::test_support::bound_table_from( arrow_array::record_batch!( ("id", Int32, [1]), @@ -973,18 +1001,47 @@ mod tests { let mut merge = table.merge_insert(&["id"]); merge.when_matched_update_all(None); - let err = merge + let result = merge .execute(reader( arrow_array::record_batch!(("id", Int32, [1]), ("title", Utf8, ["z"])).unwrap(), )) .await - .unwrap_err(); - assert!( - matches!(&err, crate::Error::InvalidInput { message } - if message.contains("merge_insert of 'title'") - && message.contains("a Function binding reads or writes it")), - "{err:?}" + .unwrap(); + assert_eq!(result.num_updated_rows, 1); + assert_eq!( + table + .count_rows(Some("title = 'z' AND search_text = 'a b'".into())) + .await + .unwrap(), + 1 ); + + let version = table.version().await.unwrap(); + for source in [ + arrow_array::record_batch!(("id", Int32, [1]), ("search_text", Utf8, ["uncomputed"])) + .unwrap(), + arrow_array::record_batch!( + ("id", Int32, [1]), + ("title", Utf8, ["must not commit"]), + ("search_text", Utf8, ["uncomputed"]) + ) + .unwrap(), + ] { + let mut merge = table.merge_insert(&["id"]); + merge.when_matched_update_all(None); + let err = merge.execute(reader(source)).await.unwrap_err(); + assert!( + matches!(&err, crate::Error::InvalidInput { message } + if message.contains("is computed") + && message.contains("cannot be written directly")), + "{err:?}" + ); + assert_eq!(table.version().await.unwrap(), version); + assert_eq!( + table.count_rows(Some("title = 'z'".into())).await.unwrap(), + 1 + ); + } } } diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 446234a6e..0888ca4c4 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -32,6 +32,35 @@ pub use lance::dataset::optimize::{CompactionMode, CompactionOptions, IndexRemap const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64; +/// Actual outcome of one remote compaction job, returned by its job handle. +/// +/// A successful bounded run can leave more work for another invocation. A +/// partial commit reports uncommitted rows rather than inventing file counts. +/// File/fragment counts are unknown (`None`) when an older worker omitted them. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct CompactionResult { + /// A complete bounded plan left eligible work for a later invocation. + #[serde(default)] + pub more_work: bool, + /// Some planned groups were not committed. + pub partial_commit: bool, + /// Live source rows in committed rewrite groups. + pub rows_succeeded: u64, + /// Planned live rows not committed by this job. + pub rows_failed: u64, + /// Percentage of planned live rows committed, from 0 to 100. + pub completion_percentage: f64, + /// Files added by committed rewrites, including deletion files, when reported. + pub files_added: Option, + /// Files removed by committed rewrites, including deletion files, when reported. + pub files_removed: Option, + /// Fragments added by committed rewrites, when reported by the server. + pub fragments_added: Option, + /// Fragments removed by committed rewrites, when reported by the server. + pub fragments_removed: Option, +} + struct PrecomputedCompactionPlanner { plan: Mutex>, } @@ -184,6 +213,53 @@ async fn validate_sq_index_remapping( Ok(plan) } +/// Optional compaction tuning. Remote tables inherit omitted values from table +/// policy, then deployment/built-in defaults. Explicit values, including a zero +/// I/O budget, take precedence. Local tables use Lance defaults for omissions. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CompactionOverrides { + pub target_rows_per_fragment: Option, + pub max_source_rows: Option, + /// Read-ahead budget in bytes; zero disables byte-based I/O backpressure. + pub io_buffer_size: Option, + pub batch_size: Option, +} + +impl CompactionOverrides { + pub(crate) fn into_options(self) -> CompactionOptions { + let mut options = CompactionOptions::default(); + if let Some(target) = self.target_rows_per_fragment { + options.target_rows_per_fragment = target; + } + options.max_source_rows = self.max_source_rows; + options.io_buffer_size = self.io_buffer_size; + options.batch_size = self.batch_size; + options + } +} + +impl TryFrom for CompactionOverrides { + type Error = Error; + + fn try_from(options: CompactionOptions) -> Result { + let mut remaining = options.clone(); + let defaults = CompactionOptions::default(); + remaining.target_rows_per_fragment = defaults.target_rows_per_fragment; + remaining.max_source_rows = defaults.max_source_rows; + remaining.io_buffer_size = defaults.io_buffer_size; + remaining.batch_size = defaults.batch_size; + if remaining != defaults { + return Err(Error::NotSupported { message: "remote CompactionOptions support only target_rows_per_fragment, max_source_rows, io_buffer_size, and batch_size; other options must retain their defaults".into() }); + } + Ok(Self { + target_rows_per_fragment: Some(options.target_rows_per_fragment), + max_source_rows: options.max_source_rows, + io_buffer_size: options.io_buffer_size, + batch_size: options.batch_size, + }) + } +} + /// Optimize the dataset. /// /// Similar to `VACUUM` in PostgreSQL, it offers different options to @@ -209,9 +285,27 @@ pub enum OptimizeAction { /// /// # LanceDB Enterprise (remote tables) /// - /// A remote table only supports `Compact` with default `options` and no - /// custom `remap_options`; both are rejected with - /// [`crate::Error::NotSupported`] otherwise. It submits a durable + /// A remote table supports per-job `target_rows_per_fragment`, + /// `max_source_rows`, `io_buffer_size`, and `batch_size`. Other non-default + /// options and custom `remap_options` return [`crate::Error::NotSupported`] + /// before submission. The server must support these SQL options; errors + /// from older servers are returned without dropping the settings. + /// The source-row budget admits whole tasks. On current Enterprise servers, + /// worker planning fails if the budget cannot admit the first useful task, + /// reporting its required live rows and source fragment count. Older servers + /// may instead finish without rewriting data in this case. + /// Zero I/O buffer size disables byte-based I/O + /// backpressure. Use a positive size to limit I/O read-ahead; this is not a + /// total-memory limit. Row targets, source-row budgets, and batch sizes must + /// be positive. + /// The legacy Lance options type cannot distinguish an omitted fragment target + /// from its default value; that default is treated as unspecified remotely. + /// Use [`crate::Table::compact`] with [`CompactionOverrides`] to explicitly + /// override a table target with the Lance default value. + /// Omitted options inherit table tuning, then deployment/built-in defaults; options + /// affect only this job, without changing ongoing table policy. + /// + /// It submits a durable /// compaction job to the server over SQL and waits for that submission to /// be confirmed, not for compaction itself to finish: the job then runs /// asynchronously on the server, so this call can return well before the @@ -219,10 +313,28 @@ pub enum OptimizeAction { /// [`OptimizeStats::compaction`] is a zeroed [`CompactionMetrics`] /// placeholder rather than the real counts a local table reports. /// - /// A branch-scoped table handle compacts that branch. The branch is not - /// validated to exist before the job is submitted, so a nonexistent - /// branch fails the compaction job asynchronously rather than failing - /// this call. + /// ``` + /// use lancedb::{Table, table::{CompactionOptions, OptimizeAction}}; + /// # async fn compact(table: &Table) -> lancedb::Result<()> { + /// table.optimize(OptimizeAction::Compact { + /// options: CompactionOptions { + /// target_rows_per_fragment: 100_000, + /// max_source_rows: Some(1_000_000), + /// io_buffer_size: Some(64 * 1024 * 1024), + /// batch_size: Some(1024), + /// ..Default::default() + /// }, + /// remap_options: None, + /// }).await?; + /// # Ok(()) + /// # } + /// ``` + /// + /// A branch-scoped table handle compacts that branch. Current Enterprise + /// servers validate the table and branch through the service catalog before + /// creating the compaction job, so a nonexistent branch fails submission. + /// Older servers may accept submission and fail the compaction job + /// asynchronously instead. Compact { options: CompactionOptions, remap_options: Option>, @@ -447,11 +559,16 @@ pub(crate) async fn execute_optimize( #[cfg(test)] mod tests { use super::{oversized_sq_partition, segment_touches_fragments, sq_vector_dimension}; + use arrow::compute::concat_batches; use arrow_array::{ Array, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray, + cast::AsArray, + types::{Float32Type, Int32Type}, }; use arrow_schema::{DataType, Field, Schema}; + use lance::index::DatasetIndexExt; use lance_arrow::FixedSizeListArrayExt; + use lance_index::frag_reuse::FRAG_REUSE_INDEX_NAME; use rstest::rstest; use std::{collections::HashSet, sync::Arc}; @@ -462,7 +579,7 @@ mod tests { scalar::BTreeIndexBuilder, vector::{IvfHnswSqIndexBuilder, IvfRqIndexBuilder}, }; - use crate::query::ExecutableQuery; + use crate::query::{ExecutableQuery, QueryBase}; use crate::table::{CompactionOptions, OptimizeAction, OptimizeStats}; use futures::TryStreamExt; @@ -1340,6 +1457,138 @@ mod tests { assert_eq!(all_values, expected); } + #[tokio::test] + async fn test_refined_rq_query_after_deferred_compaction() { + const ROWS: i32 = 128; + const DIMENSION: i32 = 32; + let conn = connect("memory://").execute().await.unwrap(); + let vectors = FixedSizeListArray::try_new_from_values( + Float32Array::from_iter_values((0..ROWS).flat_map(|id| { + (0..DIMENSION).map(move |offset| (id as f32 * 0.1 + offset as f32 * 0.3).sin()) + })), + DIMENSION, + ) + .unwrap(); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vectors.data_type().clone(), false), + ])), + vec![ + Arc::new(Int32Array::from_iter_values(0..ROWS)), + Arc::new(vectors), + ], + ) + .unwrap(); + let table = conn + .create_table("refined_rq_compaction", batch.slice(0, 64)) + .storage_option(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, "false") + .execute() + .await + .unwrap(); + table.add(batch.slice(64, 64)).execute().await.unwrap(); + table + .create_index( + &["vector"], + Index::IvfRq( + IvfRqIndexBuilder::default() + .num_partitions(4) + .num_bits(7) + .max_iterations(5), + ), + ) + .name("rq".to_string()) + .execute() + .await + .unwrap(); + table.delete("id % 7 = 0").await.unwrap(); + let dataset = table.dataset().unwrap().get().await.unwrap(); + assert_eq!(dataset.fragments().len(), 2); + let original_index = dataset.load_indices_by_name("rq").await.unwrap()[0].uuid; + + let key = (0..DIMENSION) + .map(|offset| (0.5 + offset as f32 * 0.3).sin()) + .collect::>(); + let query = || { + table + .query() + .only_if("id % 3 != 0") + .nearest_to(key.as_slice()) + .unwrap() + .nprobes(4) + .unwrap() + .limit(8) + }; + let before = query() + .fast_search() + .refine_factor(4) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let before = concat_batches(&before[0].schema(), &before).unwrap(); + + let stats = table + .optimize(OptimizeAction::Compact { + options: CompactionOptions { + target_rows_per_fragment: 256, + defer_index_remap: true, + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap(); + assert_eq!(stats.compaction.unwrap().fragments_removed, 2); + let dataset = table.dataset().unwrap().get().await.unwrap(); + assert_eq!(dataset.fragments().len(), 1); + assert_eq!( + dataset.load_indices_by_name("rq").await.unwrap()[0].uuid, + original_index + ); + assert!( + dataset + .load_indices() + .await + .unwrap() + .iter() + .any(|index| index.name == FRAG_REUSE_INDEX_NAME) + ); + + let refined = query().fast_search().refine_factor(4); + let plan = refined.explain_plan(false).await.unwrap(); + assert!(plan.contains("ANNIvf"), "{plan}"); + let after = refined + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let after = concat_batches(&after[0].schema(), &after).unwrap(); + assert_eq!(after.num_rows(), 8); + assert_eq!(after["id"].as_ref(), before["id"].as_ref()); + assert_eq!(after["_distance"].as_ref(), before["_distance"].as_ref()); + let found = after["id"].as_primitive::().values(); + assert!(found.iter().all(|id| id % 7 != 0 && id % 3 != 0)); + assert!(after["_distance"].as_primitive::().values()[0] < 1e-5); + + let exact = query() + .bypass_vector_index() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let exact = concat_batches(&exact[0].schema(), &exact).unwrap(); + let truth = exact["id"].as_primitive::().values(); + let recall = found.iter().filter(|id| truth.contains(id)).count() as f64 / 8.0; + assert!(recall >= 0.5, "recall={recall}"); + } + #[tokio::test] async fn test_compaction_preserves_schema() { let conn = connect("memory://").execute().await.unwrap(); diff --git a/rust/lancedb/src/table/prewarm.rs b/rust/lancedb/src/table/prewarm.rs new file mode 100644 index 000000000..bc1128c54 --- /dev/null +++ b/rust/lancedb/src/table/prewarm.rs @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Options, previews, and results for data-cache prewarm. + +/// Data prewarm settings for [`super::Table::prewarm_data_async`] and +/// [`super::Table::explain_prewarm_data`]. +/// +/// The table handle supplies the database, namespace, and branch. Omitted +/// columns warm all fields. The filter selects conservative metadata ranges; +/// it does not execute a row-filter scan or change the source data. +#[derive(Clone, Default)] +#[non_exhaustive] +pub struct PrewarmDataOptions { + /// Lance field paths, including nested paths such as `attrs.score`. + pub columns: Vec, + /// An optional SQL predicate for metadata pruning. + pub filter: Option, + /// One row of typed filter values. Column i binds `$` and a + /// nonnumeric column name also binds `$name`. Requires server support. + pub parameters: Option, + /// Positive per-executor warming concurrency. Omit for the server default. + pub concurrency: Option, +} + +impl std::fmt::Debug for PrewarmDataOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PrewarmDataOptions") + .field("columns", &self.columns) + .field("filter", &self.filter) + .field("concurrency", &self.concurrency) + .field( + "parameter_count", + &self.parameters.as_ref().map(|batch| batch.num_columns()), + ) + .finish() + } +} + +impl PrewarmDataOptions { + /// Use server defaults and warm every column. + pub fn new() -> Self { + Self::default() + } + + /// Select fields to warm. An empty collection selects all columns. + pub fn columns(mut self, columns: impl IntoIterator>) -> Self { + self.columns = columns.into_iter().map(Into::into).collect(); + self + } + + /// Restrict warming using a single SQL predicate for metadata pruning. + pub fn filter(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } + + /// Bind scalar filter values without interpolating them into SQL text. + /// + /// ``` + /// # use lancedb::table::PrewarmDataOptions; + /// # use arrow_array::{ArrayRef, Int64Array, RecordBatch}; + /// # use std::sync::Arc; + /// let values = RecordBatch::try_from_iter(vec![( + /// "minimum", Arc::new(Int64Array::from(vec![100])) as ArrayRef, + /// )]).unwrap(); + /// let options = PrewarmDataOptions::new() + /// .columns(["payload"]) + /// .filter("id >= $minimum") + /// .parameters(values); + /// ``` + pub fn parameters(mut self, parameters: arrow_array::RecordBatch) -> Self { + self.parameters = Some(parameters); + self + } + + /// Set positive per-executor warming concurrency. + pub fn concurrency(mut self, concurrency: u32) -> Self { + self.concurrency = Some(concurrency); + self + } +} + +/// Metadata-only preview of a data-cache prewarm on one table snapshot. +/// +/// No warming job is submitted. A later submission chooses its own snapshot and +/// may produce a different plan if the table or index metadata has changed. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmDataPlan { + /// Source snapshot used to produce this preview. + pub table_version: u64, + /// Human-readable plan, intended for display rather than parsing. + pub plan: String, + /// Conservative metadata pruning, not exact row-filter matches. + pub pruning: PrewarmPruningSummary, +} + +/// Conservative pruning facts for a PREWARM preview. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmPruningSummary { + /// Proof mode, such as `unfiltered`, `constant`, `zonemap_ranges`, or + /// `full_warm_fallback`. Future servers may return additional modes. + pub mode: String, + /// Fragments in the source snapshot. + pub input_fragments: u64, + /// Fragments selected for warming. + pub selected_fragments: u64, + /// Fragments excluded by metadata proof. + pub pruned_fragments: u64, + /// Candidate physical intervals, when known; not an exact matching-row count. + pub selected_row_ranges: Option, + /// Why metadata could not prune, when reported. + pub fallback_reason: Option, +} + +/// Reported outcome of a remote data-prewarm job. Counts describe executor work; +/// absent measurements remain unknown rather than being inferred as zero. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmDataResult { + /// Source snapshot captured by the submitted prewarm. + pub table_version: u64, + /// Reported executors targeted; unknown on older workers. + pub executors_targeted: Option, + /// Executors that reached a successful or partial terminal state. + pub executors_completed: Option, + /// Subset of completed executors that reported partial warming. + pub executors_partial: Option, + /// Reported fragments selected; unknown on older workers. + pub fragments_selected: Option, + /// Reported ranges completed; unknown on older workers. + pub ranges_completed: Option, + /// Reported bytes read; unknown on older workers. + pub bytes_read: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + #[test] + fn result_preserves_zero_partial_and_unknown_measurements() { + let result: PrewarmDataResult = serde_json::from_value(serde_json::json!({ + "table_version":42,"executors_targeted":2,"executors_completed":2, + "executors_partial":1,"ranges_completed":0,"extra":"ignored", + })) + .unwrap(); + assert_eq!(result.executors_partial, Some(1)); + assert_eq!(result.ranges_completed, Some(0)); + assert_eq!(result.bytes_read, None); + assert!(serde_json::from_value::(serde_json::json!({})).is_err()); + assert!( + serde_json::from_value::( + serde_json::json!({"table_version":42,"bytes_read":-1}) + ) + .is_err() + ); + } + + #[tokio::test] + async fn local_table_rejects_durable_data_prewarm() { + let db = crate::connect(&format!("memory://prewarm-{}", uuid::Uuid::new_v4())) + .execute() + .await + .unwrap(); + let table = db + .create_empty_table( + "items", + Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])), + ) + .execute() + .await + .unwrap(); + let error = table + .prewarm_data_async(PrewarmDataOptions::new().filter("id > 0")) + .await + .unwrap_err(); + let preview_error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert!(matches!(preview_error, crate::Error::NotSupported { .. })); + assert!(matches!(error, crate::Error::NotSupported { .. })); + assert!( + error + .to_string() + .contains("only supported on remote tables") + ); + } +} diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 8a72872e8..f63bf50bf 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -12,6 +12,7 @@ use super::NativeTable; use crate::connection::NamespaceClientPushdownOperation; use crate::error::{Error, Result}; use crate::expr::expr_to_sql_string; +use crate::index::scalar::{FtsQuery, Operator as FullTextOperator}; use crate::query::{ DEFAULT_TOP_K, QueryExecutionOptions, QueryFilter, QueryRequest, Select, VectorQueryRequest, }; @@ -31,17 +32,16 @@ use datafusion_physical_plan::{ExecutionPlan, replace_children_if_necessary}; use lance::dataset::mem_wal::DatasetMemWalExt; use lance::dataset::scanner::DatasetRecordBatchStream; use lance::dataset::scanner::Scanner; -use lance::index::DatasetIndexInternalExt; use lance::io::exec::{ANNIvfBatchExec, ANNIvfSubIndexExec}; use lance_datafusion::exec::{analyze_plan as lance_analyze_plan, execute_plan}; use lance_index::IndexType; -use lance_index::metrics::NoOpMetricsCollector; +use lance_index::scalar::FullTextSearchQuery; use lance_index::vector::DIST_COL; use lance_linalg::distance::DistanceType as LanceDistanceType; use lance_namespace::LanceNamespace; use lance_namespace::models::{ QueryTableRequest as NsQueryTableRequest, QueryTableRequestColumns, - QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, + QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, StructuredFtsQuery, }; #[derive(Debug, Clone)] @@ -118,10 +118,24 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R } fn requires_local_namespace_execution(query: &AnyQuery) -> bool { - // The namespace QueryTable request cannot represent approx_mode, search_effort or use_rte. - // For use_rte that is worse than a tuning miss: RTE read routing lives only - // in `create_plan`, so a pushed-down query would return stale base-only data. - if query.base().use_rte.is_some() || query.base().take_offsets.is_some() { + // The namespace QueryTable request cannot represent approx_mode, search_effort, + // use_rte, order_by or scan_in_order. For use_rte that is worse than a tuning miss: + // RTE read routing lives only in `create_plan`, so a pushed-down query would return + // stale base-only data. A dropped order_by would return the wrong top-K rows, and a + // dropped ordered scan would silently stop guaranteeing manifest order. + if query.base().use_rte.is_some() + || query.base().has_take() + || query.base().scan_in_order == Some(true) + || query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { + return true; + } + if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some()) + { return true; } matches!( @@ -140,6 +154,47 @@ pub async fn analyze_query_plan( Ok(lance_analyze_plan(plan, Default::default()).await?) } +/// Reject requests that ask for storage order in a query shape that cannot +/// preserve it, or that also define a different result order. +fn validate_scan_in_order(query: &AnyQuery) -> Result<()> { + if query.base().scan_in_order != Some(true) { + return Ok(()); + } + + let ranked = match query { + AnyQuery::VectorQuery(_) => true, + AnyQuery::Query(query) => { + query.full_text_search.is_some() || query.reranker.is_some() || query.norm.is_some() + } + }; + if ranked { + return Err(Error::InvalidInput { + message: "scan_in_order(true) is only supported for ordinary scans; vector, \ + full-text, hybrid, and reranked queries return ranked results" + .to_string(), + }); + } + + if query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { + return Err(Error::InvalidInput { + message: "scan_in_order(true) conflicts with a nonempty order_by; remove the \ + ordering to keep manifest order, or remove scan_in_order(true) to sort" + .to_string(), + }); + } + + if query.base().has_take() { + return crate::query::validate_take_scan_in_order(query.base()); + } + + Ok(()) +} + /// Local Execution Path (DataFusion) async fn execute_generic_query( table: &NativeTable, @@ -163,10 +218,11 @@ pub async fn create_plan( options: QueryExecutionOptions, ) -> Result> { let query = query.canonicalized()?; + validate_scan_in_order(&query)?; if let AnyQuery::Query(request) = &query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::create_take_offsets_plan(table, request, offsets, options, false) + return crate::query::create_take_plan(table, request, options, request.preserve_order) .await; } @@ -215,13 +271,11 @@ pub async fn create_plan( Some(query.query_vector[0].len() as i32), )?); } - let vector_field = schema.field(column.as_ref().unwrap()).unwrap(); - let (_, element_type) = + let (vector_type, element_type) = lance::index::vector::utils::get_vector_type(schema, column.as_ref().unwrap())?; + let is_list_vector = matches!(&vector_type, DataType::List(_)); let is_binary = matches!(element_type, DataType::UInt8); - if matches!(vector_field.data_type(), DataType::List(_)) - || (query.base.offset.unwrap_or(0) == 0 && !is_binary) - { + if is_list_vector || (query.base.offset.unwrap_or(0) == 0 && !is_binary) { // Lance distinguishes these cases from the vector column type: a // list-like query against a List column is one multivector query, // while the same query against a FixedSizeList column is a batch of @@ -257,7 +311,7 @@ pub async fn create_plan( fsl_builder.append(true); } query_vector = Some(Arc::new(fsl_builder.finish())); - is_batch_query = !matches!(vector_field.data_type(), DataType::List(_)); + is_batch_query = !is_list_vector; } else { // Lance's batch path has no per-query offset, and its binary path // requires primitive UInt8 queries rather than a fixed-size list. @@ -421,6 +475,17 @@ pub async fn create_plan( scanner.order_by(Some(order_by.clone()))?; } + if let Some(scan_in_order) = query.base.scan_in_order { + scanner.scan_in_order(scan_in_order); + if scan_in_order { + // Legacy scalar-index plans can union materialized index rows with + // unindexed fragments and emit a different sequence. Explicit + // storage order must come from the manifest scan, so filters fall + // back to evaluating over the ordered fragments. + scanner.use_scalar_index(false); + } + } + let mut plan = scanner .create_plan() .await @@ -601,7 +666,7 @@ impl<'a> AnnExecRef<'a> { /// Cosine PQ/SQ/RQ indices normalize their vectors and use squared L2 internally. This /// preserves ranking, but squared L2 over unit vectors is twice the cosine distance. Flat /// cosine indices calculate cosine directly, so they are not included. -async fn normalized_l2_ann_indices(plan: &dyn ExecutionPlan) -> Result> { +async fn normalized_l2_ann_indices(plan: &dyn ExecutionPlan) -> Result> { let mut ann_plans = Vec::new(); find_ann_plans(plan, &mut ann_plans); @@ -611,17 +676,22 @@ async fn normalized_l2_ann_indices(plan: &dyn ExecutionPlan) -> Result = ann + .indices() + .iter() + .map(|index| index.uuid) + .filter(|uuid| checked.insert(*uuid)) + .collect(); + if uuids.is_empty() { + continue; + } + let types = ann + .dataset() + .vector_index_types(&ann.query().column, &uuids) + .await?; + for (uuid, index_type) in uuids.into_iter().zip(types) { if matches!( - vector_index.index_type(), + index_type, IndexType::IvfPq | IndexType::IvfSq | IndexType::IvfRq @@ -678,7 +748,7 @@ fn collect_ann_plans( fn normalize_ann_branches( public_plan: Arc, internal_plan: Arc, - normalized_l2_indices: &HashSet, + normalized_l2_indices: &HashSet, ) -> Result> { let mut internal_ann_plans = VecDeque::new(); collect_ann_plans(&internal_plan, &mut internal_ann_plans); @@ -696,7 +766,7 @@ fn normalize_ann_branches( fn replace_ann_branches( public_plan: Arc, internal_ann_plans: &mut VecDeque>, - normalized_l2_indices: &HashSet, + normalized_l2_indices: &HashSet, ) -> Result> { if let Some(public_ann) = AnnExecRef::from_plan(public_plan.as_ref()) { let internal_plan = internal_ann_plans @@ -728,7 +798,7 @@ fn replace_ann_branches( let normalized_count = public_ann .indices() .iter() - .filter(|index| normalized_l2_indices.contains(&index.uuid.to_string())) + .filter(|index| normalized_l2_indices.contains(&index.uuid)) .count(); if normalized_count == 0 { return Ok(public_plan); @@ -859,6 +929,33 @@ async fn execute_namespace_query( parse_arrow_ipc_response(response_bytes).await } +fn namespace_fts_query(fts: &FullTextSearchQuery) -> Result> { + if !matches!(&fts.query, FtsQuery::Match(query) if query.operator == FullTextOperator::Or) { + let query = serde_json::to_value(&fts.query) + .and_then(serde_json::from_value) + .map_err(|error| Error::InvalidInput { + message: format!("Cannot serialize namespace full-text query: {error}"), + })?; + Ok(Box::new(QueryTableRequestFullTextQuery { + string_query: None, + structured_query: Some(Box::new(StructuredFtsQuery::new(query))), + })) + } else { + let columns = fts.columns(); + Ok(Box::new(QueryTableRequestFullTextQuery { + string_query: Some(Box::new(StringFtsQuery { + query: fts.query.query().clone(), + columns: if columns.is_empty() { + None + } else { + Some(columns.into_iter().collect()) + }, + })), + structured_query: None, + })) + } +} + /// Convert an AnyQuery to the namespace QueryTableRequest format. fn convert_to_namespace_query(query: &AnyQuery) -> Result { query.base().check_filter()?; @@ -913,21 +1010,12 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { } // Convert FTS query if present - let full_text_query = vq.base.full_text_search.as_ref().map(|fts| { - let columns = fts.columns(); - let columns_vec = if columns.is_empty() { - None - } else { - Some(columns.into_iter().collect()) - }; - Box::new(QueryTableRequestFullTextQuery { - string_query: Some(Box::new(StringFtsQuery { - query: fts.query.to_string(), - columns: columns_vec, - })), - structured_query: None, - }) - }); + let full_text_query = vq + .base + .full_text_search + .as_ref() + .map(namespace_fts_query) + .transpose()?; Ok(NsQueryTableRequest { id: None, // Will be set in namespace_query @@ -964,7 +1052,6 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { let k = match q.limit { Some(limit) => limit as i32, - None if q.full_text_search.is_some() => DEFAULT_TOP_K as i32, None => i32::MAX, }; @@ -996,20 +1083,11 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { }; // Handle full text search if present - let full_text_query = q.full_text_search.as_ref().map(|fts| { - let columns_vec = if fts.columns().is_empty() { - None - } else { - Some(fts.columns().iter().cloned().collect()) - }; - Box::new(QueryTableRequestFullTextQuery { - string_query: Some(Box::new(StringFtsQuery { - query: fts.query.to_string(), - columns: columns_vec, - })), - structured_query: None, - }) - }); + let full_text_query = q + .full_text_search + .as_ref() + .map(namespace_fts_query) + .transpose()?; // Empty vector for non-vector queries let vector = Box::new(QueryTableRequestVector { @@ -1024,6 +1102,7 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { filter, columns, prefilter: Some(q.prefilter), + fast_search: Some(q.fast_search), offset: q.offset.map(|o| o as i32), vector_column: None, // No vector column for plain queries with_row_id: Some(q.with_row_id), @@ -1148,6 +1227,7 @@ async fn parse_arrow_ipc_response(bytes: bytes::Bytes) -> Result Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + #[tokio::test] async fn test_parse_arrow_ipc_response_handles_file_and_stream() { use arrow_array::{Int32Array, RecordBatch}; @@ -1415,7 +1510,45 @@ mod tests { let ns_request = convert_to_namespace_query(&any_query).unwrap(); - assert_eq!(ns_request.k, 10); + assert_eq!(ns_request.k, i32::MAX); + } + + #[test] + fn test_namespace_fts_operators_and_unbounded_counts() { + for columns in [ + vec!["text".to_string()], + vec!["title".to_string(), "body".to_string()], + ] { + let fts = FullTextSearchQuery::new_query( + MatchQuery::new("gripper closed".to_string()) + .with_operator(FullTextOperator::And) + .into(), + ) + .with_columns(&columns) + .unwrap(); + let request = convert_to_namespace_query(&AnyQuery::Query(QueryRequest { + full_text_search: Some(fts), + ..Default::default() + })) + .unwrap(); + assert_eq!(request.k, i32::MAX); + let full_text_query = request.full_text_query.unwrap(); + assert!(full_text_query.string_query.is_none()); + let query = + serde_json::to_value(full_text_query.structured_query.unwrap().query).unwrap(); + if columns.len() == 1 { + assert_eq!(query["match"]["operator"], "And"); + assert_eq!(query["match"]["column"], "text"); + } else { + let leaves = query["multi_match"]["match_queries"].as_array().unwrap(); + assert_eq!(leaves.len(), 2); + assert!(leaves.iter().all(|leaf| leaf["operator"] == "And")); + } + } + let request = + namespace_fts_query(&FullTextSearchQuery::new("gripper closed".to_string())).unwrap(); + assert_eq!(request.string_query.unwrap().query, "gripper closed"); + assert!(request.structured_query.is_none()); } #[tokio::test] @@ -1805,6 +1938,60 @@ mod tests { assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); } + #[tokio::test] + async fn test_execute_query_order_by_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use crate::table::query::execute_query; + use arrow_array::{Int32Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + // Insertion order differs from ascending id, so a pushed-down query that + // drops order_by would return 3 instead of the correct top-1 row 1. + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3, 1, 2]))]).unwrap(); + + let table = conn + .create_table("test_order_by_namespace_fallback", vec![batch]) + .execute() + .await + .unwrap(); + let namespace_client = Arc::new(CountingNamespaceClient::default()); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(namespace_client.clone()); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let query = AnyQuery::Query(QueryRequest { + limit: Some(1), + order_by: Some(vec![ColumnOrdering::asc_nulls_first("id".to_string())]), + ..Default::default() + }); + + let stream = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap(); + let batches = stream.try_collect::>().await.unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + + assert_eq!(ids, vec![1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn test_query_snapshot_disables_namespace_pushdown() { use crate::connect; @@ -1905,6 +2092,115 @@ mod tests { "plan should add query_index column, got:\n{display}" ); } + + #[tokio::test] + async fn test_create_plan_batch_vector_missing_column_returns_sdk_error() { + use crate::connect; + use crate::table::query::create_plan; + use arrow_array::{Float32Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "vector", + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2), + false, + ), + ])); + let batch = RecordBatch::new_empty(schema); + let table = conn + .create_table("test_batch_vector_missing_column", vec![batch]) + .execute() + .await + .unwrap(); + let native_table = table.as_native().unwrap(); + + let query = AnyQuery::VectorQuery(VectorQueryRequest { + base: QueryRequest { + limit: Some(1), + ..Default::default() + }, + column: Some("missing_vector".to_string()), + query_vector: vec![ + Arc::new(Float32Array::from(vec![1.0, 2.0])), + Arc::new(Float32Array::from(vec![3.0, 4.0])), + ], + ..Default::default() + }); + + let error = create_plan(native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap_err(); + + assert!( + matches!( + &error, + Error::Lance { + source: lance::Error::Index { message, .. } + } if message.contains("column missing_vector does not exist in schema") + ), + "expected ordinary vector column validation error, got: {error:?}" + ); + } + + #[tokio::test] + async fn test_cold_cosine_rq_plan_only_needs_index_header() { + use crate::index::{Index, vector::IvfRqIndexBuilder}; + use lance::index::DatasetIndexExt; + + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let conn = crate::connect(uri).execute().await.unwrap(); + let vectors = Arc::new(fixed_size_list_array( + (0..512 * 8).map(|n| (1 + n % 31) as f32).collect(), + 8, + )); + let schema = Arc::new(Schema::new(vec![arrow_schema::Field::new( + "vector", + vectors.data_type().clone(), + false, + )])); + let batch = RecordBatch::try_new(schema, vec![vectors]).unwrap(); + let table = conn.create_table("vectors", batch).execute().await.unwrap(); + table + .create_index( + &["vector"], + Index::IvfRq( + IvfRqIndexBuilder::default() + .distance_type(crate::DistanceType::Cosine) + .num_partitions(1), + ), + ) + .execute() + .await + .unwrap(); + let dataset = table.dataset().unwrap().get().await.unwrap(); + let indices = dataset.load_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + // The quantizer is needed to execute the search. Planning should only read + // the segment's type from index.idx, even with an empty session cache. + let auxiliary = dir + .path() + .join("vectors.lance/_indices") + .join(indices[0].uuid.to_string()) + .join(lance_index::INDEX_AUXILIARY_FILE_NAME); + std::fs::remove_file(auxiliary).unwrap(); + let conn = crate::connect(uri).execute().await.unwrap(); + let table = conn.open_table("vectors").execute().await.unwrap(); + let plan = table + .vector_search([1.0_f32; 8].as_slice()) + .unwrap() + .create_plan(QueryExecutionOptions::default()) + .await + .unwrap(); + let mut ann = Vec::new(); + find_ann_plans(plan.as_ref(), &mut ann); + assert_eq!(ann.len(), 1); + assert_eq!(ann[0].query().metric_type, Some(LanceDistanceType::Cosine)); + } + #[rstest::rstest] #[case::modern(false)] #[case::legacy(true)] @@ -1919,9 +2215,10 @@ mod tests { use crate::connect; use crate::index::{Index, vector::IvfPqIndexBuilder}; use lance::index::{ - DatasetIndexExt, + DatasetIndexExt, DatasetIndexInternalExt, vector::{IndexFileVersion, VectorIndexParams}, }; + use lance_index::metrics::NoOpMetricsCollector; fn normalized_vector(state: &mut u64, dimension: usize) -> Vec { let mut vector = (0..dimension) @@ -2346,4 +2643,300 @@ mod tests { Some(ApproxMode::Accurate) ); } + + #[tokio::test] + async fn test_scan_in_order_local_multi_fragment_contract() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap() + }; + + let table = conn + .create_table("scan_in_order_contract", batch(vec![0, 1])) + .execute() + .await + .unwrap(); + table.add(batch(vec![2, 3])).execute().await.unwrap(); + table.add(batch(vec![4, 5])).execute().await.unwrap(); + + let fragments = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .get_fragments() + .len(); + assert_eq!(fragments, 3, "the test needs real multi-fragment data"); + + // An ordered scan must not introduce a global sort. + let plan = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .explain_plan(false) + .await + .unwrap(); + assert!( + !plan.contains("SortExec"), + "scan_in_order(true) must not add a sort, got:\n{plan}" + ); + + // Pin one version so repeated executions describe the same manifest. + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + for _ in 0..2 { + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]); + } + + // The default keeps the ordered local behavior. + let batches = table + .query() + .select(Select::columns(&["id"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]); + + // Allowing unordered scans changes no membership. + let mut unordered = collect_i32( + &table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(), + ); + unordered.sort(); + assert_eq!(unordered, vec![0, 1, 2, 3, 4, 5]); + + // An explicit sort still wins when storage order is not required. + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(false) + .order_by(Some(vec![ColumnOrdering::desc_nulls_last( + "id".to_string(), + )])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![5, 4, 3, 2, 1, 0]); + + // Deletions keep manifest order, and small output batches plus + // limit/offset must not disturb it. + table.checkout_latest().await.unwrap(); + table.delete("id = 3").await.unwrap(); + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .offset(1) + .limit(2) + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert!( + batches.iter().all(|batch| batch.num_rows() <= 1), + "max_batch_length must stay bounded" + ); + assert_eq!(collect_i32(&batches), vec![1, 2]); + } + + #[tokio::test] + async fn test_scan_in_order_rejects_ranked_and_sorted_queries() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let vector = fixed_size_list_array(vec![0.0, 0.0, 1.0, 0.0, 2.0, 0.0], 2); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vector.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int32Array::from(vec![0, 1, 2])), Arc::new(vector)], + ) + .unwrap(); + let table = conn + .create_table("scan_in_order_conflicts", batch) + .execute() + .await + .unwrap(); + + let err = table + .query() + .scan_in_order(true) + .order_by(Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())])) + .execute() + .await + .err() + .expect("ranked and sorted scans must be rejected"); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("nonempty order_by")), + "unexpected error: {err}" + ); + + let err = table + .query() + .scan_in_order(true) + .nearest_to(vec![0.0f32, 0.0]) + .unwrap() + .execute() + .await + .err() + .expect("ranked scans must be rejected"); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("ranked results")), + "unexpected error: {err}" + ); + } + + #[tokio::test] + async fn test_scan_in_order_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap() + }; + // Insertion order differs from sorted order so a dropped scan order or + // an accidental sort changes the result. + let table = conn + .create_table("scan_in_order_namespace", batch(vec![3, 1])) + .execute() + .await + .unwrap(); + table.add(batch(vec![2])).execute().await.unwrap(); + + let namespace_client = Arc::new(CountingNamespaceClient::default()); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(namespace_client.clone()); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let query = AnyQuery::Query(QueryRequest { + filter: Some(QueryFilter::Sql("id >= 1".to_string())), + select: Select::columns(&["id"]), + limit: Some(2), + scan_in_order: Some(true), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&query)); + + let batches = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![3, 1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + + // Allowing unordered scans does not require local execution. + let allow_unordered = AnyQuery::Query(QueryRequest { + scan_in_order: Some(false), + ..Default::default() + }); + assert!(!requires_local_namespace_execution(&allow_unordered)); + + // An explicit sort is already local because the namespace request has + // no order_by field. + let sorted = AnyQuery::Query(QueryRequest { + order_by: Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())]), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&sorted)); + } + + #[tokio::test] + async fn test_scan_in_order_true_rejected_on_rte() { + use crate::connect; + use crate::table::RTEWriteSpec; + use arrow_schema::{DataType, Field, Schema}; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![0, 1]))]).unwrap(); + let table = conn + .create_table("scan_in_order_rte", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + + let err = table + .query() + .scan_in_order(true) + .execute() + .await + .err() + .expect("RTE scans cannot guarantee manifest order"); + assert!( + matches!(&err, Error::NotSupported { message } + if message.contains("scan_in_order(true)") && message.contains("use_rte(false)")), + "unexpected error: {err}" + ); + + // The base table can still be read in storage order explicitly. + let batches = table + .query() + .scan_in_order(true) + .use_rte(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1]); + } } diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index d348a6668..eddb4d0c0 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -161,6 +161,19 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if !query.query_vector.is_empty() && query.base.full_text_search.is_some() { return unsupported("hybrid (vector + full-text) search"); } + // Take lookups add with_row_id internally to restore requested order. Report + // the unsupported take before that implementation detail. Neither _rowid nor + // _rowoffset is exposed by the LSM scanner, which only exposes _rowaddr. + if let Some(QueryFilter::Datafusion(expr)) = &query.base.filter + && expr + .column_refs() + .iter() + .any(|c| c.name == "_rowid" || c.name == "_rowoffset") + { + return unsupported( + "take by row id or row offset (the LSM scanner has no stable _rowid / _rowoffset)", + ); + } if query.base.with_row_id { return unsupported("with_row_id (the LSM scanner exposes _rowaddr, not a stable _rowid)"); } @@ -170,6 +183,11 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if query.base.order_by.is_some() { return unsupported("order_by"); } + if query.base.scan_in_order == Some(true) { + return unsupported( + "scan_in_order(true) (the LSM scanner does not preserve base manifest order)", + ); + } // Vector-only knobs the LSM scanner cannot honor. Both change results rather // than just recall, so error instead of silently ignoring them: distance_range // would return rows outside the bound, and use_index(false) asks for a @@ -204,19 +222,6 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if let Some(QueryFilter::Substrait(_)) = &query.base.filter { return unsupported("Substrait filters"); } - // Take-by-row-id / row-offset queries carry a `_rowid` / `_rowoffset` filter, - // columns the LSM scanner never exposes (only `_rowaddr`); reject with guidance - // rather than failing deep in datafusion with a column-not-found error. - if let Some(QueryFilter::Datafusion(expr)) = &query.base.filter - && expr - .column_refs() - .iter() - .any(|c| c.name == "_rowid" || c.name == "_rowoffset") - { - return unsupported( - "take by row id or row offset (the LSM scanner has no stable _rowid / _rowoffset)", - ); - } Ok(()) } diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 330cdfb6d..bf0c84e8f 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -55,61 +55,575 @@ use crate::function::validate_gpu_class_name; use crate::job::Job; use crate::{Error, Result}; +/// Aggregate worker resources for one Enterprise Function refresh. +/// +/// CPU is in millicores (1000 = one core) and memory is in bytes. These +/// values cap the Function workers together; they are not per-worker +/// allocations. The default GPU budget is zero, which describes a CPU-only +/// Function. This option is rejected by LanceDB Embedded refreshes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionWorkerResourceBudget { + pub total_cpu_millis: u64, + pub total_memory_bytes: u64, + /// Aggregate GPU budget across the refresh. Zero is CPU-only. + #[serde(default)] + pub total_gpu_count: u32, +} + +impl FunctionWorkerResourceBudget { + /// Create a CPU-only aggregate budget. + pub fn new(total_cpu_millis: u64, total_memory_bytes: u64) -> Self { + Self { + total_cpu_millis, + total_memory_bytes, + total_gpu_count: 0, + } + } + + /// Set the aggregate GPU budget. + pub fn with_total_gpu_count(mut self, total_gpu_count: u32) -> Self { + self.total_gpu_count = total_gpu_count; + self + } + + /// Require every per-tier resource limit to request at least one unit. + pub fn validate(&self) -> Result<()> { + if self.total_cpu_millis == 0 { + return Err(Error::InvalidInput { + message: "total_cpu_millis must be greater than zero".into(), + }); + } + if self.total_memory_bytes == 0 { + return Err(Error::InvalidInput { + message: "total_memory_bytes must be greater than zero".into(), + }); + } + Ok(()) + } +} + +/// CPU, memory, and ephemeral-storage limits for one Function refresh +/// control-plane pod. +/// +/// This sizes the supervisor or planning worker pod for a registered +/// Function refresh. LanceDB Embedded rejects it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRefreshPodResources { + /// CPU limit in millicores; 1000 is one CPU. + pub cpu_millis: u64, + /// Memory limit in bytes. + pub memory_bytes: u64, + /// Ephemeral storage limit in bytes. + pub ephemeral_storage_bytes: u64, +} + +impl FunctionRefreshPodResources { + /// Create positive CPU, memory, and ephemeral-storage limits. + pub fn new(cpu_millis: u64, memory_bytes: u64, ephemeral_storage_bytes: u64) -> Self { + Self { + cpu_millis, + memory_bytes, + ephemeral_storage_bytes, + } + } + + fn validate(&self, prefix: &str) -> Result<()> { + for (name, value) in [ + ("cpu_millis", self.cpu_millis), + ("memory_bytes", self.memory_bytes), + ("ephemeral_storage_bytes", self.ephemeral_storage_bytes), + ] { + if value == 0 { + return Err(Error::InvalidInput { + message: format!("{prefix}.{name} must be greater than zero"), + }); + } + } + Ok(()) + } +} + +/// Resources and sizing policy for the CPU-only planning fleet of one +/// registered Function refresh. +/// +/// `resources` describes one planning worker pod. The remaining fields bound +/// how many workers may run and how much work each worker receives. LanceDB +/// Embedded rejects this option. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRefreshPlanningConfig { + /// CPU, memory, and ephemeral-storage limits for one planning worker. + pub resources: FunctionRefreshPodResources, + /// Maximum number of planning workers. + pub max_workers: usize, + /// Maximum rows assigned to one planning worker. + pub rows_per_worker: u64, + /// Maximum fragments assigned to one planning worker. + pub fragments_per_worker: u64, +} + +impl FunctionRefreshPlanningConfig { + /// Create a planning configuration; every value must be positive. + pub fn new( + resources: FunctionRefreshPodResources, + max_workers: usize, + rows_per_worker: u64, + fragments_per_worker: u64, + ) -> Self { + Self { + resources, + max_workers, + rows_per_worker, + fragments_per_worker, + } + } + + fn validate(&self) -> Result<()> { + self.resources.validate("planning_workers.resources")?; + if self.max_workers == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.max_workers must be greater than zero".into(), + }); + } + if self.rows_per_worker == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.rows_per_worker must be greater than zero".into(), + }); + } + if self.fragments_per_worker == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.fragments_per_worker must be greater than zero".into(), + }); + } + Ok(()) + } +} + /// Options for refreshing a computed column. -#[derive(Debug, Clone, Default)] +/// +/// Serializes to the Enterprise backfill request body, one key per set +/// option; the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form takes the +/// same names. +#[derive(Debug, Clone, Default, Serialize)] #[non_exhaustive] pub struct RefreshColumnOptions { + /// Select exactly the current failed rows. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_errors: Option, + /// Restrict retry selection to this job. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_job_id: Option, + /// Restrict retry selection to this exception class. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_error_type: Option, + /// Explicitly release and retry quarantined rows. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_quarantined: Option, + /// Upgrade the bound Function to this exact version. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub function_version: Option, + /// Rows recomputed by a Function upgrade. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub recompute: Option, + /// Only refresh the rows matching this SQL filter. Enterprise only. + #[serde(rename = "where", skip_serializing_if = "Option::is_none")] + pub where_clause: Option, + /// Total Function refresh attempts, including the initial job. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_job_attempts: Option, + /// Override the Function's default user-code retry policy. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_policy: Option, + /// Action after user-code failure or retry exhaustion. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub error_policy: Option, + /// Under a skip policy, fail the job once more than this share of rows + /// has failed, 0 to 1. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_failed_fraction: Option, + /// Under a skip policy, fail the job once more than this many rows have + /// failed. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_failed_rows: Option, + /// Deadline for one Function call, in seconds. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub row_timeout_seconds: Option, + /// Deadline for Function initialization, in seconds. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub init_timeout_seconds: Option, + /// Worker count for an expression column in LanceDB Enterprise; + /// registered Function columns reject it. + #[serde(skip_serializing_if = "Option::is_none")] + pub num_workers: Option, + /// At most this many executor processes per Function worker. Enterprise + /// only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_executor_processes_per_worker: Option, /// Maximum rows per Function call in LanceDB Enterprise. /// /// Must be greater than zero. `None` uses the server default. This has no /// effect on expression-backed columns in LanceDB Embedded. + #[serde(skip_serializing_if = "Option::is_none")] pub batch_size: Option, + /// Override the registered Function's maximum concurrent user-code calls + /// for this logical execution. Must be greater than zero. `None` uses the + /// registration default, or disabled when the Function declares none. + /// This is not an account quota and does not change total resource limits. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_concurrency: Option, + /// Opt-in row-count threshold for publishing completed Function outputs. + /// + /// Must be greater than zero. `None` keeps whole-fragment publication. + /// Actual publication boundaries can be larger than this threshold because + /// they also depend on completed work and Function batching. LanceDB Embedded + /// rejects this option. + #[serde(skip_serializing_if = "Option::is_none")] + pub publication_interval_rows: Option, + /// Total CPU budget for this execution, in millicores. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_cpu_millis: Option, + /// Total memory budget for this execution, in bytes. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_memory_bytes: Option, + /// CPU, memory, and ephemeral-storage limits for the Function refresh + /// supervisor pod. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub supervisor_resources: Option, + /// Resources and sizing limits for the Function refresh planning fleet. + /// Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub planning_workers: Option, /// GPU class for Function workers in LanceDB Enterprise. /// /// `None` keeps the Function's registered class, or the deployment default /// when the Function does not declare one. + #[serde(skip_serializing_if = "Option::is_none")] pub gpu_class: Option, - /// Positive aggregate GPU budget for Function workers in LanceDB - /// Enterprise. - /// - /// `None` leaves the server's configured budget unchanged. + /// Positive number of GPUs allocated to each Function worker. + #[serde(skip_serializing_if = "Option::is_none")] pub gpu_count: Option, + /// Nonnegative total GPU budget for Function workers in LanceDB Enterprise. + /// Omitted values inherit column defaults, then Function defaults, then + /// deployment defaults. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_gpu_count: Option, } impl RefreshColumnOptions { + /// Retry only current failures, using the server's row identities. + pub fn retry_errors(mut self, enabled: bool) -> Self { + self.retry_errors = Some(enabled); + self + } + + /// Restrict a failed-row retry to one recorded job. + pub fn retry_job_id(mut self, job_id: impl Into) -> Self { + self.retry_job_id = Some(job_id.into()); + self + } + + /// Restrict a failed-row retry to one exception class. + pub fn retry_error_type(mut self, error_type: impl Into) -> Self { + self.retry_error_type = Some(error_type.into()); + self + } + + /// Release quarantine when explicitly retrying failures. + pub fn include_quarantined(mut self, include: bool) -> Self { + self.include_quarantined = Some(include); + self + } + + /// Change the Function version and select the upgrade's recomputation policy. + pub fn upgrade( + mut self, + version: impl Into, + recompute: crate::function::FunctionRecompute, + ) -> Self { + self.function_version = Some(version.into()); + self.recompute = Some(recompute); + self + } + /// Only refresh the rows matching `filter`. + pub fn where_clause(mut self, filter: impl Into) -> Self { + self.where_clause = Some(filter.into()); + self + } + + /// Fail the job once more than `fraction` of its rows has failed. + pub fn max_failed_fraction(mut self, fraction: f64) -> Self { + self.max_failed_fraction = Some(fraction); + self + } + + /// Fail the job once more than `rows` rows have failed. + pub fn max_failed_rows(mut self, rows: u64) -> Self { + self.max_failed_rows = Some(rows); + self + } + + /// Give each Function call at most `seconds` to return. + pub fn row_timeout_seconds(mut self, seconds: f64) -> Self { + self.row_timeout_seconds = Some(seconds); + self + } + + /// Give Function initialization at most `seconds` to complete. + pub fn init_timeout_seconds(mut self, seconds: f64) -> Self { + self.init_timeout_seconds = Some(seconds); + self + } + + /// Request `num_workers` workers for an expression column refresh. + pub fn num_workers(mut self, num_workers: usize) -> Self { + self.num_workers = Some(num_workers); + self + } + + /// Set the total job attempt limit for automatic Function refresh recovery. + pub fn max_job_attempts(mut self, attempts: u32) -> Self { + self.max_job_attempts = Some(attempts); + self + } + + /// Cap executor processes per Function worker at `processes`. + pub fn max_executor_processes_per_worker(mut self, processes: u32) -> Self { + self.max_executor_processes_per_worker = Some(processes); + self + } + + /// Override retries of failed Function calls for this refresh. + pub fn retry_policy(mut self, policy: crate::function::FunctionRetryPolicy) -> Self { + self.retry_policy = Some(policy); + self + } + + /// Select fail or skip after the retry policy is exhausted. + pub fn error_policy(mut self, policy: crate::function::FunctionErrorPolicy) -> Self { + self.error_policy = Some(policy); + self + } /// Limit each Function call to at most `batch_size` rows. pub fn batch_size(mut self, batch_size: usize) -> Self { self.batch_size = Some(batch_size); self } + /// Override the registered Function's maximum concurrent user-code calls + /// for this logical execution. + pub fn max_concurrency(mut self, max_concurrency: u32) -> Self { + self.max_concurrency = Some(max_concurrency); + self + } + + /// Use `rows` as the opt-in publication threshold for completed Function + /// outputs. The actual publication boundary can be larger than this value. + pub fn publication_interval_rows(mut self, rows: u64) -> Self { + self.publication_interval_rows = Some(rows); + self + } + + /// Override the total CPU budget for this refresh. + pub fn total_cpu_millis(mut self, value: u64) -> Self { + self.total_cpu_millis = Some(value); + self + } + + /// Override the total memory budget for this refresh. + pub fn total_memory_bytes(mut self, value: u64) -> Self { + self.total_memory_bytes = Some(value); + self + } + + /// Set the Function refresh supervisor pod resources. + pub fn supervisor_resources(mut self, resources: FunctionRefreshPodResources) -> Self { + self.supervisor_resources = Some(resources); + self + } + + /// Set the Function refresh planning fleet resources and sizing. + pub fn planning_workers(mut self, planning: FunctionRefreshPlanningConfig) -> Self { + self.planning_workers = Some(planning); + self + } + /// Request Function workers from `gpu_class`. pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { self.gpu_class = Some(gpu_class.into()); self } - /// Request an aggregate GPU budget of `gpu_count`. + /// Set the number of GPUs allocated to each Function worker. pub fn gpu_count(mut self, gpu_count: u32) -> Self { self.gpu_count = Some(gpu_count); self } + /// Request an aggregate GPU budget of `total_gpu_count`. + pub fn total_gpu_count(mut self, total_gpu_count: u32) -> Self { + self.total_gpu_count = Some(total_gpu_count); + self + } + + /// The first set option a LanceDB Embedded refresh cannot honor, if any. + pub fn enterprise_only_option(&self) -> Option<&'static str> { + [ + ("retry_errors", self.retry_errors.is_some()), + ("retry_job_id", self.retry_job_id.is_some()), + ("retry_error_type", self.retry_error_type.is_some()), + ("include_quarantined", self.include_quarantined.is_some()), + ("function_version", self.function_version.is_some()), + ("recompute", self.recompute.is_some()), + ("where", self.where_clause.is_some()), + ("retry_policy", self.retry_policy.is_some()), + ("error_policy", self.error_policy.is_some()), + ("max_failed_fraction", self.max_failed_fraction.is_some()), + ("max_failed_rows", self.max_failed_rows.is_some()), + ("row_timeout_seconds", self.row_timeout_seconds.is_some()), + ("init_timeout_seconds", self.init_timeout_seconds.is_some()), + ("num_workers", self.num_workers.is_some()), + ("max_job_attempts", self.max_job_attempts.is_some()), + ( + "max_executor_processes_per_worker", + self.max_executor_processes_per_worker.is_some(), + ), + ("max_concurrency", self.max_concurrency.is_some()), + ( + "publication_interval_rows", + self.publication_interval_rows.is_some(), + ), + ("gpu_count", self.gpu_count.is_some()), + ("total_cpu_millis", self.total_cpu_millis.is_some()), + ("total_memory_bytes", self.total_memory_bytes.is_some()), + ("supervisor_resources", self.supervisor_resources.is_some()), + ("planning_workers", self.planning_workers.is_some()), + ] + .into_iter() + .find_map(|(name, set)| set.then_some(name)) + } + /// Validate client-side constraints before any request is sent. pub fn validate(&self) -> Result<()> { + let retry = self.retry_errors == Some(true); + if (retry || self.function_version.is_some()) && self.where_clause.is_some() { + return Err(Error::InvalidInput { + message: "retry_errors and Function upgrades cannot be combined with where".into(), + }); + } + if !retry + && (self.retry_job_id.is_some() + || self.retry_error_type.is_some() + || self.include_quarantined == Some(true)) + { + return Err(Error::InvalidInput { + message: "retry filters require retry_errors=true".into(), + }); + } + if self + .function_version + .as_ref() + .is_some_and(|version| version.is_empty()) + || (self.recompute.is_some() && self.function_version.is_none()) + { + return Err(Error::InvalidInput { + message: "recompute requires a nonempty function_version".into(), + }); + } + if self + .where_clause + .as_deref() + .is_some_and(|f| f.trim().is_empty()) + { + return Err(Error::InvalidInput { + message: "where must not be empty".into(), + }); + } + if let Some(policy) = &self.retry_policy { + policy.validate()?; + } + if self + .max_failed_fraction + .is_some_and(|f| !f.is_finite() || !(0.0..=1.0).contains(&f)) + { + return Err(Error::InvalidInput { + message: "max_failed_fraction must be a finite number between 0 and 1".into(), + }); + } + for (name, seconds) in [ + ("row_timeout_seconds", self.row_timeout_seconds), + ("init_timeout_seconds", self.init_timeout_seconds), + ] { + if seconds.is_some_and(|s| !s.is_finite() || s <= 0.0) { + return Err(Error::InvalidInput { + message: format!("{name} must be a positive finite number"), + }); + } + } + if self.num_workers == Some(0) { + return Err(Error::InvalidInput { + message: "num_workers must be greater than zero".into(), + }); + } + if self.max_job_attempts == Some(0) { + return Err(Error::InvalidInput { + message: "max_job_attempts must be greater than zero".into(), + }); + } + if self.max_executor_processes_per_worker == Some(0) { + return Err(Error::InvalidInput { + message: "max_executor_processes_per_worker must be greater than zero".into(), + }); + } if self.batch_size == Some(0) { return Err(Error::InvalidInput { message: "batch_size must be greater than zero".into(), }); } + if self.max_concurrency == Some(0) { + return Err(Error::InvalidInput { + message: "max_concurrency must be greater than zero".into(), + }); + } + if self.publication_interval_rows == Some(0) { + return Err(Error::InvalidInput { + message: "publication_interval_rows must be greater than zero".into(), + }); + } + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { + return Err(Error::InvalidInput { + message: "total_cpu_millis and total_memory_bytes must be positive integers".into(), + }); + } + + if let Some(resources) = &self.supervisor_resources { + resources.validate("supervisor_resources")?; + } + if let Some(planning) = &self.planning_workers { + planning.validate()?; + } if let Some(gpu_class) = &self.gpu_class { validate_gpu_class_name(gpu_class)?; } if self.gpu_count == Some(0) { return Err(Error::InvalidInput { - message: "gpu_count must be greater than zero".into(), + message: "gpu_count must be positive".into(), }); } + if self + .gpu_count + .zip(self.total_gpu_count) + .is_some_and(|(per_worker, total)| per_worker > total) + { + return Err(Error::InvalidInput { + message: "total_gpu_count cannot fit one Function worker".into(), + }); + } + Ok(()) } } @@ -157,6 +671,7 @@ async fn execute_refresh_column_with_source( schema.clone(), column, &expression, + dataset.session().datafusion_session(), )?); ensure_inputs_filled(&dataset, &schema, column, &bound).await?; let field = dataset @@ -259,7 +774,10 @@ async fn execute_refresh_column_with_source( let session = dataset.session(); let new_dataset = Dataset::commit( WriteDestination::Dataset(dataset.clone()), - Operation::DataReplacement { replacements }, + Operation::DataReplacement { + replacements, + data_change: true, + }, Some(source_version), None, None, @@ -339,7 +857,12 @@ async fn ensure_inputs_filled( ), }); }; - let input_bound = super::computed_columns::bind(schema.clone(), input, expression)?; + let input_bound = super::computed_columns::bind( + schema.clone(), + input, + expression, + dataset.session().datafusion_session(), + )?; let mut unfilled = 0u64; for fragment in dataset.get_fragments() { unfilled += count_fragment_gains(dataset, &fragment, &input_bound, input) @@ -378,11 +901,14 @@ pub(crate) async fn execute_refresh_column_async( let execution = execute_refresh_column_with_source(&table, &column).await?; table.bump_freshness(); Ok(crate::function::RefreshColumnResult { + error_groups: Vec::new(), + error_groups_truncated: false, rows_assigned: execution.result.rows_filled, rows_failed: 0, rows_remaining: 0, source_version: execution.source_version, published_version: execution.published_version, + plan: None, }) }))) } @@ -2315,3 +2841,47 @@ mod tests { assert_eq!(payloads.value(0), payload); } } + +#[cfg(test)] +mod resource_validation_tests { + use super::{FunctionRefreshPlanningConfig, FunctionRefreshPodResources, RefreshColumnOptions}; + + #[test] + fn independent_totals_preserve_placement_and_pod_validation() { + assert!( + RefreshColumnOptions::default() + .total_cpu_millis(1000) + .validate() + .is_ok() + ); + assert!( + RefreshColumnOptions::default() + .total_gpu_count(0) + .validate() + .is_ok() + ); + assert!( + RefreshColumnOptions::default() + .gpu_class("H100:2") + .validate() + .is_err() + ); + assert!( + RefreshColumnOptions::default() + .supervisor_resources(FunctionRefreshPodResources::new(0, 1024, 1024)) + .validate() + .is_err() + ); + assert!( + RefreshColumnOptions::default() + .planning_workers(FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1000, 1024, 1024), + 0, + 1, + 1 + )) + .validate() + .is_err() + ); + } +} diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index db4d6b91f..ab872c7fc 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -166,7 +166,9 @@ pub(crate) async fn execute_declare( .into(), }); } - let transform = computed_columns::declare(table.schema().await?, columns)?; + let session = table.dataset.get().await?.session(); + let transform = + computed_columns::declare(table.schema().await?, columns, session.datafusion_session())?; let NewColumnTransform::AllNulls(schema) = transform else { unreachable!("declarations are all-null") }; @@ -307,7 +309,11 @@ pub(crate) async fn execute_alter_columns( .filter(|alteration| alteration.rename.is_some() || alteration.data_type.is_some()) .map(|alteration| alteration.path.as_str()) .collect::>(); - computed_columns::ensure_not_an_input(&schema, &rebinding)?; + computed_columns::ensure_not_an_input( + &schema, + &rebinding, + dataset.session().datafusion_session(), + )?; let retyped = alterations .iter() .filter(|alteration| alteration.data_type.is_some()) @@ -344,7 +350,12 @@ pub(crate) async fn execute_drop_columns( let dropped = names.iter().map(String::as_str).collect::>(); ensure_not_embedding_column(&schema, "drop", dropped.iter().copied())?; computed_columns::ensure_not_bound_by(&unbinding.retained, "schema evolution", &dropped)?; - computed_columns::ensure_not_an_input_of(&schema, &dropped, &dropped)?; + computed_columns::ensure_not_an_input_of( + &schema, + &dropped, + &dropped, + dataset.session().datafusion_session(), + )?; if !unbinding.is_noop() { // The retirement commits before the projection, so the whole diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index aa325cd7c..10895aa69 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -26,6 +26,7 @@ pub struct UpdateBuilder { parent: Arc, pub(crate) filter: Option, pub(crate) columns: Vec<(String, String)>, + pub(crate) retries: Option, } impl UpdateBuilder { @@ -34,9 +35,17 @@ impl UpdateBuilder { parent, filter: None, columns: Vec::new(), + retries: None, } } + /// Override the remote retry budget for this call. `0` disables retries. + /// Ambiguous write results are never replayed. Ignored by embedded tables. + pub fn retries(mut self, retries: u8) -> Self { + self.retries = Some(retries); + self + } + /// Limits the update operation to rows matching the given filter /// /// If a row does not match the filter then it will be left unchanged. @@ -94,11 +103,6 @@ pub(crate) async fn execute_update( // 1. Snapshot the current dataset let dataset = table.dataset.get().await?; crate::materialized_view::ensure_not_a_view(&table.name, &dataset.schema().metadata, "update")?; - super::computed_columns::ensure_not_function_bound( - &arrow_schema::Schema::from(dataset.schema()), - "update", - update.columns.iter().map(|(name, _)| name.as_str()), - )?; super::computed_columns::ensure_not_written( &arrow_schema::Schema::from(dataset.schema()), update.columns.iter().map(|(name, _)| name.as_str()), @@ -113,6 +117,11 @@ pub(crate) async fn execute_update( } // 4. Apply the columns (SET clause) + let written_columns = update + .columns + .iter() + .map(|(column, _)| column.clone()) + .collect::>(); for (column, value) in update.columns { builder = builder.set(column, &value)?; } @@ -120,13 +129,26 @@ pub(crate) async fn execute_update( // 5. Execute the operation (Write new files) let operation = builder.build()?; let res = operation.execute().await?; + let mut new_dataset = res.new_dataset.as_ref().clone(); + if res.rows_updated > 0 + && let Err(error) = super::freshness::preserve_function_freshness( + &mut new_dataset, + super::freshness::FunctionWrite::Update { + columns: &written_columns, + }, + ) + .await + { + log::warn!("update committed but Function freshness could not be preserved: {error}"); + } // 6. Update the table's view of the latest version - table.dataset.update(res.new_dataset.as_ref().clone()); + let version = new_dataset.version().version; + table.dataset.update(new_dataset); Ok(UpdateResult { rows_updated: res.rows_updated, - version: res.new_dataset.version().version, + version, }) } @@ -447,26 +469,38 @@ mod tests { assert_eq!(0, tbl.count_rows(Some("i == 0".to_string())).await.unwrap()); } - /// A Function binding protects only the columns it reads or writes; any - /// other column updates as on a plain table. #[tokio::test] - async fn update_on_a_function_table_refuses_only_bound_columns() { + async fn update_allows_function_inputs_but_protects_outputs() { let table = crate::table::computed_columns::test_support::bound_table().await; - let result = table.update().column("spare", "7").execute().await.unwrap(); + let result = table + .update() + .column("title", "'changed'") + .execute() + .await + .unwrap(); assert_eq!(result.rows_updated, 1); - for column in ["title", "search_text"] { + assert_eq!( + table + .count_rows(Some("title = 'changed' AND search_text = 'a b'".into())) + .await + .unwrap(), + 1 + ); + for column in ["search_text", "search_token_count"] { + let version = table.version().await.unwrap(); let err = table .update() - .column(column, "'x'") + .column("title", "'must not commit'") + .column(column, "NULL") .execute() .await .unwrap_err(); assert!( matches!(&err, crate::Error::InvalidInput { message } - if message.contains(&format!("update of '{column}'")) - && message.contains("a Function binding reads or writes it")), + if message.contains("is computed") && message.contains("cannot be written directly")), "{column}: {err:?}" ); + assert_eq!(table.version().await.unwrap(), version); } } } diff --git a/rust/lancedb/src/table/write_progress.rs b/rust/lancedb/src/table/write_progress.rs index 191c3284d..efea4586c 100644 --- a/rust/lancedb/src/table/write_progress.rs +++ b/rust/lancedb/src/table/write_progress.rs @@ -6,7 +6,7 @@ //! You can add a callback to process progress in [`crate::table::AddDataBuilder::progress`]. //! [`WriteProgress`] is the struct passed to the callback. -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -30,12 +30,21 @@ impl WriteProgress { self.elapsed } - /// Number of rows written so far. + /// Number of rows processed by the writer. + /// + /// Remote multipart writes count rows in acknowledged IPC parts, starting + /// at zero and counting retransmissions once. Other writers report rows + /// processed by the input scan. Neither indicates a successful commit. pub fn output_rows(&self) -> usize { self.output_rows } - /// Number of bytes written so far. + /// Number of bytes processed by the writer. + /// + /// Remote multipart writes report acknowledged IPC part bytes, starting at + /// zero. Retransmitted parts are counted once. Other writers report their + /// encoded bytes when available, otherwise the scanned Arrow memory size. + /// This does not indicate that the write has been committed. pub fn output_bytes(&self) -> usize { self.output_bytes } @@ -94,6 +103,8 @@ pub(crate) struct WriteProgressTracker { /// Wire bytes tracked separately by the insert layer. When set (> 0), /// this takes precedence over the in-memory bytes from `rows_and_bytes`. wire_bytes: AtomicUsize, + /// Multipart progress excludes input scanning and counts only acknowledged parts. + acknowledged_parts: AtomicBool, active_tasks: Arc, total_tasks: AtomicUsize, start: Instant, @@ -107,6 +118,7 @@ impl WriteProgressTracker { Self { rows_and_bytes: std::sync::Mutex::new((0, 0)), wire_bytes: AtomicUsize::new(0), + acknowledged_parts: AtomicBool::new(false), active_tasks: Arc::new(AtomicUsize::new(0)), total_tasks: AtomicUsize::new(1), start: Instant::now(), @@ -115,6 +127,11 @@ impl WriteProgressTracker { } } + /// Select acknowledged rows and wire bytes before polling the input plan. + pub fn use_acknowledged_parts(&self) { + self.acknowledged_parts.store(true, Ordering::Relaxed); + } + /// Set the total number of parallel write tasks (the write parallelism). pub fn set_total_tasks(&self, n: usize) { self.total_tasks.store(n, Ordering::Relaxed); @@ -130,13 +147,29 @@ impl WriteProgressTracker { pub fn record_batch(&self, rows: usize, bytes: usize) { // Lock order: callback first, then rows_and_bytes. This is the only // order used anywhere, so deadlocks cannot occur. + let mut cb = self.callback.lock().unwrap_or_else(|e| e.into_inner()); + let mut guard = self + .rows_and_bytes + .lock() + .unwrap_or_else(|e| e.into_inner()); + if !self.acknowledged_parts.load(Ordering::Relaxed) { + guard.0 += rows; + guard.1 += bytes; + } + let progress = self.snapshot(guard.0, guard.1, false); + drop(guard); + cb(&progress); + } + + /// Record one successfully staged part, after any retries have finished. + pub fn record_acknowledged_part(&self, rows: usize, bytes: usize) { let mut cb = self.callback.lock().unwrap_or_else(|e| e.into_inner()); let mut guard = self .rows_and_bytes .lock() .unwrap_or_else(|e| e.into_inner()); guard.0 += rows; - guard.1 += bytes; + self.wire_bytes.fetch_add(bytes, Ordering::Relaxed); let progress = self.snapshot(guard.0, guard.1, false); drop(guard); cb(&progress); @@ -179,7 +212,11 @@ impl WriteProgressTracker { let wire = self.wire_bytes.load(Ordering::Relaxed); // Prefer wire bytes (actual I/O size) when the insert layer is // tracking them; fall back to in-memory Arrow size otherwise. - let output_bytes = if wire > 0 { wire } else { in_memory_bytes }; + let output_bytes = if self.acknowledged_parts.load(Ordering::Relaxed) || wire > 0 { + wire + } else { + in_memory_bytes + }; WriteProgress { elapsed: self.start.elapsed(), output_rows: rows, diff --git a/rust/lancedb/src/test_fixtures.rs b/rust/lancedb/src/test_fixtures.rs new file mode 100644 index 000000000..71ea8c6e8 --- /dev/null +++ b/rust/lancedb/src/test_fixtures.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Shared golden data for downstream compatibility tests. +//! +//! Enable the `test-fixtures` feature to access these fixtures from another crate. + +/// The version 1 Function Arrow type golden as UTF-8 JSON. +/// +/// Contains supported declaration spellings, their canonical JSON Arrow types, +/// and declarations that must be rejected. The contents match the golden used by +/// LanceDB's Rust and Python tests; parsing is left to the consumer. +/// +/// ``` +/// let golden: serde_json::Value = +/// serde_json::from_str(lancedb::test_fixtures::FUNCTION_ARROW_TYPES_JSON).unwrap(); +/// assert!(golden["valid"].is_array()); +/// assert!(golden["invalid"].is_array()); +/// ``` +pub const FUNCTION_ARROW_TYPES_JSON: &str = + include_str!("../tests/fixtures/first_class_functions/v1/arrow_types.json"); diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs index 560fe858a..528457153 100644 --- a/rust/lancedb/src/utils/mod.rs +++ b/rust/lancedb/src/utils/mod.rs @@ -539,6 +539,7 @@ pub fn supported_btree_data_type(dtype: &DataType) -> bool { dtype, DataType::Boolean | DataType::Utf8 + | DataType::LargeUtf8 | DataType::Time32(_) | DataType::Time64(_) | DataType::Date32 @@ -680,6 +681,22 @@ impl TimeoutStream { Box::pin(Self::new(inner, timeout)) } + /// Like [`Self::new`], but the stream expires at `deadline` rather than + /// `timeout` after its first poll. `timeout` is only used in the error. + pub fn with_deadline( + inner: SendableRecordBatchStream, + timeout: std::time::Duration, + deadline: tokio::time::Instant, + ) -> Self { + Self { + inner, + state: TimeoutState::Started { + deadline: Box::pin(tokio::time::sleep_until(deadline)), + timeout, + }, + } + } + fn timeout_error(timeout: &std::time::Duration) -> DataFusionError { DataFusionError::Execution(format!("Query timeout after {} ms", timeout.as_millis())) } diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index 0a4240038..6cb18757d 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -2085,3 +2085,377 @@ async fn blob_layout_rte_merge_normalizes_before_writing() -> Result<()> { } Ok(()) } + +/// One-row blob v2 batch carrying an external URI with an explicit byte range. +fn range_uri_batch( + ids: &[i64], + uris: &[&str], + positions: &[Option], + sizes: &[Option], +) -> RecordBatch { + let image_field = lancedb::blob("image", true); + let DataType::Struct(children) = image_field.data_type().clone() else { + unreachable!("blob field is a struct"); + }; + let values = StructArray::new( + children, + vec![ + new_null_array(&DataType::LargeBinary, ids.len()), + Arc::new(StringArray::from_iter_values(uris.iter().copied())), + Arc::new(UInt64Array::from(positions.to_vec())), + Arc::new(UInt64Array::from(sizes.to_vec())), + ], + None, + ); + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + image_field, + ])), + vec![Arc::new(Int64Array::from(ids.to_vec())), Arc::new(values)], + ) + .unwrap() +} + +fn wide_blob_table_schema() -> Arc { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + lancedb::blob("image", true), + ])) +} + +fn local_base(id: u32, path: String) -> BasePath { + BasePath { + id, + name: Some(format!("base{id}")), + path, + is_dataset_root: false, + } +} + +fn write_local_payload(dir: &std::path::Path, name: &str, payload: &[u8]) -> (String, String) { + let path = dir.join(name); + std::fs::write(&path, payload).unwrap(); + ( + url::Url::from_file_path(&path).unwrap().to_string(), + url::Url::from_directory_path(dir).unwrap().to_string(), + ) +} + +/// A create with data and `initial_bases` must commit once. Registering the +/// base in a later commit, or creating empty first, would bump the version and +/// leave an intermediate table without its storage. +#[tokio::test] +async fn create_table_with_data_registers_initial_base_atomically() -> Result<()> { + let tmp = tempdir().unwrap(); + let payload = b"0123456789abcdef"; + let (clip_uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", payload); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + + let table = db + .create_table( + "videos", + range_uri_batch(&[1], &[clip_uri.as_str()], &[Some(0)], &[Some(6)]), + ) + .initial_bases(vec![local_base(1, base_uri.clone())]) + .execute() + .await?; + + assert_eq!(table.version().await?, 1); + let manifest = table.as_native().unwrap().manifest().await?; + let registered = manifest.base_paths.get(&1).expect("base 1 registered"); + assert_eq!(registered.path, base_uri); + assert!(!registered.is_dataset_root); + + let reopened = db.open_table("videos").execute().await?; + let ids = collect_row_ids(&reopened).await?; + let files = reopened.fetch_blob_files("image", &ids).await?; + let file = files[0].as_ref().unwrap(); + assert_eq!(file.uri(), Some("clip.mp4")); + assert_eq!(file.position(), Some(0)); + assert_eq!(file.size(), 6); + let bytes = reopened.fetch_blobs("image", &ids).await?; + assert_eq!(bytes.value(0), &payload[..6]); + Ok(()) +} + +#[tokio::test] +async fn create_table_with_data_accepts_unregistered_uri_only_with_opt_in() -> Result<()> { + let tmp = tempdir().unwrap(); + let payload = b"0123456789abcdef"; + let (clip_uri, _) = write_local_payload(tmp.path(), "clip.mp4", payload); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + let batch = range_uri_batch(&[1], &[clip_uri.as_str()], &[Some(0)], &[Some(6)]); + + let err = db + .create_table("videos", batch.clone()) + .execute() + .await + .unwrap_err(); + assert!( + err.to_string() + .contains("allow_external_blob_outside_bases"), + "got: {err}" + ); + assert!(db.open_table("videos").execute().await.is_err()); + + let table = db + .create_table("videos", batch) + .allow_external_blob_outside_bases(true) + .execute() + .await?; + assert_eq!(table.version().await?, 1); + let reopened = db.open_table("videos").execute().await?; + let ids = collect_row_ids(&reopened).await?; + let bytes = reopened.fetch_blobs("image", &ids).await?; + assert_eq!(bytes.value(0), &payload[..6]); + Ok(()) +} + +/// An explicit `id=0` asks Lance to assign the base ID in the create commit. +#[tokio::test] +async fn create_empty_table_with_initial_bases_bootstraps_base_with_auto_id() -> Result<()> { + let tmp = tempdir().unwrap(); + let payload = b"payload-bytes"; + let (clip_uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", payload); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + + let table = db + .create_empty_table("videos", wide_blob_table_schema()) + .initial_bases(vec![local_base(0, base_uri.clone())]) + .execute() + .await?; + let manifest = table.as_native().unwrap().manifest().await?; + let registered = manifest + .base_paths + .values() + .find(|base| base.path == base_uri) + .expect("base registered with the empty create"); + assert!(registered.id > 0); + assert!(!registered.is_dataset_root); + + table + .add(range_uri_batch( + &[1], + &[clip_uri.as_str()], + &[None], + &[None], + )) + .execute() + .await?; + let reopened = db.open_table("videos").execute().await?; + let ids = collect_row_ids(&reopened).await?; + let files = reopened.fetch_blob_files("image", &ids).await?; + assert_eq!(files[0].as_ref().unwrap().uri(), Some("clip.mp4")); + let bytes = reopened.fetch_blobs("image", &ids).await?; + assert_eq!(bytes.value(0), payload); + Ok(()) +} + +/// Scoped `base_.` options travel with the table and keep each base +/// readable after reopen. Unscoped options stay shared defaults. +#[tokio::test] +async fn created_bases_read_back_with_scoped_storage_options() -> Result<()> { + let tmp = tempdir().unwrap(); + let payload_a = b"base-a-payload"; + let payload_b = b"base-b-payload"; + let dir_a = tmp.path().join("base-a"); + let dir_b = tmp.path().join("base-b"); + std::fs::create_dir_all(&dir_a).unwrap(); + std::fs::create_dir_all(&dir_b).unwrap(); + let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a); + let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b); + let storage_options = [ + ("timeout", "7s"), + ("base_1.region", "base-one"), + ("base_2.region", "base-two"), + ]; + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + + let table = db + .create_table( + "videos", + range_uri_batch( + &[1, 2], + &[uri_a.as_str(), uri_b.as_str()], + &[None, None], + &[None, None], + ), + ) + .initial_bases(vec![local_base(1, base_a), local_base(2, base_b)]) + .storage_options(storage_options) + .execute() + .await?; + assert_eq!(table.version().await?, 1); + + let reopened = db + .open_table("videos") + .storage_options(storage_options) + .execute() + .await?; + let ids = collect_row_ids(&reopened).await?; + let files = reopened.fetch_blob_files("image", &ids).await?; + assert_eq!(files[0].as_ref().unwrap().uri(), Some("clip.mp4")); + assert_eq!(files[1].as_ref().unwrap().uri(), Some("clip.mp4")); + let bytes = reopened.fetch_blobs("image", &ids).await?; + assert_eq!(bytes.value(0), payload_a); + assert_eq!(bytes.value(1), payload_b); + Ok(()) +} + +/// Scoped `base_.` options belong to exactly one base. An option +/// that only base 1 can reject must not change what base 2 reads on reopen. +#[tokio::test] +async fn scoped_storage_options_do_not_leak_between_bases_on_reopen() -> Result<()> { + let tmp = tempdir().unwrap(); + let payload_a = b"base-a-payload"; + let payload_b = b"base-b-payload"; + let dir_a = tmp.path().join("base-a"); + let dir_b = tmp.path().join("base-b"); + std::fs::create_dir_all(&dir_a).unwrap(); + std::fs::create_dir_all(&dir_b).unwrap(); + let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a); + let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + + db.create_table( + "videos", + range_uri_batch( + &[1, 2], + &[uri_a.as_str(), uri_b.as_str()], + &[None, None], + &[None, None], + ), + ) + .initial_bases(vec![local_base(1, base_a), local_base(2, base_b)]) + .execute() + .await?; + + let reopened = db + .open_table("videos") + .storage_options([("base_1.scheduler_error_mode", "invalid")]) + .execute() + .await?; + let pairs = sorted_id_rowid(&reopened).await?; + let row_for = |id: i64| { + pairs + .iter() + .find(|(row_id, _)| *row_id == id) + .map(|(_, row_id)| *row_id) + .expect("row present") + }; + + let err = reopened + .fetch_blobs("image", &[row_for(1)]) + .await + .unwrap_err(); + assert!( + err.to_string().contains("scheduler_error_mode"), + "base 1 should carry its scoped option, got: {err}" + ); + let bytes = reopened.fetch_blobs("image", &[row_for(2)]).await?; + assert_eq!(bytes.value(0), payload_b); + Ok(()) +} + +fn namespace_properties(root: &std::path::Path) -> std::collections::HashMap { + std::collections::HashMap::from([("root".to_string(), root.to_str().unwrap().to_string())]) +} + +/// Connection-level storage options must be merged under the request's +/// storage options on the namespace create path. Replacing the request +/// accessor drops `base_.` settings and silently accepts options the +/// selected base cannot use. +#[tokio::test] +async fn namespace_create_keeps_caller_scoped_storage_options() -> Result<()> { + let tmp = tempdir().unwrap(); + let (uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", b"namespace-scoped"); + let db = connect_namespace("dir", namespace_properties(&tmp.path().join("ns"))) + .storage_options([("timeout", "7s")]) + .execute() + .await?; + + let err = db + .create_table( + "videos", + range_uri_batch(&[1], &[uri.as_str()], &[None], &[None]), + ) + .initial_bases(vec![local_base(1, base_uri)]) + .storage_option("base_1.scheduler_error_mode", "invalid") + .execute() + .await + .unwrap_err(); + assert!( + err.to_string().contains("scheduler_error_mode"), + "request-scoped option was dropped, got: {err}" + ); + Ok(()) +} + +/// A namespace reopen keeps scoped options attached to their own base: base +/// 1's invalid option fails its read while base 2 still returns exact bytes. +#[tokio::test] +async fn namespace_reopen_applies_scoped_options_to_their_own_base() -> Result<()> { + let tmp = tempdir().unwrap(); + let payload_a = b"namespace-base-a"; + let payload_b = b"namespace-base-b"; + let dir_a = tmp.path().join("base-a"); + let dir_b = tmp.path().join("base-b"); + std::fs::create_dir_all(&dir_a).unwrap(); + std::fs::create_dir_all(&dir_b).unwrap(); + let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a); + let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b); + let db = connect_namespace("dir", namespace_properties(&tmp.path().join("ns"))) + .storage_options([("timeout", "7s")]) + .execute() + .await?; + + db.create_table( + "videos", + range_uri_batch( + &[1, 2], + &[uri_a.as_str(), uri_b.as_str()], + &[None, None], + &[None, None], + ), + ) + .initial_bases(vec![local_base(1, base_a), local_base(2, base_b)]) + .execute() + .await?; + + let reopened = db + .open_table("videos") + .storage_options([("base_1.scheduler_error_mode", "invalid")]) + .execute() + .await?; + let pairs = sorted_id_rowid(&reopened).await?; + let row_for = |id: i64| { + pairs + .iter() + .find(|(row_id, _)| *row_id == id) + .map(|(_, row_id)| *row_id) + .expect("row present") + }; + + let err = reopened + .fetch_blobs("image", &[row_for(1)]) + .await + .unwrap_err(); + assert!( + err.to_string().contains("scheduler_error_mode"), + "base 1 should carry its scoped option, got: {err}" + ); + let bytes = reopened.fetch_blobs("image", &[row_for(2)]).await?; + assert_eq!(bytes.value(0), payload_b); + Ok(()) +} diff --git a/rust/lancedb/tests/datafusion_blob_schema.rs b/rust/lancedb/tests/datafusion_blob_schema.rs index d51c182f6..5af3122ab 100644 --- a/rust/lancedb/tests/datafusion_blob_schema.rs +++ b/rust/lancedb/tests/datafusion_blob_schema.rs @@ -571,66 +571,701 @@ async fn legacy_blob_write_mode_rejects_descriptor_scans_and_keeps_scalar_scans( } #[tokio::test] -async fn copying_non_null_descriptors_between_tables_commits_no_rows() { +async fn copying_descriptors_materializes_payloads_and_preserves_snapshot() { + use std::collections::HashMap; + use std::num::NonZeroUsize; + + use lancedb::blob::{BlobOptions, blob_with_options}; + use lancedb::table::OptimizeAction; + + for managed in [false, true] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let payload = blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(8), + dedicated_size_threshold: NonZeroUsize::new(32), + }, + ); + let values: Vec> = vec![ + Some(b"hi"), + Some(&[2; 16]), + Some(&[3; 64]), + None, + Some(b""), + Some(b"skip"), + ]; + let schema = Arc::new(Schema::new_with_metadata( + vec![Field::new("id", DataType::Int64, false), payload], + HashMap::from([("lance.blob.managed".into(), managed.to_string())]), + )); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2, 3, 4, 5, 6])), + blob_inputs(values.clone()), + ], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_batch_size(2) + .with_target_partitions(2), + ); + register(&ctx, &source, BlobSchema::Read).await; + // Descriptor queries and SELECT * retain their original read schema. + let sizes = sql(&ctx, "SELECT payload.size FROM docs ORDER BY id").await; + assert_eq!( + sizes + .column(0) + .as_primitive::() + .value(2), + 64 + ); + assert_eq!(sql(&ctx, "SELECT * FROM docs").await.num_columns(), 2); + let kinds = sql(&ctx, "SELECT payload.kind FROM docs ORDER BY id").await; + let kinds = kinds + .column(0) + .as_primitive::(); + if !managed { + assert_eq!( + kinds.value(0), + lance_core::datatypes::BlobKind::Inline as u8 + ); + assert_eq!( + kinds.value(1), + lance_core::datatypes::BlobKind::Packed as u8 + ); + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Dedicated as u8 + ); + } else { + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Managed as u8 + ); + } + let (_destination_tmp, destination) = empty_table(vec![ + blob("copied", true), + Field::new("id", DataType::Int64, false), + ]) + .await; + let writer = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode); + ctx.register_table("destination", Arc::new(writer)).unwrap(); + let plan = ctx.sql("INSERT INTO destination (id, copied) SELECT id + 10, payload AS copied FROM docs WHERE id > 0 AND (payload.size IS NULL OR payload.size < 100) ORDER BY id DESC LIMIT 5 OFFSET 1") + .await.unwrap().create_physical_plan().await.unwrap(); + // A live-table change after planning must not change the source + // version used to decode the descriptors in this insert. + source.delete("id = 1").await.unwrap(); + datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(destination.count_rows(None).await.unwrap(), 5); + source.optimize(OptimizeAction::All).await.unwrap(); + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let reader = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID]) + .unwrap(); + ctx.register_table("copied_rows", Arc::new(reader)).unwrap(); + let ids = sql(&ctx, "SELECT _rowid FROM copied_rows ORDER BY id").await; + let ids = ids + .column(0) + .as_primitive::() + .values(); + assert_eq!( + destination.fetch_blobs("copied", ids).await.unwrap(), + LargeBinaryArray::from(values[..5].to_vec()) + ); + } + } +} + +#[tokio::test] +async fn copying_nested_descriptors_preserves_parent_nulls_and_field_identity() { + use arrow_array::Int32Array; + use lancedb::blob::{BlobOptions, blob_with_options}; + + for difference in ["metadata", "order", "scalar"] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let children = vec![ + Arc::new(Field::new("note", DataType::Utf8, true)), + Arc::new(Field::new("rank", DataType::Int32, true)), + Arc::new(blob_with_options( + "clip", + true, + BlobOptions { + inline_size_threshold: Some(8), + ..Default::default() + }, + )), + ]; + let extra_field = Field::new("extra", DataType::Struct(children.clone().into()), true); + let extra = StructArray::new( + children.into(), + vec![ + Arc::new(StringArray::from(vec![ + Some("a"), + Some("hidden"), + Some("c"), + ])), + Arc::new(Int32Array::from(vec![1, 2, 3])), + blob_inputs(vec![Some(b"hi"), Some(b"hidden"), Some(b"")]), + ], + Some(NullBuffer::from(vec![true, false, true])), + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + extra_field, + ])), + vec![Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let mut target_children = vec![ + Field::new("note", DataType::Utf8, true), + Field::new( + "rank", + if difference == "scalar" { + DataType::Int64 + } else { + DataType::Int32 + }, + true, + ), + blob("clip", true), + ]; + if difference == "order" { + target_children.swap(0, 2); + } + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + Field::new("extra", DataType::Struct(target_children.into()), true), + blob("flattened", true), + ]) + .await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + for expression in [ + "CASE WHEN id = 1 THEN extra ELSE NULL END", + "named_struct('note', extra.note, 'rank', extra.rank, 'clip', extra.clip)", + ] { + let query = format!( + "INSERT INTO destination SELECT id, {expression} AS extra, extra.clip AS flattened FROM docs" + ); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{difference}, {mode:?}: {error}" + ); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } + sql(&ctx, "INSERT INTO destination SELECT id, extra, extra.clip AS flattened FROM docs ORDER BY id DESC").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let ids = row_ids(&ctx, &destination).await; + let expected = + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, Some(b"".as_slice())]); + assert_eq!( + destination.fetch_blobs("extra.clip", &ids).await.unwrap(), + expected, + "{difference}, {mode:?}" + ); + assert_eq!( + destination.fetch_blobs("flattened", &ids).await.unwrap(), + expected + ); + let nested = sql(&ctx, "SELECT extra FROM read_docs ORDER BY id").await; + let extra = nested.column(0).as_struct(); + assert!(extra.is_null(1)); + assert_eq!( + extra + .column_by_name("note") + .unwrap() + .as_string::() + .value(2), + "c" + ); + let rank = extra.column_by_name("rank").unwrap(); + if difference == "scalar" { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } else { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } + } + } +} + +#[tokio::test] +async fn ordinary_descriptor_shaped_structs_remain_plain_data() { + let fields = vec![ + Field::new("id", DataType::Int64, false), + Field::new( + "raw", + DataType::Struct( + vec![ + Field::new("kind", DataType::UInt8, true), + Field::new("position", DataType::UInt64, true), + Field::new("size", DataType::UInt64, true), + Field::new("blob_id", DataType::UInt32, true), + Field::new("blob_uri", DataType::Utf8, true), + ] + .into(), + ), + true, + ), + ]; + let (source_tmp, source) = empty_table(fields.clone()).await; + let (_destination_tmp, destination) = empty_table(fields).await; + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + sql(&ctx, "INSERT INTO docs VALUES (1, named_struct('kind', 1, 'position', 2, 'size', 3, 'blob_id', 4, 'blob_uri', 'plain data'))").await; + let expected = sql(&ctx, "SELECT * FROM docs").await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + sql(&ctx, "INSERT INTO destination SELECT * FROM docs").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let actual = sql(&ctx, "SELECT * FROM destination").await; + assert_eq!(actual.columns(), expected.columns()); +} + +#[tokio::test] +async fn ambiguous_descriptor_sources_fail_during_planning_without_writing() { let (_tmp, source) = empty_table(vec![ Field::new("id", DataType::Int64, false), blob("payload", true), ]) .await; - let ctx = SessionContext::new_with_config( - SessionConfig::new() - .with_batch_size(1) - .with_target_partitions(1), - ); + let ctx = SessionContext::new(); register(&ctx, &source, BlobSchema::Write).await; sql( &ctx, "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", ) .await; - sql(&ctx, "INSERT INTO docs VALUES (2, NULL)").await; register(&ctx, &source, BlobSchema::Read).await; - let (_dest_tmp, destination) = empty_table( - source - .schema() - .await - .unwrap() - .fields() - .iter() - .map(|f| f.as_ref().clone()) - .collect(), - ) + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) .await; let writer = BaseTableAdapter::try_new(destination.base_table().clone()) .await - .unwrap() - .with_blob_schema(BlobSchema::Write); + .unwrap(); ctx.register_table("destination", Arc::new(writer)).unwrap(); let version = destination.version().await.unwrap(); - // The null row is valid and reaches the writer before the non-null - // descriptor. Even if it is written to a fragment, it must not be committed. - let plan = ctx - .sql("INSERT INTO destination SELECT id, payload FROM docs ORDER BY id DESC") + for select in [ + "SELECT a.id, a.payload FROM docs a JOIN docs b ON a.id = b.id", + "SELECT id, payload FROM docs UNION ALL SELECT id, payload FROM docs", + "SELECT id, payload FROM docs GROUP BY id, payload", + "SELECT id, CASE WHEN id = 1 THEN payload ELSE NULL END AS payload FROM docs", + ] { + let query = format!("INSERT INTO destination {select}"); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{query}: {error}" + ); + } + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + assert_eq!(destination.version().await.unwrap(), version); +} + +#[tokio::test] +async fn external_descriptor_copy_obeys_destination_bases_and_preserves_ranges() { + use lance::dataset::WriteParams; + use lance_core::datatypes::BlobKind; + use lance_table::format::BasePath; + use lancedb::table::WriteOptions; + + let external_tmp = tempdir().unwrap(); + let payload = b"0123456789abcdef"; + let path = external_tmp.path().join("payload.bin"); + std::fs::write(&path, payload).unwrap(); + let uri = url::Url::from_file_path(&path).unwrap().to_string(); + let base_uri = url::Url::from_directory_path(external_tmp.path()) + .unwrap() + .to_string(); + let base = |id| BasePath { + id, + name: Some("external".into()), + path: base_uri.clone(), + is_dataset_root: false, + }; + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ])); + let DataType::Struct(children) = schema.field(1).data_type().clone() else { + unreachable!() + }; + let input = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + Arc::new(StructArray::new( + children, + vec![ + Arc::new(LargeBinaryArray::from(vec![ + None, + Some(b"inline".as_slice()), + ])), + Arc::new(StringArray::from(vec![Some(uri.as_str()), None])), + Arc::new(UInt64Array::from(vec![Some(4), None])), + Arc::new(UInt64Array::from(vec![Some(6), None])), + ], + None, + )), + ], + ) + .unwrap(); + for source_registered in [false, true] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let source = db + .create_empty_table("source", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: source_registered.then(|| vec![base(7)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + source + .add(input.clone()) + .allow_external_blob_outside_bases(!source_registered) + .execute() + .await + .unwrap(); + for mode in [BlobSchema::Read, BlobSchema::Write] { + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let descriptor = sql(&ctx, "SELECT payload.blob_id FROM docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + if source_registered { 7 } else { 0 } + ); + for authorized in [false, true] { + let destination_tmp = tempdir().unwrap(); + let destination_db = connect(destination_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let destination = destination_db + .create_empty_table("destination", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: authorized.then(|| vec![base(11)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + ctx.deregister_table("destination").unwrap(); + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let result = ctx + .sql("INSERT INTO destination SELECT * FROM docs ORDER BY id") + .await + .unwrap() + .collect() + .await; + if !authorized { + let error = result.unwrap_err().to_string(); + assert!( + error.contains("outside registered external bases"), + "{error}" + ); + let reopened = destination_db + .open_table("destination") + .execute() + .await + .unwrap(); + assert_eq!(reopened.version().await.unwrap(), version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); + // A logical URI input has the same destination authorization boundary. + ctx.register_table( + "logical_target", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write), + ), + ) + .unwrap(); + let error = ctx.sql(&format!("INSERT INTO logical_target SELECT 3, named_struct('data', NULL, 'uri', '{uri}')")).await.unwrap().collect().await.unwrap_err().to_string(); + assert!( + error.contains("allow_external_blob_outside_bases"), + "{error}" + ); + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } else { + result.unwrap(); + let ids = row_ids(&ctx, &destination).await; + let descriptor = sql(&ctx, "SELECT payload.kind, payload.blob_id, payload.blob_uri, payload.position, payload.size FROM read_docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + BlobKind::External as u8 + ); + assert_eq!( + descriptor + .column(1) + .as_primitive::() + .value(0), + 11 + ); + assert_eq!( + descriptor.column(2).as_string::().value(0), + "payload.bin" + ); + assert_eq!( + descriptor + .column(3) + .as_primitive::() + .value(0), + 4 + ); + assert_eq!( + descriptor + .column(4) + .as_primitive::() + .value(0), + 6 + ); + assert_eq!( + destination.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![ + Some(&payload[4..10]), + Some(b"inline".as_slice()) + ]) + ); + let files = destination.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[0].as_ref().unwrap(); + assert_eq!(file.uri(), Some("payload.bin")); + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let registered = &dataset.manifest().base_paths[&11]; + let resolved = + url::Url::parse(&format!("{}/", registered.path.trim_end_matches('/'))) + .unwrap() + .join(file.uri().unwrap()) + .unwrap(); + assert_eq!(resolved.as_str(), uri); + assert_eq!(file.position(), Some(4)); + assert_eq!(file.size(), 6); + } + } + } + } +} + +#[tokio::test] +async fn source_payload_failure_after_written_partition_does_not_commit() { + use datafusion_physical_plan::{ + ExecutionPlanProperties, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + union::UnionExec, + }; + use futures::TryStreamExt; + use lancedb::blob::{BlobOptions, blob_with_options}; + use std::num::NonZeroUsize; + + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(0), + dedicated_size_threshold: NonZeroUsize::new(1), + }, + ), + ])); + let source = db + .create_table( + "docs", + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + blob_inputs(vec![Some(&[1; 64]), Some(&[2; 64])]), + ], + ) + .unwrap(), + ) + .execute() + .await + .unwrap(); + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_target_partitions(1) + .with_batch_size(1), + ); + register(&ctx, &source, BlobSchema::Read).await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + let first = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 1") .await .unwrap() .create_physical_plan() .await .unwrap(); - let error = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + let second = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 2") .await - .unwrap_err(); - assert!(error.to_string().contains("blob"), "{error}"); + .unwrap() + .create_physical_plan() + .await + .unwrap(); + assert_eq!(first.name(), "InsertExec"); + assert_eq!(second.name(), "InsertExec"); + // Combine already validated SQL inputs only to control partition scheduling: + // finish one real uncommitted write before faulting the next payload read. + let input = UnionExec::try_new(vec![ + first.children()[0].clone(), + second.children()[0].clone(), + ]) + .unwrap(); + assert_eq!(input.output_partitioning().partition_count(), 2); + let insert = first + .replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let batches: Vec = insert + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 1 + ); assert_eq!(destination.count_rows(None).await.unwrap(), 0); assert_eq!(destination.version().await.unwrap(), version); - sql( - &ctx, - "INSERT INTO destination SELECT id, payload FROM docs WHERE payload IS NULL", - ) - .await; - let ids = row_ids(&ctx, &destination).await; - assert_eq!(ids.len(), 1); - assert_eq!( - destination.fetch_blobs("payload", &ids).await.unwrap(), - LargeBinaryArray::from(vec![None::<&[u8]>]) + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let data_dir = _destination_tmp.path().join("docs.lance").join("data"); + assert!( + std::fs::read_dir(data_dir).unwrap().next().is_some(), + "first partition must have written a data file" ); + let ids = row_ids(&ctx, &source).await; + let files = source.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[1].as_ref().unwrap(); + assert_eq!( + file.kind(), + Some(lance_core::datatypes::BlobKind::Dedicated) + ); + let missing_path = std::path::Path::new("/").join(file.data_path().unwrap().as_ref()); + drop(files); + std::fs::remove_file(&missing_path).unwrap(); + let error = insert + .execute(1, ctx.task_ctx()) + .unwrap() + .try_collect::>() + .await + .unwrap_err() + .to_string(); + assert!( + error.contains(missing_path.file_name().unwrap().to_str().unwrap()), + "{error}" + ); + // Check both the live handle and an independently reopened manifest. + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + let reopened = lance::Dataset::open(dataset.uri()).await.unwrap(); + assert_eq!(reopened.version().version, version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); } diff --git a/rust/lancedb/tests/first_class_function_slice1.rs b/rust/lancedb/tests/first_class_function_slice1.rs index 86ccea1cc..878e74bb0 100644 --- a/rust/lancedb/tests/first_class_function_slice1.rs +++ b/rust/lancedb/tests/first_class_function_slice1.rs @@ -182,13 +182,17 @@ fn unknown_fields_and_discriminators_are_forward_decodable() { let version = FunctionVersion::from_json(&result.to_string()).expect("future remote value"); assert_eq!(version.image().descriptor["future_interface"]["version"], 2); assert_eq!(version.signature().output.kind, "future_output_shape"); - assert_eq!( - serde_json::from_str::( - &version.to_canonical_json().expect("canonical future value") - ) - .expect("canonical JSON")["image"]["descriptor"]["future_interface"], - serde_json::json!({"version": 2}) - ); + let canonical: Value = + serde_json::from_str(&version.to_canonical_json().expect("canonical future value")) + .expect("canonical JSON"); + + let mut expected: Value = + serde_json::from_str(fixture("remote_function_version.canonical.json").trim()) + .expect("canonical FunctionVersion fixture"); + expected["image"]["descriptor"]["future_interface"] = serde_json::json!({"version": 2}); + expected["signature"]["output"]["kind"] = Value::String("future_output_shape".to_string()); + assert_eq!(canonical, expected); + assert!(canonical.get("future_version_metadata").is_none()); } #[test] diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index 815ddcf08..10114cbad 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -71,6 +71,7 @@ fn execution_controls_match_shared_canonical_golden() { let value: Value = serde_json::from_str(&request.to_canonical_json().unwrap()).unwrap(); assert_eq!(value["batch_size"], 2); + assert_eq!(value["max_concurrency"], 4); assert_eq!(value["row_timeout_seconds"], 0.75); } @@ -80,6 +81,13 @@ fn execution_controls_require_their_positive_ranges() { for (field, value) in [ ("batch_size", Value::from(0)), ("batch_size", Value::from(4_294_967_296_u64)), + ("max_concurrency", Value::from(0)), + ("max_concurrency", Value::from(4_294_967_296_u64)), + ("max_concurrency", Value::from(-1)), + ("max_concurrency", Value::from(1.5)), + ("total_cpu_millis", Value::from(0)), + ("total_memory_bytes", Value::from(0)), + ("total_gpu_count", Value::from(4_294_967_296_u64)), ("row_timeout_seconds", Value::from(0)), ("row_timeout_seconds", Value::from(-0.25)), ] { @@ -107,9 +115,14 @@ fn execution_controls_are_validated_before_canonical_serialization() { request.batch_size = Some(0); let error = request.to_canonical_json().unwrap_err(); assert!(error.to_string().contains("batch_size"), "{error}"); + + let mut request = FunctionRegistrationRequest::from_json(&source).unwrap(); + request.max_concurrency = Some(0); + let error = request.to_canonical_json().unwrap_err(); + assert!(error.to_string().contains("max_concurrency"), "{error}"); } -/// The same shared golden as the Python suite builds from `@udf(secrets=...)` +/// The same shared golden as the Python suite builds from `@function(secrets=...)` /// plus `bind_secrets`, so both clients agree byte for byte on a bound request. #[test] fn secret_bound_registration_request_matches_shared_canonical_golden() { @@ -156,11 +169,15 @@ async fn local_function_catalog_operations_return_stable_not_supported() { .get_function("normalize_score", "1", &[]) .await .unwrap_err(); + let latest_lookup_error = connection + .get_function_latest("normalize_score", &[]) + .await + .unwrap_err(); let drop_error = connection .drop_function("normalize_score", "1", &[]) .await .unwrap_err(); - for error in [create_error, lookup_error, drop_error] { + for error in [create_error, lookup_error, latest_lookup_error, drop_error] { assert!(matches!( error, Error::NotSupported { message } diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json index 9ce9a289f..b5bdff2a8 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json @@ -1 +1 @@ -{"artifact":{"adapter":{"kind":"scalar_to_arrow_batch","version":1},"content":{"data":"ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK","encoding":"base64"},"digest":"sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f","entrypoint":"normalize_score","kind":"python_callable"},"batch_size":2,"name":"normalize_score","row_timeout_seconds":0.75,"runtime":{"env":{"MODE":"test"},"environment":{"kind":"pip","packages":["numpy>=2"]},"kind":"python","python_version":"3.12"},"signature":{"inputs":[{"arrow_type":"float64","name":"value","nullable":false}],"output":{"arrow_type":"float64","kind":"scalar","nullable":false}}} +{"artifact":{"adapter":{"kind":"scalar_to_arrow_batch","version":1},"content":{"data":"ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK","encoding":"base64"},"digest":"sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f","entrypoint":"normalize_score","kind":"python_callable"},"batch_size":2,"max_concurrency":4,"name":"normalize_score","row_timeout_seconds":0.75,"runtime":{"env":{"MODE":"test"},"environment":{"kind":"pip","packages":["numpy>=2"]},"kind":"python","python_version":"3.12"},"signature":{"inputs":[{"arrow_type":"float64","name":"value","nullable":false}],"output":{"arrow_type":"float64","kind":"scalar","nullable":false}}} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json index cb0961eba..ce21edb51 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json @@ -1,6 +1,7 @@ { "name": "normalize_score", "batch_size": 2, + "max_concurrency": 4, "row_timeout_seconds": 0.75, "artifact": { "kind": "python_callable", diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json new file mode 100644 index 000000000..7bf0c375c --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json @@ -0,0 +1,269 @@ +[ + { + "name": "pip", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "reordered-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "numpy==2.2.0", + "openai==3.40.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "changed-pin", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.46.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:43da49cfcf8ecd47becb5be20b9eff06c5267f9244c18e751b230c624f5ad12a" + }, + { + "name": "changed-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "prod", + "LABEL": "你好" + } + }, + "digest": "sha256:9b305e9188f4ddda5a0b72d2235c2c46ba50de9bf82c699f5060b02e4aa0820d" + }, + { + "name": "changed-python", + "runtime": { + "kind": "python", + "python_version": "3.11", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:8fa58561581414b02d0619e466e3720828d1820d8211b0e73c90ec4b0d3ecd0c" + }, + { + "name": "gpu", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true + }, + "digest": "sha256:3ea9354ff101038937b1f5a3b6639c4cc6dcb88ee975dcb8e1a5dee2500c283c" + }, + { + "name": "gpu-class", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true, + "gpu_class": "a100" + }, + "digest": "sha256:253f0641ef029aed8337bbcb210f7769147d671747406f7ce4fa5dc40d5c5efc" + }, + { + "name": "conda", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "conda-forge", + "defaults" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:9246f88a6b1daceb3090c51930650ea967947142cdc70737c847a6bf72c85d30" + }, + { + "name": "reordered-channels", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "defaults", + "conda-forge" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:12ef13a6f5b8730a719288ab2406e7f6c13634b14dbef2390f0bbe62f847e18d" + }, + { + "name": "system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "zlib1g", + "ffmpeg" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "reordered-system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "ffmpeg", + "zlib1g" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "empty-environment", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + } + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-fields", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [], + "channels": [], + "modules": [], + "system_packages": [] + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + } +] diff --git a/rust/lancedb/tests/remote_blob_ranges.rs b/rust/lancedb/tests/remote_blob_ranges.rs new file mode 100644 index 000000000..51c49fe09 --- /dev/null +++ b/rust/lancedb/tests/remote_blob_ranges.rs @@ -0,0 +1,634 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +#![cfg(feature = "remote")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{Array, ArrayRef, LargeBinaryArray, RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use lancedb::Table; +use lancedb::blob::BlobRangeRequest; +use lancedb::remote::{ClientConfig, RetryConfig, TimeoutConfig}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; + +const MIB: u64 = 1024 * 1024; +const IDENTITY: &str = "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const ROUTE: &str = "/v1/table/test/fetch_blob_ranges/"; + +struct Reply { + status: u16, + version: Option, + body: Vec, + declared_extra: usize, + identity: Option<&'static str>, +} + +fn ipc(column: &str, values: ArrayRef) -> Vec { + let batch = RecordBatch::try_from_iter([(column, values)]).unwrap(); + let mut body = Vec::new(); + let mut writer = StreamWriter::try_new(&mut body, &batch.schema()).unwrap(); + // Multiple batches exercise response assembly as well as HTTP partitions. + let mid = batch.num_rows() / 2; + writer.write(&batch.slice(0, mid)).unwrap(); + writer + .write(&batch.slice(mid, batch.num_rows() - mid)) + .unwrap(); + writer.finish().unwrap(); + drop(writer); + body +} + +fn legacy_reply(path: &str, body: &Value, takes: usize) -> Reply { + use arrow_array::{StructArray, UInt8Array, UInt32Array, UInt64Array}; + let version = body["version"] + .as_u64() + .unwrap_or(if takes == 1 { 7 } else { 8 }); + if path.ends_with("/query/") { + assert_eq!(body["branch"], "experiment"); + assert_eq!(body["columns"], json!(["image"])); + let filter = body["filter"].as_str().unwrap(); + let ids = filter + .split_once('(') + .unwrap() + .1 + .trim_end_matches(')') + .split(',') + .map(|id| id.trim().parse::().unwrap()) + .filter(|id| [10, 20, 30, 40].contains(id)) + .rev() + .collect::>(); + let fields = lance_core::datatypes::BLOB_V2_DESC_FIELDS.clone(); + let descriptors = StructArray::new( + fields, + vec![ + Arc::new(UInt8Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from( + ids.iter() + .map(|id| if *id == 40 { 0 } else { 5 }) + .collect::>(), + )), + Arc::new(UInt32Array::from(vec![0; ids.len()])), + Arc::new(StringArray::from(vec![""; ids.len()])), + ], + Some(ids.iter().map(|id| *id != 20).collect()), + ); + let batch = RecordBatch::try_from_iter([ + ("image", Arc::new(descriptors) as ArrayRef), + ("_rowid", Arc::new(UInt64Array::from(ids)) as ArrayRef), + ]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + Reply { + status: 200, + version: Some(version), + body: bytes, + declared_extra: 0, + identity: Some(IDENTITY), + } + } else { + assert!(path.contains("branch=experiment"), "{path}"); + let version = path + .split("version=") + .nth(1) + .unwrap() + .split('&') + .next() + .unwrap() + .parse::() + .unwrap(); + let range = body["range"] + .as_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap(); + let (start, end) = range.split_once('-').unwrap(); + let start = start.parse::().unwrap(); + let end = end.parse::().unwrap(); + let payload = if version == 8 { b"ALPHA" } else { b"alpha" }; + Reply { + status: 206, + version: Some(version), + body: payload[start..=end].to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + } + } +} + +fn reply(values: Vec>>, version: u64) -> Reply { + Reply { + status: 200, + version: Some(version), + body: ipc( + "value", + Arc::new(LargeBinaryArray::from_iter( + values.iter().map(|v| v.as_deref()), + )), + ), + declared_extra: 0, + identity: Some(IDENTITY), + } +} + +fn byte(row: u64, offset: u64, version: u64) -> u8 { + ((row * 17 + offset % 251 + version) % 251) as u8 +} + +fn serve_ranges(body: &Value, version: u64) -> Reply { + assert_eq!(body["column"], "image"); + let ranges = body["ranges"].as_array().unwrap(); + assert!(ranges.len() <= 1024); + assert!( + ranges + .iter() + .map(|r| r["length"].as_u64().unwrap()) + .sum::() + <= 64 * MIB + ); + let values = ranges + .iter() + .map(|r| { + let row = r["row_id"].as_u64().unwrap(); + let offset = r["offset"].as_u64().unwrap(); + let length = r["length"].as_u64().unwrap(); + (row != 20).then(|| { + (offset..offset + length) + .map(|i| byte(row, i, version)) + .collect() + }) + }) + .collect(); + reply(values, version) +} + +struct Server { + url: String, + calls: Arc>>, + task: tokio::task::JoinHandle<()>, + identities: Arc>>>, +} + +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl Server { + async fn new(handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static) -> Self { + Self::with_capability(handler, Some("1")).await + } + + async fn with_capability( + handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static, + capability: Option<&'static str>, + ) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let calls = Arc::new(Mutex::new(Vec::new())); + let captured = calls.clone(); + let identities = Arc::new(Mutex::new(Vec::new())); + let captured_identities = identities.clone(); + let task = tokio::spawn(async move { + let mut fetches = 0; + let mut takes = 0; + loop { + let (socket, _) = listener.accept().await.unwrap(); + let captured = captured.clone(); + let result = tokio::time::timeout(Duration::from_secs(20), async { + let mut socket = BufReader::new(socket); + let mut line = String::new(); + socket.read_line(&mut line).await?; + let path = line.split_whitespace().nth(1).unwrap().to_string(); + let method = line.split_whitespace().next().unwrap().to_string(); + let mut range = String::new(); + let mut length = 0; + let mut identity = None; + loop { + line.clear(); + socket.read_line(&mut line).await?; + assert!(line.len() <= 16384); + if line == "\r\n" { break; } + if let Some((name, value)) = line.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse::().unwrap(); + } + if name.eq_ignore_ascii_case("x-lancedb-query-snapshot") { identity = Some(value.trim().to_owned()); } + if name.eq_ignore_ascii_case("range") { range = value.trim().to_string(); } + } + } + assert!(length <= 256 * 1024); + let mut bytes = vec![0; length]; + socket.read_exact(&mut bytes).await?; + let body = if method == "GET" { json!({"range": range}) } else if bytes.is_empty() { json!({}) } else { serde_json::from_slice(&bytes).unwrap() }; + captured.lock().unwrap().push((path.clone(), body.clone())); + let response = if path == "/v1/table/test/describe/" { + Reply { status: 200, version: None, body: serde_json::to_vec(&json!({"version": 8, "schema": {"fields": []}})).unwrap(), declared_extra: 0, identity: None } + } else if path == "/v1/table/test/branches/list/" { + Reply { status: 200, version: None, body: br#"{"branches":{"experiment":{"parentBranch":null,"parentVersion":1,"createAt":1,"manifestSize":1}}}"#.to_vec(), declared_extra: 0, identity: None } + } else if capability != Some("1") { + assert_ne!(path, ROUTE, "unknown capability must select old routes first"); + takes += usize::from(path.ends_with("/query/")); + legacy_reply(&path, &body, takes) + } else { + assert_eq!(path, ROUTE, "unexpected legacy or fallback request"); + fetches += 1; + captured_identities.lock().unwrap().push(identity); + handler(&body, fetches) + }; + if response.status == 0 { return Ok::<_, std::io::Error>(()); } + let version = response.version.map(|v| format!("x-lancedb-version: {v}\r\n")).unwrap_or_default(); + let capability = if path.ends_with("/describe/") { capability.map(|value| format!("x-lancedb-blob-ranges: {value}\r\n")).unwrap_or_default() } else { String::new() }; + let content_type = if path == ROUTE || path.ends_with("/query/") { "application/vnd.apache.arrow.stream" } else { "application/json" }; + let content_range = if method == "GET" { format!("Content-Range: {}/5\r\n", body["range"].as_str().unwrap().replace("bytes=", "bytes ")) } else { String::new() }; + let identity = if path == ROUTE { response.identity.map(|id| format!("x-lancedb-query-snapshot: {id}\r\n")).unwrap_or_default() } else { String::new() }; + let header = format!("HTTP/1.1 {} Response\r\nContent-Type: {content_type}\r\nphalanx-version: 1.13.0-beta.0\r\n{capability}{version}{identity}{content_range}Content-Length: {}\r\nConnection: close\r\n\r\n", response.status, response.body.len() + response.declared_extra); + socket.write_all(header.as_bytes()).await?; + for chunk in response.body.chunks(8192) { socket.write_all(chunk).await?; } + socket.shutdown().await?; + Ok(()) + }).await; + // A client rejecting a malformed schema may close the body early. + assert!(result.is_ok(), "loopback request timed out"); + } + }); + Self { + url, + calls, + task, + identities, + } + } + + async fn table(&self, version: Option) -> Table { + let db = lancedb::connect("db://dev") + .api_key("fake") + .region("us-east-1") + .host_override(&self.url) + .client_config(ClientConfig { + retry_config: RetryConfig { + retries: Some(2), + connect_retries: Some(2), + read_retries: Some(2), + ..Default::default() + }, + timeout_config: TimeoutConfig { + timeout: Some(Duration::from_secs(30)), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let mut open = db.open_table("test").branch("experiment"); + if let Some(version) = version { + open = open.version(version); + } + open.execute().await.unwrap() + } +} + +#[tokio::test] +async fn public_ranges_work_on_old_routes_only_servers() { + for capability in [None, Some("0"), Some("2")] { + for checkout in [None, Some(3)] { + let server = Server::with_capability( + |_, _| panic!("new endpoint must not be requested"), + capability, + ) + .await; + let table = server.table(checkout).await; + let cloned = table.clone(); + let ranges = [ + BlobRangeRequest::new(10, 1, 3), + BlobRangeRequest::new(20, 0, 1), + BlobRangeRequest::new(40, 0, 0), + BlobRangeRequest::new(10, 5, 0), + BlobRangeRequest::new(10, 1, 3), + ]; + let result = cloned.fetch_blob_ranges("image", ranges).await.unwrap(); + assert_eq!( + result, + LargeBinaryArray::from(vec![ + Some(b"lph".as_slice()), + None, + Some(b"".as_slice()), + Some(b"".as_slice()), + Some(b"lph".as_slice()) + ]) + ); + let result = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!( + result.value(0), + if checkout.is_none() { b"A" } else { b"a" } + ); + for ranges in [ + vec![BlobRangeRequest::new(10, 4, 2)], + vec![BlobRangeRequest::new(99, 0, 1)], + ] { + assert!(matches!( + table.fetch_blob_ranges("image", ranges).await.unwrap_err(), + lancedb::Error::InvalidInput { .. } + )); + } + assert!( + !server + .calls + .lock() + .unwrap() + .iter() + .any(|(path, _)| path == ROUTE) + ); + } + } +} + +#[tokio::test] +async fn public_ranges_keep_order_nulls_and_snapshot_without_pinning_live_handle() { + for checkout in [None, Some(3)] { + let server = Server::new(move |body, call| { + assert_eq!(body["branch"], "experiment"); + let expected = checkout.or((call > 1 && call < 3).then_some(7)); + assert_eq!(body["version"].as_u64(), expected); + serve_ranges( + body, + body["version"] + .as_u64() + .unwrap_or(if call == 1 { 7 } else { 8 }), + ) + }) + .await; + let table = server.table(checkout).await; + let mut requests = (0..1025) + .map(|i| BlobRangeRequest::new(if i % 9 == 0 { 20 } else { 10 + i % 7 }, i, i % 4)) + .collect::>(); + requests.extend([ + BlobRangeRequest::new(10, 0, 0), + BlobRangeRequest::new(10, 2, 3), + BlobRangeRequest::new(10, 2, 3), + ]); + let result = table + .fetch_blob_ranges("image", requests.clone()) + .await + .unwrap(); + assert_eq!(result.len(), requests.len()); + for (i, request) in requests.iter().enumerate() { + assert_eq!(result.is_null(i), request.row_id == 20); + if request.row_id != 20 { + let expected = (request.offset..request.offset + request.length) + .map(|j| byte(request.row_id, j, checkout.unwrap_or(7))) + .collect::>(); + assert_eq!(result.value(i), expected); + } + } + let next = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!(next.value(0), [byte(10, 0, checkout.unwrap_or(8))]); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); + } +} + +#[tokio::test] +async fn public_ranges_partition_bytes_and_reassemble_large_single_range() { + let server = Server::new(|body, call| { + assert_eq!(body["version"].as_u64(), (call > 1).then_some(7)); + serve_ranges(body, 7) + }) + .await; + let table = server.table(None).await; + let requests = [ + BlobRangeRequest::new(10, 3, 33 * MIB), + BlobRangeRequest::new(30, 7, 33 * MIB), + BlobRangeRequest::new(40, 11, 70 * MIB), + BlobRangeRequest::new(20, 0, u64::MAX), + ]; + let result = table.fetch_blob_ranges("image", requests).await.unwrap(); + assert_eq!(result.len(), 4); + for (i, request) in requests[..3].iter().enumerate() { + assert_eq!(result.value_length(i) as u64, request.length); + assert!( + result + .value(i) + .iter() + .enumerate() + .all(|(j, value)| *value == byte(request.row_id, request.offset + j as u64, 7)) + ); + } + assert!(result.is_null(3)); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); +} + +#[tokio::test] +async fn public_ranges_reject_malformed_responses_and_http_failures_without_fallback() { + for case in 0..16 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + // Fail after one successful partition to prove no partial success. + if call == 1 { + return response; + } + match case { + 0 => response.body = ipc("value", Arc::new(StringArray::from(vec!["bad"]))), + 1 => { + response.body = ipc( + "wrong", + Arc::new(LargeBinaryArray::from(vec![Some(b"a".as_slice())])), + ) + } + 2 => response = reply(vec![], 7), + 3 => response = reply(vec![Some(vec![1]), Some(vec![2])], 7), + 4 => response.body.truncate(response.body.len() - 8), + 5 => response.body.truncate(response.body.len() / 2), + 6 => response.declared_extra = 10, + 7 => response = reply(vec![Some(vec![])], 7), + 8 => response.version = None, + 9 => response.version = Some(8), + 10..=14 => { + response.status = [401, 403, 404, 429, 500][case - 10]; + response.body = b"ordinary failure".to_vec(); + } + 15 => response.status = 0, + _ => unreachable!(), + } + response + }) + .await; + let table = server.table(None).await; + let requests = vec![BlobRangeRequest::new(10, 0, 1); 1025]; + assert!( + table.fetch_blob_ranges("image", requests).await.is_err(), + "case {case}" + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2, + "case {case}" + ); + } +} + +#[tokio::test] +async fn public_ranges_validate_locally_and_propagate_server_range_errors() { + let server = Server::new(|_, _| Reply { + status: 400, + version: None, + body: b"range exceeds blob size or missing row".to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + assert_eq!(table.fetch_blob_ranges("image", []).await.unwrap().len(), 0); + assert!( + table + .fetch_blob_ranges("image", [BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err() + .to_string() + .contains("overflows u64") + ); + assert_eq!(server.calls.lock().unwrap().len(), before); + let error = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 9, 2)]) + .await + .unwrap_err(); + assert!(matches!(error, lancedb::Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds")); +} + +#[tokio::test] +async fn public_ranges_require_original_identity_on_every_partition() { + for huge in [false, true] { + for case in 0..5 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + if call == 2 { + response.identity = match case { + 0 => None, // Old serving node ignores the precondition. + 1 => Some("invalid"), + _ => Some( + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ), + }; + if case == 3 || case == 4 { + response.status = if case == 3 { 400 } else { 404 }; + response.body = + b"query snapshot identity mismatch: gone or replaced".to_vec(); + } else { + // Identity verification must win over malformed payload. + response.body = b"not Arrow".to_vec(); + } + } + response + }) + .await; + let table = server.table(None).await; + let requests = if huge { + vec![BlobRangeRequest::new(10, 0, 64 * MIB + 1)] + } else { + vec![BlobRangeRequest::new(10, 0, 1); 1025] + }; + let error = table + .fetch_blob_ranges("image", requests) + .await + .unwrap_err(); + if case < 3 { + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + } else if case == 3 { + assert!( + matches!(error, lancedb::Error::InvalidInput { .. }), + "{error}" + ); + } else { + assert!( + matches!(error, lancedb::Error::TableNotFound { .. }), + "{error}" + ); + } + assert_eq!( + *server.identities.lock().unwrap(), + [None, Some(IDENTITY.into())] + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2 + ); + } + } +} + +#[tokio::test] +async fn public_ranges_cannot_establish_identity_from_numeric_version_or_describe() { + for identity in [None, Some("invalid"), Some("v2:unsupported")] { + let server = Server::new(move |_, call| { + assert_eq!(call, 1, "no failure fallback, replay or second partition"); + let mut response = reply(vec![Some(b"A".to_vec()); 1024], 7); + response.identity = identity; + response.body = b"not Arrow".to_vec(); + response + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + let error = table + .fetch_blob_ranges("image", vec![BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap_err(); + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + assert_eq!(server.calls.lock().unwrap().len(), before + 1); + } +} diff --git a/rust/lancedb/tests/table_delta_docs.rs b/rust/lancedb/tests/table_delta_docs.rs new file mode 100644 index 000000000..0fa9c9f18 --- /dev/null +++ b/rust/lancedb/tests/table_delta_docs.rs @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::Arc; + +use arrow_array::cast::AsArray; +use arrow_array::types::Int64Type; +use arrow_array::{RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray}; +use arrow_schema::{DataType, Field, Schema}; +fn make_quotes_reader(rows: Vec<(i64, &str, &str)>) -> Box { + let ids: Vec = rows.iter().map(|(id, _, _)| *id).collect(); + let authors: Vec<&str> = rows.iter().map(|(_, author, _)| *author).collect(); + let quotes: Vec<&str> = rows.iter().map(|(_, _, quote)| *quote).collect(); + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("author", DataType::Utf8, false), + Field::new("quote", DataType::Utf8, false), + ])); + + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(arrow_array::Int64Array::from(ids)), + Arc::new(StringArray::from(authors)), + Arc::new(StringArray::from(quotes)), + ], + ) + .unwrap(); + Box::new(RecordBatchIterator::new( + vec![Ok(batch)].into_iter(), + schema, + )) +} + +#[tokio::test] +async fn checkpoint_delta_docs() -> anyhow::Result<()> { + let directory = tempfile::tempdir()?; + let db = lancedb::connect(directory.path().to_str().unwrap()) + .execute() + .await?; + + // --8<-- [start:versioning_checkpoint_delta] + use futures::TryStreamExt; + + let table = db + .create_table( + "checkpoint_delta_example", + make_quotes_reader(vec![ + (1, "Richard", "Wubba Lubba Dub Dub!"), + (2, "Morty", "Rick, what's going on?"), + ]), + ) + .storage_option("new_table_enable_stable_row_ids", "true") + .execute() + .await?; + + let mut tags = table.tags().await?; + tags.create("baseline", table.version().await?).await?; + table + .add(make_quotes_reader(vec![(3, "Summer", "Whatever, Grandpa")])) + .execute() + .await?; + table + .update() + .only_if("id = 2") + .column("quote", "'Aww geez, Rick!'") + .execute() + .await?; + table.delete("id = 1").await?; + + let delta = table.delta("baseline", None).await?; + let mut inserted = delta.inserted_rows().await?; + while let Some(batch) = inserted.try_next().await? { + println!("inserted: {:?}", batch.column_by_name("id")); + } + let mut deleted = delta.deleted_row_ids().await?; + while let Some(batch) = deleted.try_next().await? { + println!("deleted row ids: {batch:?}"); + } + for transaction in delta.list_transactions().await? { + println!("{}", transaction.operation.name()); + } + // --8<-- [end:versioning_checkpoint_delta] + + assert_eq!(table.version().await?, 4); + + let inserted = delta.inserted_rows().await?.try_collect::>().await?; + let inserted_ids: Vec = inserted + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(inserted_ids, vec![3]); + + let updated = delta.updated_rows().await?.try_collect::>().await?; + let updated_ids: Vec = updated + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(updated_ids, vec![2]); + assert_eq!( + delta + .deleted_row_ids() + .await? + .try_collect::>() + .await? + .len(), + 1 + ); + assert_eq!( + delta + .list_transactions() + .await? + .iter() + .map(|transaction| transaction.operation.name()) + .collect::>(), + vec!["Append", "Update", "Delete"] + ); + + Ok(()) +} diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 000000000..5bd7130a5 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,98 @@ +#!/bin/sh +# Install the public LanceDB command-line client from GitHub Releases. +set -eu + +fail() { + printf 'lancedb installer: %s\n' "$*" >&2 + exit 1 +} + +download() { + curl -q --proto '=https' --proto-redir '=https' -fsSL "$@" +} + +main() { + [ "$#" -eq 0 ] || fail 'Set LANCEDB_VERSION and LANCEDB_INSTALL_DIR via the environment.' + releases=https://github.com/lancedb/lancedb/releases + platform=$(uname -s)-$(uname -m) + case "$platform" in + Darwin-arm64) target=aarch64-apple-darwin ;; + Linux-aarch64|Linux-arm64) target=aarch64-unknown-linux-gnu ;; + Linux-x86_64) target=x86_64-unknown-linux-gnu ;; + *) fail "No CLI archive for $platform. Supported: Apple Silicon macOS, Linux ARM64 and Linux x86-64." ;; + esac + + case "$target" in + *-linux-gnu) + libc=$(getconf GNU_LIBC_VERSION 2>/dev/null) || fail 'Linux requires glibc 2.28 or newer.' + printf '%s\n' "$libc" | awk -F '[ .]' '$1 == "glibc" && ($2 > 2 || ($2 == 2 && $3 >= 28)) { ok=1 } END { exit !ok }' || + fail 'Linux requires glibc 2.28 or newer.' + if [ "$target" = x86_64-unknown-linux-gnu ]; then + for feature in avx2 fma f16c; do + grep -qw "$feature" /proc/cpuinfo || fail "The Linux x86-64 binary requires CPU feature $feature." + done + fi ;; + *-apple-darwin) + os_version=$(sw_vers -productVersion) + [ "${os_version%%.*}" -ge 14 ] || fail 'Apple Silicon requires macOS 14 or newer.' ;; + esac + + dir=${LANCEDB_INSTALL_DIR:-"$HOME/.local/bin"} + case "$dir" in /*) ;; *) fail 'LANCEDB_INSTALL_DIR must be an absolute path.' ;; esac + dest=$dir/lancedb + if [ -e "$dest" ] || [ -L "$dest" ]; then + fail "$dest already exists. Move it first or choose a separate LANCEDB_INSTALL_DIR." + fi + if existing=$(command -v lancedb); then + if [ -z "${LANCEDB_INSTALL_DIR:-}" ]; then + fail "Found $existing on PATH. To install alongside it, set LANCEDB_INSTALL_DIR to a separate directory." + fi + fi + + tag=${LANCEDB_VERSION:-} + if [ -z "$tag" ]; then + latest=$(download --head --output /dev/null --write-out '%{url_effective}' "$releases/latest") + tag=${latest##*/} + fi + version=${tag#v} + # Match the stable and beta tag formats supported by ci/package_cli.py. + case "$version" in *[!0-9a-z.-]*|'') fail "Invalid release version: $tag" ;; esac + printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$' || + fail "Invalid release version: $tag" + + stem=lancedb-v$version-$target + archive=$stem.tar.gz + url=$releases/download/v$version + mkdir -p "$dir" + # Stage on the destination filesystem so the final hard link is atomic and cannot overwrite a file. + stage=$(mktemp -d "$dir/.lancedb-install.XXXXXXXX") + trap 'rm -rf "$stage"' EXIT + trap 'exit 1' HUP INT TERM + + download -o "$stage/SHA256SUMS" "$url/SHA256SUMS" || + fail "Could not fetch CLI checksums for v$version. Choose a release with CLI assets using LANCEDB_VERSION." + expected=$(awk -v name="$archive" '$2 == name { count++; hash=$1 } END { if (count != 1) exit 1; print hash }' "$stage/SHA256SUMS") || + fail "Expected exactly one checksum for $archive." + download -o "$stage/$archive" "$url/$archive" + if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum < "$stage/$archive") + else + actual=$(shasum -a 256 < "$stage/$archive") + fi + [ "${actual%% *}" = "$expected" ] || fail "Checksum mismatch for $archive." + + tar -xzOf "$stage/$archive" "$stem/lancedb" > "$stage/lancedb" + chmod 755 "$stage/lancedb" + reported=$("$stage/lancedb" --version) || + fail "Cannot run $target on this machine. Check the CPU and OS requirements in the CLI install guide." + [ "$reported" = "lancedb $version" ] || fail "Unexpected CLI version: $reported" + ln "$stage/lancedb" "$dest" + printf 'Installed %s at %s\n' "$reported" "$dest" + case ":${PATH:-}:" in + *:"$dir":*) ;; + *) printf 'Add %s to PATH or invoke the full path above.\n' "$dir" ;; + esac +} + +# Keep the entry point last so a truncated download cannot start installation. +main "$@"