diff --git a/.bumpversion.toml b/.bumpversion.toml index 8f10d67f0..5a9826d7b 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.18" +current_version = "0.42.0-beta.22" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. 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 3d92d818a..0d061ac59 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -17,7 +17,7 @@ runs: 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/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/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..3dc4dab56 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -47,7 +47,7 @@ jobs: python-version: "3.10" 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: | diff --git a/.github/workflows/gh-release.yml b/.github/workflows/gh-release.yml index bbaade34c..eedf8450c 100644 --- a/.github/workflows/gh-release.yml +++ b/.github/workflows/gh-release.yml @@ -77,7 +77,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 +85,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. 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/nodejs.yml b/.github/workflows/nodejs.yml index 4d28ca4a1..9a21786d2 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -42,7 +42,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 @@ -52,14 +52,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 +98,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 +110,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 +188,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 +196,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 @@ -249,7 +249,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 @@ -259,11 +259,11 @@ jobs: cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml # Use the same pinned compiler for cache selection and the native build. - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: cache: false rustflags: "" - - 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/npm-publish.yml b/.github/workflows/npm-publish.yml index ac95b5a47..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: @@ -167,7 +167,7 @@ jobs: # 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 @@ -178,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 @@ -194,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 @@ -216,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 }} @@ -225,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 }} @@ -326,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 @@ -352,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 @@ -394,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: @@ -404,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 8730e220d..304e96857 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -184,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 @@ -311,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 e208ac7cd..62da9cf6e 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 @@ -198,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 @@ -236,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. @@ -271,7 +271,7 @@ jobs: python-version: "3.10" # 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 636c1a7bf..b3805b422 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -42,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: | @@ -108,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 @@ -135,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 @@ -151,7 +151,7 @@ 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. @@ -159,8 +159,8 @@ jobs: # 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 @@ -208,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 @@ -218,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 @@ -280,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. @@ -290,7 +290,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: Run remote tests run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests @@ -317,7 +317,7 @@ jobs: 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 }} @@ -358,7 +358,7 @@ jobs: 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 @@ -397,7 +397,7 @@ jobs: 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 @@ -437,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 6f75f40c8..e7c3b1caf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1395,7 +1395,7 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" dependencies = [ - "bit-vec 0.10.1", + "bit-vec 0.10.2", ] [[package]] @@ -1406,9 +1406,9 @@ checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" [[package]] name = "bit-vec" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" dependencies = [ "borsh", "serde", @@ -3786,9 +3786,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", ] @@ -3885,8 +3885,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5190,18 +5190,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", @@ -5364,8 +5364,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arc-swap", "arrow", @@ -5440,8 +5440,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-buffer", @@ -5463,7 +5463,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-buffer", @@ -5477,7 +5477,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-schema", @@ -5486,8 +5486,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrayref", "crunchy", @@ -5497,8 +5497,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-buffer", @@ -5536,8 +5536,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5568,8 +5568,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5594,8 +5594,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5612,8 +5612,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "proc-macro2", "quote", @@ -5622,8 +5622,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-arith", "arrow-array", @@ -5657,8 +5657,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-arith", "arrow-array", @@ -5689,8 +5689,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-schema", @@ -5721,8 +5721,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arc-swap", "arrow", @@ -5795,8 +5795,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-schema", @@ -5819,8 +5819,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -5865,8 +5865,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "byteorder", "ethnum", @@ -5883,7 +5883,7 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.25" +version = "15.0.0-beta.26" dependencies = [ "approx", "argminmax 0.7.1", @@ -5905,8 +5905,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "async-trait", @@ -5920,8 +5920,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arc-swap", "arrow", @@ -5975,8 +5975,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-buffer", @@ -5990,8 +5990,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow", "arrow-array", @@ -6032,8 +6032,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "arrow-array", "arrow-schema", @@ -6046,8 +6046,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.25" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" +version = "15.0.0-beta.26" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.26#f9fd19edfb14e43d3981b20dfaf183672751414b" dependencies = [ "frostem", "icu_segmenter", @@ -6060,7 +6060,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.18" +version = "0.42.0-beta.22" dependencies = [ "ahash", "anyhow", @@ -6171,7 +6171,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.18" +version = "0.42.0-beta.22" dependencies = [ "anyhow", "arrow-array", @@ -6214,7 +6214,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.18" +version = "0.42.0-beta.22" dependencies = [ "arrow-array", "arrow-buffer", @@ -6234,12 +6234,13 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "serde", "serde_json", ] [[package]] name = "lancedb-python" -version = "0.42.0-beta.18" +version = "0.42.0-beta.22" dependencies = [ "arc-swap", "arrow", @@ -6393,9 +6394,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", ] @@ -8668,7 +8669,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ "bit-set 0.11.1", - "bit-vec 0.10.1", + "bit-vec 0.10.2", "bitflags 2.11.1", "chacha20", "core_detect", @@ -11925,9 +11926,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", diff --git a/Cargo.toml b/Cargo.toml index d38249548..b7d4b9db7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,20 +20,20 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.26", default-features = false, "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.26", default-features = false, "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.26", default-features = false, "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" 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/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/deny.toml b/deny.toml
      index 458559936..b10550a54 100644
      --- a/deny.toml
      +++ b/deny.toml
      @@ -132,13 +132,31 @@ ignore = [
           { 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. Transitive via
      -    # aws-smithy-http/runtime/types, including aws-config -> lance-io.
      -    # No safe upgrade exists; clearing requires AWS Smithy to migrate to
      -    # core::pin::pin!, pin-project, or pin-project-lite. Revisit on AWS updates.
      +    # 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
      -    # https://github.com/rustsec/advisory-db/issues/3314
      -    { id = "RUSTSEC-2026-0441", reason = "pin-utils unmaintained via AWS Smithy; no safe upgrade, awaiting upstream migration" },
      +
      +    # 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/src/java/java.md b/docs/src/java/java.md
      index 1a8347ad5..86faf0a61 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.18
      +    0.42.0-beta.22
       
       ```
       
      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..b3fcf5ec3 100644
      --- a/docs/src/js/classes/Index.md
      +++ b/docs/src/js/classes/Index.md
      @@ -258,3 +258,51 @@ using an underlying bitmap index.
       #### Returns
       
       [`Index`](Index.md)
      +
      +***
      +
      +### 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 f93c1b7cd..a1618c47b 100644
      --- a/docs/src/js/classes/Table.md
      +++ b/docs/src/js/classes/Table.md
      @@ -268,6 +268,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
      @@ -305,6 +337,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
      @@ -423,7 +489,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.
      @@ -444,7 +510,7 @@ account for the replacement caveat described in [Table.createIndex](Table.md#cre
       
       #### Returns
       
      -`Promise`<[`Job`](Job.md)>
      +`Promise`<[`Job`](Job.md)<`void`>>
       
       ***
       
      @@ -486,6 +552,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
      @@ -619,6 +732,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
      @@ -867,6 +1032,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
      @@ -1047,29 +1232,99 @@ retrying with the settings removed.
       
       ### 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();
      +```
       
       ***
       
      @@ -1200,7 +1455,7 @@ number of rows filled and the new version number of the table.
       ### refreshColumnAsync()
       
       ```ts
      -abstract refreshColumnAsync(column, options?): Promise
      +abstract refreshColumnAsync(column, options?): Promise>
       ```
       
       Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh
      @@ -1225,26 +1480,18 @@ LanceDB Enterprise it is the server's backfill job.
           `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
           `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
           and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`,
      -    `maxConcurrency`, `resourceBudget`, `supervisorResources`,
      +    `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. A `resourceBudget` requires `cpuMillis` and
      -    `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function.
      -    `supervisorResources` and each `planningWorkers.resources` entry require
      -    positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`.
      -    `planningWorkers` also requires positive `maxWorkers`,
      -    `rowsPerWorker` and `fragmentsPerWorker`.
      -    The budget applies only to this explicit refresh and does not configure
      -    a later automatic refresh.
      -    `gpuCount` at the top level is the shorthand that preserves the
      -    deployment defaults for CPU and memory, and cannot be combined with
      -    `resourceBudget`. `numWorkers` applies only to expression columns; use
      -    `resourceBudget` for registered Functions. All are LanceDB Enterprise
      -    only; a LanceDB Embedded refresh rejects every option other than
      -    `batchSize`, `gpuClass` and `gpuCount`.
      +    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.
      @@ -1253,17 +1500,15 @@ LanceDB Enterprise it is the server's backfill job.
       
       #### Returns
       
      -`Promise`<[`Job`](Job.md)>
      +`Promise`<[`Job`](Job.md)<`void`>>
       
       #### Example
       
       ```ts
       const job = await table.refreshColumnAsync("embedding", {
         where: "published_at > '2026-01-01'",
      -  resourceBudget: {
      -    cpuMillis: 8000,
      -    memoryBytes: 16 * 1024 ** 3,
      -  },
      +  totalCpuMillis: 8000,
      +  totalMemoryBytes: 16 * 1024 ** 3,
         maxConcurrency: 4,
         publicationIntervalRows: 10000,
         errorPolicy: "skip",
      @@ -1276,6 +1521,22 @@ 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
      @@ -1633,6 +1894,44 @@ 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 } },
      +});
      +```
      +
      +***
      +
       ### vectorSearch()
       
       ```ts
      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/globals.md b/docs/src/js/globals.md
      index 23e576877..79ebf0f13 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)
      @@ -71,13 +72,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)
      @@ -103,10 +109,12 @@
       - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md)
       - [FunctionErrors](interfaces/FunctionErrors.md)
       - [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md)
      +- [FunctionProfile](interfaces/FunctionProfile.md)
      +- [FunctionProfileOptions](interfaces/FunctionProfileOptions.md)
      +- [FunctionProfileWaitOptions](interfaces/FunctionProfileWaitOptions.md)
       - [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md)
       - [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md)
       - [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md)
      -- [FunctionWorkerResourceBudget](interfaces/FunctionWorkerResourceBudget.md)
       - [HnswPqOptions](interfaces/HnswPqOptions.md)
       - [HnswSqOptions](interfaces/HnswSqOptions.md)
       - [IndexConfig](interfaces/IndexConfig.md)
      @@ -119,6 +127,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)
      @@ -128,9 +137,14 @@
       - [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)
       - [RefreshColumnOptions](interfaces/RefreshColumnOptions.md)
       - [RefreshColumnResult](interfaces/RefreshColumnResult.md)
       - [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md)
      @@ -147,6 +161,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)
      @@ -178,13 +194,19 @@
       - [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)
       - [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/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/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
      index 3a203026c..eb95c8004 100644
      --- a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md
      +++ b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md
      @@ -22,11 +22,11 @@ optional activeJobId: string;
       
       ```ts
       optional blockedReason:
      +  | "cancelled"
         | "table_has_mem_wal"
         | "inputs_not_settled"
         | "dependency_in_flight"
         | "table_capacity"
      -  | "cancelled"
         | "preparation_backoff"
         | "failure_threshold_reached"
         | "binding_revision_missing";
      @@ -86,8 +86,8 @@ optional nextRunAtReason: string;
       
       ```ts
       state:
      -  | "running"
         | "queued"
      +  | "running"
         | "disabled"
         | "ready"
         | "up_to_date"
      diff --git a/docs/src/js/interfaces/FunctionErrors.md b/docs/src/js/interfaces/FunctionErrors.md
      index bee0a80d8..17f2beefa 100644
      --- a/docs/src/js/interfaces/FunctionErrors.md
      +++ b/docs/src/js/interfaces/FunctionErrors.md
      @@ -20,6 +20,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
      diff --git a/docs/src/js/interfaces/FunctionErrorsOptions.md b/docs/src/js/interfaces/FunctionErrorsOptions.md
      index af0e71cfe..ec8b9b036 100644
      --- a/docs/src/js/interfaces/FunctionErrorsOptions.md
      +++ b/docs/src/js/interfaces/FunctionErrorsOptions.md
      @@ -37,3 +37,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/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/FunctionWorkerResourceBudget.md b/docs/src/js/interfaces/FunctionWorkerResourceBudget.md
      deleted file mode 100644
      index 0352bc833..000000000
      --- a/docs/src/js/interfaces/FunctionWorkerResourceBudget.md
      +++ /dev/null
      @@ -1,39 +0,0 @@
      -[**@lancedb/lancedb**](../README.md) • **Docs**
      -
      -***
      -
      -[@lancedb/lancedb](../globals.md) / FunctionWorkerResourceBudget
      -
      -# Interface: FunctionWorkerResourceBudget
      -
      -Aggregate worker resources for one Enterprise Function refresh.
      -
      -## Properties
      -
      -### cpuMillis
      -
      -```ts
      -cpuMillis: number;
      -```
      -
      -Aggregate CPU budget in millicores; 1000 is one CPU.
      -
      -***
      -
      -### gpuCount?
      -
      -```ts
      -optional gpuCount: number;
      -```
      -
      -Aggregate GPU budget. Omitted means zero, a CPU-only refresh.
      -
      -***
      -
      -### memoryBytes
      -
      -```ts
      -memoryBytes: number;
      -```
      -
      -Aggregate memory budget in bytes.
      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/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/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/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/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md
      index 07157e4ab..4a5b256f7 100644
      --- a/docs/src/js/interfaces/RefreshColumnOptions.md
      +++ b/docs/src/js/interfaces/RefreshColumnOptions.md
      @@ -8,8 +8,7 @@
       
       Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every
       option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores
      -`batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including
      -`resourceBudget`.
      +`batchSize`, `gpuClass` and `totalGpuCount` and rejects the rest.
       
       ## Properties
       
      @@ -50,7 +49,7 @@ GPU class for Function workers.
       optional gpuCount: number;
       ```
       
      -Positive aggregate GPU budget for Function workers.
      +Positive GPU count allocated to each Function worker.
       
       ***
       
      @@ -140,17 +139,6 @@ Requires LanceDB Enterprise with non-Blob Function outputs.
       
       ***
       
      -### resourceBudget?
      -
      -```ts
      -optional resourceBudget: FunctionWorkerResourceBudget;
      -```
      -
      -Complete aggregate CPU and memory budget for a registered Function
      -refresh. `gpuCount` inside the budget defaults to zero.
      -
      -***
      -
       ### retryPolicy?
       
       ```ts
      @@ -181,6 +169,36 @@ 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
      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/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/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 b64940e39..47a20aa57 100644
      --- a/docs/src/python/python.md
      +++ b/docs/src/python/python.md
      @@ -37,6 +37,14 @@ 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
      @@ -298,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:
       
      @@ -352,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
      @@ -420,6 +449,8 @@ code that used the former LanceDB Enterprise-only argument order.
       
       ::: lancedb.table.Branches
       
      +::: lancedb.table.TableDelta
      +
       ::: lancedb.RTEWriteSpec
       
       ## Functions and Jobs
      @@ -442,6 +473,53 @@ identifiers. `fn.image` has a concise representation; `describe()` exposes Pytho
       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
      @@ -449,7 +527,9 @@ and then call the returned instance; call `close()` if the class defines it. Thi
       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 function
      @@ -481,19 +561,41 @@ scaler.close()
       ### Function packaging restrictions
       
       The decorator snapshots the Function's source and referenced globals into a new
      -module. It conservatively rejects imports of `sys`, `builtins`, `importlib`,
      -`inspect`, `gc`, `ctypes`, and `types`, including submodules such as `ctypes.util`
      -and `importlib.metadata`. 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.
      +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.
       
      -For legitimate 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.
      +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`:
       
      @@ -640,7 +742,15 @@ 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
       
      @@ -656,6 +766,8 @@ with BlobReader(read_range, len(payload)) as reader:
       
       ::: lancedb.job.Job
       
      +::: lancedb.job.JobState
      +
       ::: lancedb.job.AsyncJob
       
       ::: lancedb.job.JobInfo
      @@ -664,6 +776,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
      @@ -763,6 +881,8 @@ of raw SQL strings with [where][lancedb.query.LanceQueryBuilder.where] and
       
       ::: lancedb.query.Query
       
      +::: lancedb.query.ColumnOrdering
      +
       ::: lancedb.query.LanceQueryBuilder
       
       ::: lancedb.query.LanceVectorQueryBuilder
      @@ -873,6 +993,18 @@ 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.
      @@ -906,9 +1038,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_.
      ; + 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. */ @@ -4678,15 +5168,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 () => { @@ -5714,9 +6310,10 @@ describe("computed columns", () => { ).rejects.toThrow("max_concurrency requires a LanceDB Enterprise refresh"); await expect( table.refreshColumnAsync("x", { - resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 }, + totalCpuMillis: 1_000, + totalMemoryBytes: 1_024, }), - ).rejects.toThrow("resource_budget requires a LanceDB Enterprise refresh"); + ).rejects.toThrow("total_cpu_millis requires a LanceDB Enterprise refresh"); await expect( table.refreshColumn("x", { supervisorResources: { @@ -5791,3 +6388,68 @@ 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 override methods optional for existing custom Table subclasses", async () => { + // Declare the old Table surface; only the new methods must be inherited. + // Keeping these override methods abstract must fail type checking here. + // biome-ignore lint/correctness/noUnusedVariables: declaration merging supplies the legacy members + interface LegacyTable + extends Omit< + Table, + "getTableOverrides" | "updateTableOverrides" | "resetTableOverrides" + > {} + class LegacyTable extends Table {} + + const table = new LegacyTable(); + 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/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/index.ts b/nodejs/lancedb/index.ts index a6bcd68f5..e8a015c59 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"; @@ -60,7 +60,6 @@ export { FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionRetryPolicy, - FunctionWorkerResourceBudget, RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, @@ -118,7 +117,19 @@ 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, @@ -153,16 +164,22 @@ export { HnswPqOptions, HnswSqOptions, FtsOptions, + RTreeOptions, BaseTokenizer, } from "./indices"; export { Table, + TableDelta, + TableDeltaReader, + TableDeltaTransaction, + DeltaVersion, FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, FunctionColumnVersionStatus, Branches, + CreateBranchOptions, BranchColumnSummary, BranchColumnChange, BranchIndexSummary, @@ -175,6 +192,7 @@ export { UpdateOptions, OptimizeOptions, CompactionOptions, + PrewarmDataOptions, Version, WriteProgress, FtsToken, @@ -664,3 +682,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..d743827da 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,53 @@ 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 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/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/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 f949bd00a..6645e0205 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, @@ -41,7 +58,10 @@ import { IndexConfig, IndexStatistics, JobFailureInfo, + RecordBatchIterator as NativeBatchIterator, Branches as NativeBranches, + DeltaRef as NativeDeltaRef, + TableDelta as NativeTableDelta, OptimizeStats, RTEStats, RefreshColumnOptions, @@ -57,12 +77,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 { @@ -165,6 +187,18 @@ 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. */ @@ -224,6 +258,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. */ @@ -562,22 +632,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. * @@ -831,26 +962,18 @@ export abstract class Table { * `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, * `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` * and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, - * `maxConcurrency`, `resourceBudget`, `supervisorResources`, + * `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. A `resourceBudget` requires `cpuMillis` and - * `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. - * `supervisorResources` and each `planningWorkers.resources` entry require - * positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`. - * `planningWorkers` also requires positive `maxWorkers`, - * `rowsPerWorker` and `fragmentsPerWorker`. - * The budget applies only to this explicit refresh and does not configure - * a later automatic refresh. - * `gpuCount` at the top level is the shorthand that preserves the - * deployment defaults for CPU and memory, and cannot be combined with - * `resourceBudget`. `numWorkers` applies only to expression columns; use - * `resourceBudget` for registered Functions. All are LanceDB Enterprise - * only; a LanceDB Embedded refresh rejects every option other than - * `batchSize`, `gpuClass` and `gpuCount`. + * 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. @@ -860,10 +983,8 @@ export abstract class Table { * ```ts * const job = await table.refreshColumnAsync("embedding", { * where: "published_at > '2026-01-01'", - * resourceBudget: { - * cpuMillis: 8000, - * memoryBytes: 16 * 1024 ** 3, - * }, + * totalCpuMillis: 8000, + * totalMemoryBytes: 16 * 1024 ** 3, * maxConcurrency: 4, * publicationIntervalRows: 10000, * errorPolicy: "skip", @@ -936,6 +1057,11 @@ export abstract class Table { abstract refreshMaterializedView( sourceVersion?: number, full?: boolean, + totalCpuMillis?: number, + totalMemoryBytes?: number, + totalGpuCount?: number, + gpuClass?: string, + gpuCount?: number, ): Promise; /** @ignore */ @@ -1057,6 +1183,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. * @@ -1209,6 +1385,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. * @@ -1505,8 +1762,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( @@ -1757,8 +2043,21 @@ export class LocalTable extends Table { 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 { @@ -1823,6 +2122,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(); } @@ -1860,6 +2173,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, @@ -1884,20 +2209,33 @@ 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 { - // 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?.compactionOptions ?? {})) { - if (!supported.has(key)) { - throw new Error(`Unsupported compaction option: ${key}`); - } - } + validateCompactionOptions(options?.compactionOptions); return await this.inner.optimize( options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, @@ -2102,6 +2440,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}. * @@ -2124,6 +2707,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. * @@ -2135,8 +2730,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), + ); } /** @@ -2197,3 +2819,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 d603a2c8f..dd7e563e1 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.18", + "version": "0.42.0-beta.22", "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 8115e27f9..d9aa4fc34 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.18", + "version": "0.42.0-beta.22", "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 f3cdd7253..ebe6345fb 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.18", + "version": "0.42.0-beta.22", "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 4d165c4de..3f921c91a 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.18", + "version": "0.42.0-beta.22", "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 d884605b6..217ae7e36 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.18", + "version": "0.42.0-beta.22", "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 2b6bdc8da..ddffdf695 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.18", + "version": "0.42.0-beta.22", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 1402f5bee..6f71ba0e6 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.18", + "version": "0.42.0-beta.22", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index a0cf05acb..91d833236 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.22", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index e57bb68d3..df01d672a 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -35,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 @@ -1399,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': @@ -1485,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==} @@ -5165,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 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..80107b0b4 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, RTreeIndexBuilder, +}; use lancedb::index::vector::{ IvfFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder, IvfRqIndexBuilder, @@ -226,6 +228,17 @@ impl Index { } } + #[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 09b245f97..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. /// @@ -141,13 +247,100 @@ impl Job { 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) @@ -187,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, @@ -203,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, } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index a0a220e24..5b1153909 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -2,17 +2,17 @@ // 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, FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig, - FunctionRefreshPodResources as LanceFunctionRefreshPodResources, - FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref, - Table as LanceDbTable, + FunctionRefreshPodResources as LanceFunctionRefreshPodResources, NewColumnTransform, Ref, + Table as LanceDbTable, TableDelta as LanceDbTableDelta, }; use napi::Env; use napi::bindgen_prelude::*; @@ -20,13 +20,56 @@ use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; -use crate::error::NapiErrorExt; +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 { @@ -84,6 +127,57 @@ impl CompactionOptions { } } +/// 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 @@ -298,6 +392,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()); @@ -581,9 +709,11 @@ impl Table { }) .transpose()?; let request = lancedb::function::FunctionErrorsRequest { + history: false, job_id: options.job_id, column: options.column, limit, + page_token: options.page_token, }; let errors = self .inner_ref()? @@ -643,10 +773,16 @@ impl Table { } #[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 @@ -658,6 +794,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()) } @@ -777,6 +937,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() @@ -846,6 +1037,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()? @@ -893,6 +1097,50 @@ 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, @@ -1693,18 +1941,8 @@ pub struct FunctionErrorsOptions { pub column: Option, /// At most this many records (server default 10000, cap 100000). pub limit: Option, -} - -/// Aggregate worker resources for one Enterprise Function refresh. -#[napi(object)] -#[derive(Clone, Debug)] -pub struct FunctionWorkerResourceBudget { - /// Aggregate CPU budget in millicores; 1000 is one CPU. - pub cpu_millis: f64, - /// Aggregate memory budget in bytes. - pub memory_bytes: f64, - /// Aggregate GPU budget. Omitted means zero, a CPU-only refresh. - pub gpu_count: Option, + /// Empty starts retained history, including repaired rows, for an exact jobId; otherwise continue that page. + pub page_token: Option, } /// CPU, memory, and ephemeral-storage limits for one Function refresh @@ -1769,18 +2007,6 @@ fn positive_safe_integer(value: f64, name: &str) -> napi::Result { Ok(value as u64) } -fn resource_budget_gpu_count(value: Option) -> napi::Result { - let Some(value) = value else { - return Ok(0); - }; - if !value.is_finite() || value.fract() != 0.0 || !(0.0..=u32::MAX as f64).contains(&value) { - return Err(napi::Error::from_reason( - "resourceBudget.gpuCount must be an integer between 0 and 4294967295", - )); - } - Ok(value as u32) -} - fn positive_u32(value: Option, name: &str) -> napi::Result> { value .map(|value| { @@ -1799,8 +2025,7 @@ fn positive_u32(value: Option, name: &str) -> napi::Result> { /// Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every /// option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores -/// `batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including -/// `resourceBudget`. +/// `batchSize`, `gpuClass` and `totalGpuCount` and rejects the rest. #[napi(object)] #[derive(Clone, Debug, Default)] pub struct RefreshColumnOptions { @@ -1819,15 +2044,18 @@ pub struct RefreshColumnOptions { pub max_concurrency: Option, /// GPU class for Function workers. pub gpu_class: Option, - /// Complete aggregate CPU and memory budget for a registered Function - /// refresh. `gpuCount` inside the budget defaults to zero. - pub resource_budget: 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, - /// Positive aggregate GPU budget for Function workers. - pub gpu_count: 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"` (default) stops on a row error; `"skip"` writes null and @@ -1862,17 +2090,14 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { .transpose()?; options.max_concurrency = positive_u32(value.max_concurrency, "maxConcurrency")?; options.gpu_class = value.gpu_class; - options.resource_budget = value - .resource_budget - .map(|budget| { - Ok::<_, napi::Error>( - LanceFunctionWorkerResourceBudget::new( - positive_safe_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?, - positive_safe_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?, - ) - .with_gpu_count(resource_budget_gpu_count(budget.gpu_count)?), - ) - }) + 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 @@ -1926,7 +2151,20 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { )) }) .transpose()?; - options.gpu_count = value.gpu_count; + 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 { @@ -2052,6 +2290,8 @@ pub struct FunctionErrors { 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. @@ -2170,6 +2410,7 @@ impl From for FunctionErrors { 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, } } } @@ -2268,6 +2509,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, @@ -2306,12 +2625,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() } @@ -2369,7 +2696,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| { @@ -2378,13 +2716,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] @@ -2432,3 +2784,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/Cargo.toml b/python/Cargo.toml index 9ae588fc1..d437f998c 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.18" +version = "0.42.0-beta.22" publish = false edition.workspace = true description = "Python bindings for LanceDB" @@ -53,7 +53,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/pyproject.toml b/python/pyproject.toml
        index ff64d9772..6e43633d6 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"
         keywords = [
        -    "data-format",
        -    "data-science",
        -    "machine-learning",
        -    "arrow",
        -    "data-analytics",
        +    "lance",
        +    "vector-search",
        +    "full-text-search",
        +    "dataset",
        +    "versioning",
         ]
         classifiers = [
             "Development Status :: 3 - Alpha",
        @@ -64,7 +64,7 @@ tests = [
             "polars>=0.19, <=1.32.3",
             "pyarrow>=16",
             "pyarrow-stubs>=16.0",
        -    "pylance==15.0.0b25",
        +    "pylance==15.0.0b26",
             "requests>=2.31.0",
             "datafusion>=54,<55",
             "opentelemetry-sdk>=1.30.0",
        diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py
        index acf25d35c..e368c985d 100644
        --- a/python/python/lancedb/__init__.py
        +++ b/python/python/lancedb/__init__.py
        @@ -29,7 +29,6 @@ from ._lancedb import (
         )
         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
        @@ -39,13 +38,18 @@ 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,
        @@ -75,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 (
        @@ -678,6 +683,11 @@ __all__ = [
             "FunctionColumnLastRefreshJob",
             "FunctionColumnStatus",
             "FunctionColumnVersionStatus",
        +    "FunctionErrors",
        +    "AsyncFunctionErrors",
        +    "FunctionErrorGroup",
        +    "FunctionProvenance",
        +    "FunctionValueProvenance",
             "col",
             "Expr",
             "func",
        @@ -686,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 fc1925ca6..77d9877e7 100644
        --- a/python/python/lancedb/_blob.py
        +++ b/python/python/lancedb/_blob.py
        @@ -7,7 +7,9 @@ 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
        @@ -30,10 +32,47 @@ 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:
        @@ -376,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}"
             )
         
         
        @@ -417,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}"
             )
         
         
        @@ -638,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(
        @@ -662,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/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi
        index 63d442703..12bd81fdd 100644
        --- a/python/python/lancedb/_lancedb.pyi
        +++ b/python/python/lancedb/_lancedb.pyi
        @@ -26,6 +26,7 @@ from .index import (
             Fm,
             NGram,
             ZoneMap,
        +    RTree,
             HnswPq,
             HnswSq,
             HnswFlat,
        @@ -323,6 +324,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(
        @@ -333,6 +337,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,
        @@ -342,6 +349,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,
        @@ -379,6 +388,11 @@ class Connection(object):
                 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,
        @@ -393,6 +407,11 @@ class Connection(object):
                 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,
        @@ -433,6 +452,20 @@ class BlobFile:
             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
        @@ -447,14 +480,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:
        @@ -469,6 +522,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: ...
        @@ -519,6 +584,18 @@ class JobFailureInfo:
             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
        @@ -568,6 +645,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,
        @@ -603,6 +681,7 @@ class Table:
                     Fm,
                     NGram,
                     ZoneMap,
        +            RTree,
                     FTS,
                 ],
                 replace: Optional[bool],
        @@ -628,6 +707,7 @@ class Table:
                     Fm,
                     NGram,
                     ZoneMap,
        +            RTree,
                     FTS,
                 ],
                 replace: Optional[bool],
        @@ -639,11 +719,33 @@ class Table:
             ) -> 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,
        @@ -662,7 +764,11 @@ class Table:
                 columns: list[tuple[str, str]],
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[int] = None,
        -        auto_refresh_resource_budget: Optional[dict[str, 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,
        @@ -670,7 +776,11 @@ class Table:
                 output_name: Optional[str],
                 auto_refresh_enabled: Optional[bool] = None,
                 auto_refresh_interval_seconds: Optional[int] = None,
        -        auto_refresh_resource_budget: Optional[dict[str, 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,
        @@ -680,11 +790,13 @@ class Table:
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[dict[str, 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,
        @@ -692,7 +804,14 @@ class Table:
                 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,
        @@ -702,11 +821,13 @@ class Table:
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[dict[str, 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,
        @@ -714,14 +835,40 @@ class Table:
                 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]: ...
        @@ -734,20 +881,22 @@ class Table:
                 source_version: Optional[int] = None,
                 *,
                 full: bool = False,
        -        cpu_millis: Optional[int] = None,
        -        memory_bytes: Optional[int] = None,
        -        gpu_count: 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: ...
             async def refresh_materialized_view_async(
                 self,
                 source_version: Optional[int] = None,
                 *,
                 full: bool = False,
        -        cpu_millis: Optional[int] = None,
        -        memory_bytes: Optional[int] = None,
        -        gpu_count: 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: ...
             async def materialized_view_definition(self) -> str: ...
             async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ...
        @@ -757,6 +906,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,
                 *,
        @@ -805,7 +959,13 @@ class Table:
                 requests: Sequence[Sequence[int]],
             ) -> pa.LargeBinaryArray: ...
             async def fetch_blob_files(
        -        self, column: str, row_ids: list[int], buffer_size: Optional[int] = None
        +        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, buffer_size: Optional[int] = None
        @@ -815,7 +975,7 @@ class Table:
         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): ...
         
        @@ -826,6 +986,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: ...
        @@ -886,11 +1048,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): ...
        @@ -906,10 +1083,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
        @@ -919,9 +1106,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
        @@ -948,6 +1139,12 @@ class FTSQuery:
             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
        @@ -957,6 +1154,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]]): ...
        @@ -1017,6 +1220,7 @@ class PyQueryRequest:
             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]]]
        @@ -1040,6 +1244,7 @@ class PyQueryRequest:
             postfilter: Optional[bool]
             norm: Optional[str]
             order_by: Optional[List[ColumnOrdering]]
        +    scan_in_order: Optional[bool]
         
         class CompactionStats:
             fragments_removed: int
        @@ -1127,8 +1332,13 @@ 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]
        @@ -1150,6 +1360,10 @@ 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
        @@ -1222,7 +1436,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,
        @@ -1245,6 +1464,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(
        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/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 8c9901aff..9efee4393 100644
        --- a/python/python/lancedb/db.py
        +++ b/python/python/lancedb/db.py
        @@ -118,6 +118,7 @@ from .namespace_utils import (
             _normalize_drop_namespace_mode,
             _normalize_drop_namespace_behavior,
         )
        +from .resources import _resource_options
         
         
         def _view_description(
        @@ -507,6 +508,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.
         
        @@ -570,6 +573,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
        @@ -745,6 +765,11 @@ class DBConnection(EnforceOverrides):
                 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``.
         
        @@ -788,6 +813,14 @@ 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
        @@ -799,6 +832,13 @@ class DBConnection(EnforceOverrides):
                 ...     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",
        @@ -819,6 +859,11 @@ class DBConnection(EnforceOverrides):
                 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.
         
        @@ -835,6 +880,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",
        @@ -1562,7 +1614,7 @@ class DBConnection(EnforceOverrides):
                 [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.refresh()``.
        +        ``job.result()`` after ``job.checkout_latest()``.
         
                 Raises `JobNotFoundError` when the server has no such job, the way
                 `open_table` does for a missing table.
        @@ -1698,6 +1750,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,
             ) -> pa.RecordBatchReader:
                 """Execute SQL and return a blocking Arrow reader.
         
        @@ -1712,6 +1767,9 @@ class DBConnection(EnforceOverrides):
                     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(
        @@ -1720,6 +1778,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.
         
        @@ -1738,17 +1799,31 @@ 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.
                 """
                 raise NotImplementedError(
        @@ -1933,11 +2008,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)
        @@ -2124,6 +2228,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.
         
        @@ -2154,6 +2260,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
         
        @@ -2165,6 +2273,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:
        @@ -2177,6 +2286,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.
        @@ -2210,6 +2323,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 (
        @@ -2241,6 +2355,11 @@ class LanceDBConnection(DBConnection):
                 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``.
         
        @@ -2268,6 +2387,13 @@ 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,
        @@ -2280,6 +2406,11 @@ class LanceDBConnection(DBConnection):
                         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))
        @@ -2298,7 +2429,19 @@ class LanceDBConnection(DBConnection):
                 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,
        @@ -2311,6 +2454,11 @@ class LanceDBConnection(DBConnection):
                         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)
        @@ -3258,6 +3406,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.
         
        @@ -3315,6 +3465,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
                 -------
        @@ -3426,6 +3593,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:
        @@ -3472,6 +3658,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)
        @@ -3483,6 +3670,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)
        @@ -3589,6 +3778,11 @@ class AsyncConnection(object):
                 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``.
         
        @@ -3601,6 +3795,13 @@ class AsyncConnection(object):
                 See
                 [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view].
                 """
        +        _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(
        @@ -3620,7 +3821,12 @@ class AsyncConnection(object):
                     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))
         
        @@ -3637,6 +3843,11 @@ class AsyncConnection(object):
                 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.
         
        @@ -3647,6 +3858,13 @@ class AsyncConnection(object):
                 Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id``
                 identifies that query on this connection.
                 """
        +        _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(
        @@ -3666,7 +3884,12 @@ class AsyncConnection(object):
                     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)
         
        @@ -4528,6 +4751,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,
             ) -> AsyncRecordBatchReader:
                 """Execute SQL and return an asynchronous Arrow reader.
         
        @@ -4542,6 +4768,9 @@ class AsyncConnection(object):
                     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()
         
        @@ -4551,6 +4780,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.
         
        @@ -4558,6 +4790,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(
        @@ -4565,6 +4802,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/functions.py b/python/python/lancedb/functions.py
        index 9178d5194..ba7241ceb 100644
        --- a/python/python/lancedb/functions.py
        +++ b/python/python/lancedb/functions.py
        @@ -16,6 +16,7 @@ import builtins
         import base64
         import functools
         import hashlib
        +import importlib.metadata
         import importlib.util
         import inspect
         import symtable
        @@ -64,15 +65,13 @@ from .schema import is_blob_v2_field as _is_blob_v2_field
         from ._blob_reader import BlobReader
         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:
        @@ -81,16 +80,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]:
        @@ -451,8 +458,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
        @@ -461,6 +470,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
        @@ -498,6 +508,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")
        @@ -511,6 +523,7 @@ 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
        @@ -712,8 +725,9 @@ class FunctionVersion(_RemoteValue):
             version also requires matching the source and all other registration inputs,
             including signature, Secret bindings, models, and execution controls.
         
        -    ``gpu_class`` is the operator-defined GPU pool fixed into this Function
        -    version, or ``None`` when registration used the deployment default.
        +    ``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
        @@ -748,6 +762,9 @@ class FunctionVersion(_RemoteValue):
             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[PythonRuntimeSpec] = None
        @@ -940,6 +957,9 @@ class FunctionRegistrationRequest(_RemoteValue):
             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, ...] = ()
        @@ -1132,6 +1152,221 @@ 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.
         
        @@ -1169,6 +1404,8 @@ class RefreshColumnResult(_RemoteValue):
             """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
        @@ -1898,6 +2135,17 @@ def _python_extension_type(data_type: pa.DataType) -> Optional[pa.ExtensionType]
         _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.
        @@ -1912,28 +2160,170 @@ _NAMESPACE_HELPER_HINT = (
         )
         
         
        +_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. " + _NAMESPACE_HELPER_HINT
        +        "Function's reconstructed module namespace. "
        +        + _APPROVED_NAMESPACE_HINT
        +        + _NAMESPACE_HELPER_HINT
             )
         
         
        -def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]:
        -    found: set[str] = set()
        +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]:
        @@ -2246,14 +2636,21 @@ class _SourcePackager:
                         "Function's reconstructed module namespace. Reference dependencies "
                         "explicitly. " + _NAMESPACE_HELPER_HINT
                     )
        -        namespace_imports = _namespace_imports(definition)
        -        if namespace_imports:
        -            raise _namespace_import_error(namespace_imports)
        +        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)
        +            self._bind(reader_name, BlobReader, definition=definition)
                 unresolved = []
                 for name in sorted(references):
                     if name == target.__name__:
        @@ -2265,7 +2662,7 @@ class _SourcePackager:
                             )
                         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:
        @@ -2320,7 +2717,13 @@ class _SourcePackager:
                         "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(
        @@ -2331,14 +2734,23 @@ class _SourcePackager:
                         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 captured
                 copy otherwise."""
        +        approved = _approved_global_namespace_binding(definition, name, value)
        +        if approved is not None:
        +            return approved
                 if value is BlobReader:
                     return f"from lance_blob import BlobReader as {name}"
                 if isinstance(value, types.ModuleType):
        @@ -2790,6 +3202,12 @@ class FunctionDefinition:
             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
        @@ -2814,8 +3232,12 @@ class FunctionDefinition:
                 max_concurrency: Optional[int] = None,
                 row_timeout_seconds: Optional[float] = None,
                 retry_policy: Optional[FunctionRetryPolicy] = None,
        -        gpu: bool = False,
        +        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, ...] = (),
        @@ -2836,11 +3258,9 @@ class FunctionDefinition:
                 if conda_channels and not conda:
                     raise ValueError("conda_channels requires conda packages")
                 _validate_package_requirements("conda" if conda else "pip", conda or pip)
        -        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")
        +        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(
        @@ -2958,6 +3378,7 @@ class FunctionDefinition:
                     env=environment,
                     gpu=gpu_marker,
                     gpu_class=gpu_class,
        +            gpus_per_worker=gpus_per_worker,
                 )
                 self._function = function
                 self._request = FunctionRegistrationRequest(
        @@ -2979,6 +3400,9 @@ class FunctionDefinition:
                     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,
        @@ -3059,6 +3483,16 @@ class FunctionDefinition:
                 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)
         
         
        @@ -3080,8 +3514,12 @@ def function(
             max_concurrency: Optional[int] = None,
             row_timeout_seconds: Optional[float] = None,
             retry_policy: Optional[FunctionRetryPolicy] = None,
        -    gpu: bool = False,
        +    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] = (),
        @@ -3104,8 +3542,12 @@ def function(
             max_concurrency: Optional[int] = None,
             row_timeout_seconds: Optional[float] = None,
             retry_policy: Optional[FunctionRetryPolicy] = None,
        -    gpu: bool = False,
        +    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] = (),
        @@ -3149,7 +3591,12 @@ def function(
             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,
        @@ -3224,20 +3671,25 @@ def function(
             values, such as instances of your own classes, inside the function or
             class body as well.
         
        -    **Namespace restrictions.** The packaged source cannot import ``sys``,
        +    **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`` and ``importlib.metadata``.
        -    Referencing a module-level alias for one of these modules 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`` are 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.
        +    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
        @@ -3306,22 +3758,37 @@ def function(
                 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.
        +        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, 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.
        +    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 shipped with the Function and importable
                 by their own names. Package resources, including binary data and
        @@ -3365,13 +3832,13 @@ def function(
             ...     return value
             >>> batch_identity(pa.array([1, 2, 3])).to_pylist()
             [1, 2, 3]
        -    >>> @function(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'
        +    >>> gpu_score.registration_request.runtime.gpus_per_worker
        +    2
             >>> @function
             ... class scale:
             ...     def __init__(self, factor: float, offset: float = 0.0):
        @@ -3406,7 +3873,10 @@ def function(
             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)
        @@ -3445,6 +3915,10 @@ def function(
                     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),
        @@ -3487,12 +3961,21 @@ __all__ = [
             "ResolvedEnvironmentProvenance",
             "ResolvedPackage",
             "RefreshColumnResult",
        +    "FunctionErrors",
        +    "AsyncFunctionErrors",
        +    "FunctionErrorGroup",
        +    "FunctionProvenance",
        +    "FunctionValueProvenance",
             "FunctionDefinition",
         ]
         
         
         def udf(*args: Any, **kwargs: Any) -> Any:
        -    """Deprecated alias of :func:`function`."""
        +    """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,
        diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py
        index f1626c540..321a1b151 100644
        --- a/python/python/lancedb/index.py
        +++ b/python/python/lancedb/index.py
        @@ -147,6 +147,45 @@ class ZoneMap:
             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 FTS:
             """Describe a FTS index configuration.
        @@ -1001,4 +1040,5 @@ __all__ = [
             "LabelList",
             "Fm",
             "NGram",
        +    "RTree",
         ]
        diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py
        index e49609e1f..778d44e2b 100644
        --- a/python/python/lancedb/job.py
        +++ b/python/python/lancedb/job.py
        @@ -4,14 +4,26 @@
         """Handles to asynchronous registry jobs, SQL queries, and local operations."""
         
         import asyncio
        +import json
         import logging
         import reprlib
         import time
         from contextlib import suppress
         from datetime import timedelta
        +from enum import Enum
         from os import PathLike
         from pathlib import Path
        -from typing import Any, Callable, Generic, Optional, TypeVar, cast
        +from typing import (
        +    Any,
        +    AsyncIterator,
        +    Callable,
        +    Generic,
        +    Iterator,
        +    Optional,
        +    TypeVar,
        +    cast,
        +)
        +from uuid import uuid4
         
         import pyarrow as pa
         
        @@ -20,6 +32,10 @@ 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")
        @@ -30,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:
        @@ -41,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 (
        @@ -147,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 (
        @@ -172,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
        @@ -198,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__(
        @@ -209,26 +294,31 @@ class AsyncJob(Generic[T]):
                 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
        @@ -238,6 +328,54 @@ 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.
         
        @@ -247,17 +385,16 @@ class AsyncJob(Generic[T]):
                 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
                 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":
        +            if self.job_type() == "query":
                         return {
        -                    "job_id": self.id,
        +                    "job_id": self.id(),
                             "job_type": "query",
                             "state": state,
                             "client_elapsed_time_millis": int(
        @@ -286,6 +423,10 @@ 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
        @@ -311,7 +452,9 @@ class AsyncJob(Generic[T]):
                 if self._inner is None:
                     return cast(T, None)
                 query_progress = (
        -            progress is not False and progress is not None and self.job_type == "query"
        +            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)
        @@ -385,15 +528,15 @@ class AsyncJob(Generic[T]):
                             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."
        @@ -415,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
        @@ -429,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
        @@ -486,6 +688,146 @@ 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.
         
        @@ -542,10 +884,15 @@ class AsyncJob(Generic[T]):
                 *,
                 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
        @@ -569,7 +916,29 @@ 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)
        @@ -597,49 +966,113 @@ def _repr_payload(value: Any) -> str:
         def _job_repr(kind: str, job: Any) -> str:
             """Show cached job identity and bounded previews without backend calls.
         
        -    The complete payloads remain available through ``spec`` and ``result``.
        +    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={_repr_payload(job.id)}, " 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={_repr_payload(job.id)}")
        +    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)
        +        value = getattr(job, name)()
                 if value is not None:
                     fields.append(f"{name}={_repr_payload(value)}")
             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={_repr_payload(job.failure)}")
        +    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`.
                 """
        @@ -686,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.
         
        @@ -695,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]:
        @@ -736,6 +1225,109 @@ 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.
         
        @@ -772,6 +1364,7 @@ class Job(Generic[T]):
                 *,
                 limit: Optional[int] = None,
                 filter: Optional[str] = None,
        +        page_token: Optional[str] = None,
             ) -> "pa.Table":
                 """This job's recorded lifecycle events.
         
        @@ -784,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)
        @@ -798,6 +1404,12 @@ def _typed_job(
         
         
         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/materialized_view.py b/python/python/lancedb/materialized_view.py
        index dc04f89f8..28f7d9401 100644
        --- a/python/python/lancedb/materialized_view.py
        +++ b/python/python/lancedb/materialized_view.py
        @@ -17,9 +17,9 @@ from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union
         import json
         from dataclasses import dataclass
         
        -from .functions import _validate_gpu_class_name
         from .background_loop import LOOP
         from .job import AsyncJob, Job, _typed_job
        +from .resources import _resource_options
         
         if TYPE_CHECKING:
             import pyarrow as pa
        @@ -167,31 +167,16 @@ def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
             return normalized
         
         
        -def _refresh_execution_options(cpu_millis, memory_bytes, gpu_count, gpu_class):
        -    values = {
        -        "cpu_millis": cpu_millis,
        -        "memory_bytes": memory_bytes,
        -        "gpu_count": gpu_count,
        -    }
        -    for name, value in values.items():
        -        maximum = 2**32 - 1 if name == "gpu_count" else 2**64 - 1
        -        minimum = 0 if name == "gpu_count" else 1
        -        if value is not None and (
        -            type(value) is not int or not minimum <= value <= maximum
        -        ):
        -            raise ValueError(
        -                f"{name} must be an integer between {minimum} and {maximum}"
        -            )
        -    if (cpu_millis is not None or memory_bytes is not None) and any(
        -        value is None for value in values.values()
        -    ):
        -        raise ValueError(
        -            "cpu_millis, memory_bytes, and gpu_count must be specified together"
        -        )
        -    if gpu_class is not None:
        -        values["gpu_class"] = _validate_gpu_class_name(gpu_class)
        -        if gpu_count == 0:
        -            raise ValueError("gpu_class requires a positive GPU budget")
        +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}
         
         
        @@ -228,10 +213,11 @@ class AsyncMaterializedView:
                 *,
                 full: bool = False,
                 source_version: Optional[int] = None,
        -        cpu_millis: Optional[int] = None,
        -        memory_bytes: Optional[int] = None,
        -        gpu_count: 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.
         
        @@ -240,11 +226,14 @@ class AsyncMaterializedView:
                 and ``source_version`` selects a source version instead of the latest.
                 LanceDB Enterprise SQL refreshes do not support source-version pinning.
         
        -        ``cpu_millis`` (1000 = one core), ``memory_bytes``, and ``gpu_count``
        -        cap aggregate resources for this execution, including its Function
        -        processes. CPU or memory requires all three budget fields; 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.
        +        ``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.
         
        @@ -256,7 +245,11 @@ class AsyncMaterializedView:
                     source_version=source_version,
                     full=full,
                     **_refresh_execution_options(
        -                cpu_millis, memory_bytes, gpu_count, gpu_class
        +                total_cpu_millis,
        +                total_memory_bytes,
        +                total_gpu_count,
        +                gpu_class,
        +                gpu_count=gpu_count,
                     ),
                 )
         
        @@ -265,10 +258,11 @@ class AsyncMaterializedView:
                 *,
                 full: bool = False,
                 source_version: Optional[int] = None,
        -        cpu_millis: Optional[int] = None,
        -        memory_bytes: Optional[int] = None,
        -        gpu_count: 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.
         
        @@ -289,7 +283,11 @@ class AsyncMaterializedView:
                         source_version=source_version,
                         full=full,
                         **_refresh_execution_options(
        -                    cpu_millis, memory_bytes, gpu_count, gpu_class
        +                    total_cpu_millis,
        +                    total_memory_bytes,
        +                    total_gpu_count,
        +                    gpu_class,
        +                    gpu_count=gpu_count,
                         ),
                     ),
                     RefreshMaterializedViewResult.from_json,
        @@ -326,10 +324,11 @@ class MaterializedView:
                 *,
                 full: bool = False,
                 source_version: Optional[int] = None,
        -        cpu_millis: Optional[int] = None,
        -        memory_bytes: Optional[int] = None,
        -        gpu_count: 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]."""
        @@ -338,7 +337,11 @@ class MaterializedView:
                         full=full,
                         source_version=source_version,
                         **_refresh_execution_options(
        -                    cpu_millis, memory_bytes, gpu_count, gpu_class
        +                    total_cpu_millis,
        +                    total_memory_bytes,
        +                    total_gpu_count,
        +                    gpu_class,
        +                    gpu_count=gpu_count,
                         ),
                     )
                 )
        @@ -348,10 +351,11 @@ class MaterializedView:
                 *,
                 full: bool = False,
                 source_version: Optional[int] = None,
        -        cpu_millis: Optional[int] = None,
        -        memory_bytes: Optional[int] = None,
        -        gpu_count: 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.
         
        @@ -364,7 +368,11 @@ class MaterializedView:
                             full=full,
                             source_version=source_version,
                             **_refresh_execution_options(
        -                        cpu_millis, memory_bytes, gpu_count, gpu_class
        +                        total_cpu_millis,
        +                        total_memory_bytes,
        +                        total_gpu_count,
        +                        gpu_class,
        +                        gpu_count=gpu_count,
                             ),
                         )
                     )
        diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py
        index 463536619..bee9576c2 100644
        --- a/python/python/lancedb/namespace.py
        +++ b/python/python/lancedb/namespace.py
        @@ -509,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.
         
        @@ -584,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
                         ),
                     }
        @@ -640,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 = []
        @@ -661,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,
                     )
                 )
         
        @@ -668,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,
        @@ -706,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,
        @@ -730,6 +738,11 @@ class LanceNamespaceDBConnection(DBConnection):
                 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.
        @@ -749,7 +762,12 @@ class LanceNamespaceDBConnection(DBConnection):
                                 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
                     )
        @@ -768,6 +786,11 @@ class LanceNamespaceDBConnection(DBConnection):
                 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(
        @@ -781,7 +804,12 @@ class LanceNamespaceDBConnection(DBConnection):
                         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)
        @@ -1132,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,
        @@ -1205,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.
         
        @@ -1302,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:
        @@ -1323,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,
        @@ -1381,6 +1416,11 @@ class AsyncLanceNamespaceDBConnection:
                 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."""
        @@ -1394,7 +1434,12 @@ class AsyncLanceNamespaceDBConnection:
                     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.
        @@ -1412,6 +1457,11 @@ class AsyncLanceNamespaceDBConnection:
                 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."""
        @@ -1425,7 +1475,12 @@ class AsyncLanceNamespaceDBConnection:
                     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":
        @@ -1717,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(
        @@ -1731,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.
         
        @@ -1740,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:
        @@ -1808,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.
         
        @@ -1899,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..ff1cf7b59 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())
         
        @@ -406,10 +513,17 @@ class Transforms:
         DEFAULT_BATCH_SIZE = 100
         
         
        +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 +532,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 +553,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 +604,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
        @@ -499,6 +623,9 @@ class Permutation:
                 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 +765,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 +783,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 +806,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 +828,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,18 +840,43 @@ 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,
        @@ -716,17 +885,13 @@ class Permutation:
                     "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,17 +923,32 @@ 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"]
        @@ -779,6 +959,58 @@ class Permutation:
                 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 +1240,7 @@ class Permutation:
                     "pandas",
                     "arrow",
                     "torch",
        +            "torch_dict",
                     "torch_row",
                     "torch_col",
                     "polars",
        @@ -1019,28 +1252,54 @@ 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
        @@ -1059,6 +1318,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":
        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 214d2255f..93f84aeca 100644
        --- a/python/python/lancedb/query.py
        +++ b/python/python/lancedb/query.py
        @@ -4,7 +4,6 @@
         from __future__ import annotations
         
         import asyncio
        -import re
         from abc import ABC, abstractmethod
         from concurrent.futures import ThreadPoolExecutor
         from datetime import timedelta
        @@ -48,6 +47,7 @@ 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,
        @@ -205,25 +205,6 @@ def _supports_blob_fetch(
             )
         
         
        -def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]:
        -    value = (schema.metadata or {}).get(b"lancedb:query_version", b"")
        -    if not value.isdigit() or not 0 < int(value) < 2**64:
        -        raise NotImplementedError(
        -            "blob_mode='bytes' 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(b"lancedb:query_snapshot", b"")
        -    if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
        -        raise NotImplementedError(
        -            "blob_mode='bytes' 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")
        -
        -
         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")
        @@ -273,6 +254,24 @@ 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
        @@ -372,6 +371,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,
             }
        @@ -382,6 +385,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
        @@ -571,11 +580,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"
        @@ -1010,6 +1115,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
         
        @@ -1088,6 +1196,9 @@ class Query(pydantic.BaseModel):
             # 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
         
        @@ -1107,6 +1218,10 @@ 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()
        @@ -1114,6 +1229,7 @@ class Query(pydantic.BaseModel):
                 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
        @@ -1139,6 +1255,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,
        @@ -1313,6 +1430,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",
        @@ -1647,6 +1765,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
        @@ -1671,22 +1793,109 @@ 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, blob_sources: Optional[dict[str, str]] = None) -> 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() or blob_sources:
        +        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 _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
        @@ -1705,13 +1914,18 @@ class LanceQueryBuilder(ABC):
                     )
                 )
         
        -    def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
        +    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
        +        if blob_mode == "lazy":
        +            return {}
        +        if schema is None:
        +            schema = self._table.schema
                 blob_sources = blob_projection_sources(
                     schema,
                     self._columns,
        @@ -1759,8 +1973,9 @@ 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()
        +        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.
        @@ -1788,22 +2003,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.
        @@ -1822,12 +2041,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
         
        @@ -1883,24 +2143,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(
        @@ -1957,6 +2233,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
                 )
        @@ -2384,11 +2661,37 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
                     ``"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:
        @@ -2428,6 +2731,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,
                 /,
        @@ -2456,25 +2784,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(blob_sources)
        -        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)
        -            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)
         
             def where(
                 self, where: Union[str, Expr], prefilter: bool = None
        @@ -2625,6 +2942,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
                 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)
        @@ -2709,18 +3027,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(blob_sources)
        -        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(
        @@ -2759,15 +3084,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(timeout=timeout, blob_mode=blob_mode).read_all()
        +            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,
        @@ -2780,6 +3175,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:
        @@ -2794,12 +3190,14 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
                 *,
                 blob_mode: BlobMode = "lazy",
             ) -> pa.RecordBatchReader:
        -        blob_sources = self._validated_blob_sources(blob_mode)
        -        query = self._query_for_scan(blob_sources)
        -        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.
        @@ -2858,6 +3256,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(
        @@ -2921,11 +3342,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,
        @@ -2938,6 +3362,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
        @@ -2967,7 +3392,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
                 )
                 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(
        @@ -2976,6 +3404,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(
        @@ -2983,9 +3412,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.
        @@ -3518,6 +3950,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
                 )
        @@ -3618,6 +4051,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:
                 """
        @@ -3636,6 +4071,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
         
        @@ -3667,6 +4115,26 @@ 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
        @@ -3746,15 +4214,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
        @@ -3827,6 +4312,30 @@ 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,
                 *,
        @@ -3834,6 +4343,7 @@ class AsyncQueryBase(object):
                 timeout: Optional[timedelta] = None,
                 blob_sources: Optional[dict[str, str]] = None,
             ) -> AsyncRecordBatchReader:
        +        self._ensure_fragment_constraints_supported("to_batches()")
                 if (
                     blob_sources
                     and not self._user_requested_row_id()
        @@ -3850,7 +4360,8 @@ class AsyncQueryBase(object):
                         max_batch_length=max_batch_length,
                         timeout=timeout,
                     )
        -        await self._maybe_add_blob_row_id()
        +        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
        @@ -3951,10 +4462,17 @@ class AsyncQueryBase(object):
                 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)
        -        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 != "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(
        @@ -4241,6 +4759,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(
        @@ -4258,6 +4777,7 @@ class AsyncQueryBase(object):
                 -------
                 plan : str
                 """
        +        self._ensure_fragment_constraints_supported("analyze_plan()")
                 return await self._inner.analyze_plan(distributed_metrics)
         
         
        @@ -4293,9 +4813,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.
        @@ -4328,20 +4850,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:
        @@ -4412,6 +4950,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):
        @@ -4495,11 +5099,17 @@ 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(
        @@ -4539,18 +5149,22 @@ class AsyncQuery(AsyncStandardQuery):
                     columns = []
         
                 if isinstance(query, str):
        -            return AsyncFTSQuery(
        -                self._inner.nearest_to_text(
        -                    {
        -                        "query": query,
        -                        "columns": columns,
        -                        "operator": fts_query.operator,
        -                    }
        -                ),
        -                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):
        @@ -4571,6 +5185,7 @@ class AsyncFTSQuery(AsyncStandardQuery):
                 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:
        @@ -4656,12 +5271,50 @@ 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,
        @@ -4996,17 +5649,47 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
                     columns = []
         
                 if isinstance(query, str):
        -            return AsyncHybridQuery(
        -                self._inner.nearest_to_text(
        -                    {"query": query, "columns": columns, "operator": fts_query.operator}
        -                ),
        -                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,
                 *,
        @@ -5015,8 +5698,12 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
                 blob_sources: Optional[dict[str, str]] = None,
             ) -> AsyncRecordBatchReader:
                 reader = await super()._execute_batches(
        -            timeout=timeout, blob_sources=blob_sources
        +            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
        @@ -5092,6 +5779,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)
         
        @@ -5141,6 +5829,15 @@ 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,
                 *,
        @@ -5388,15 +6085,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
        diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py
        index 2927f2726..bf2f5669f 100644
        --- a/python/python/lancedb/remote/db.py
        +++ b/python/python/lancedb/remote/db.py
        @@ -62,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]:
        @@ -641,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.
         
        @@ -686,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
                 -------
        @@ -761,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"
        @@ -806,7 +823,19 @@ class RemoteDBConnection(DBConnection):
                 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(
        @@ -821,6 +850,11 @@ class RemoteDBConnection(DBConnection):
                         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(
        @@ -846,7 +880,19 @@ class RemoteDBConnection(DBConnection):
                 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,
        @@ -859,6 +905,11 @@ class RemoteDBConnection(DBConnection):
                         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)
        @@ -1405,6 +1456,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.
         
        @@ -1420,6 +1474,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/table.py b/python/python/lancedb/remote/table.py
        index 2d068536e..715804e4b 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 (
        @@ -48,8 +49,11 @@ 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 (
        +    FunctionProvenance,
             FunctionApplication,
             FunctionRetryPolicy,
             RefreshColumnResult,
        @@ -77,9 +81,11 @@ from ..table import (
             BlobMode,
             Branches,
             CompactionOptions,
        +    CompactionResult,
             IndexStatistics,
             Query,
             Table,
        +    TableDelta,
             Tags,
         )
         from ..types import BaseTokenizerType, ScalarIndexType
        @@ -282,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)
        @@ -600,7 +619,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, FTS.
                 replace : bool, default True
                     Whether to replace an existing index on this column.
                 wait_timeout : timedelta, optional
        @@ -923,6 +942,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))
         
        @@ -1089,7 +1116,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
        @@ -1104,6 +1132,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,
                 *,
        @@ -1152,7 +1200,9 @@ class RemoteTable(Table):
                 computed: Dict[str, str] | None = None,
                 auto_refresh_enabled: bool | None = None,
                 auto_refresh_interval_seconds: int | None = None,
        -        auto_refresh_resource_budget: Optional[Dict[str, int]] = 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(
        @@ -1160,7 +1210,9 @@ class RemoteTable(Table):
                         computed=computed,
                         auto_refresh_enabled=auto_refresh_enabled,
                         auto_refresh_interval_seconds=auto_refresh_interval_seconds,
        -                auto_refresh_resource_budget=auto_refresh_resource_budget,
        +                total_cpu_millis=total_cpu_millis,
        +                total_memory_bytes=total_memory_bytes,
        +                total_gpu_count=total_gpu_count,
                     )
                 )
         
        @@ -1172,11 +1224,12 @@ class RemoteTable(Table):
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[Dict[str, 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,
        @@ -1184,7 +1237,14 @@ class RemoteTable(Table):
                 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(
        @@ -1193,11 +1253,12 @@ class RemoteTable(Table):
                         batch_size=batch_size,
                         max_concurrency=max_concurrency,
                         publication_interval_rows=publication_interval_rows,
        -                resource_budget=resource_budget,
        +                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,
        @@ -1205,7 +1266,14 @@ class RemoteTable(Table):
                         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,
                     )
                 )
         
        @@ -1217,11 +1285,12 @@ class RemoteTable(Table):
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[Dict[str, 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,
        @@ -1229,7 +1298,14 @@ class RemoteTable(Table):
                 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(
        @@ -1239,11 +1315,12 @@ class RemoteTable(Table):
                             batch_size=batch_size,
                             max_concurrency=max_concurrency,
                             publication_interval_rows=publication_interval_rows,
        -                    resource_budget=resource_budget,
        +                    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,
        @@ -1251,19 +1328,67 @@ class RemoteTable(Table):
                             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(
        @@ -1313,7 +1438,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]:
        @@ -1375,7 +1504,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
        @@ -1383,7 +1519,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
        @@ -1394,8 +1531,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)
        @@ -1414,9 +1605,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
        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 5e36ffc86..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):
        @@ -344,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/streaming.py b/python/python/lancedb/streaming.py
        index 810911e28..23a81c135 100644
        --- a/python/python/lancedb/streaming.py
        +++ b/python/python/lancedb/streaming.py
        @@ -30,7 +30,7 @@ import warnings
         from collections import deque
         from concurrent.futures import 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 pyarrow as pa
        @@ -60,6 +60,13 @@ DEFAULT_PREFETCH_BATCHES = 4
         _UNSET = object()
         
         
        +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 _WorkerSample(NamedTuple):
             data: Any
             dataset: "StreamingDataset"
        @@ -1999,6 +2006,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 +2043,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 7f378a34c..fad89db49 100644
        --- a/python/python/lancedb/table.py
        +++ b/python/python/lancedb/table.py
        @@ -46,9 +46,13 @@ from ._blob import (
             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,
        @@ -77,6 +81,7 @@ from .index import (
             Fm,
             NGram,
             ZoneMap,
        +    RTree,
             HnswPq,
             HnswSq,
             HnswFlat,
        @@ -84,6 +89,9 @@ from .index import (
         )
         from .expr import Expr
         from .functions import (
        +    FunctionErrors,
        +    AsyncFunctionErrors,
        +    FunctionProvenance,
             FunctionRetryPolicy,
             FunctionApplication,
             RefreshColumnResult as RefreshColumnJobResult,
        @@ -124,6 +132,7 @@ from .schema import (
             row_addressable_blob_v2_paths,
             schema_has_blob_field,
         )
        +from .resources import _resource_options
         
         
         def _should_push_down_query_table(
        @@ -139,6 +148,12 @@ def _requires_local_namespace_execution(query: Query) -> bool:
                 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
        @@ -292,7 +307,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,
        @@ -300,7 +315,6 @@ if TYPE_CHECKING:
                 CompactionStats,
                 Tag,
                 AddColumnsResult,
        -        FunctionErrors,
                 RefreshColumnResult,
                 AddResult,
                 AlterColumnsResult,
        @@ -339,6 +353,7 @@ IndexConfigType = Union[
             Fm,
             NGram,
             ZoneMap,
        +    RTree,
             FTS,
         ]
         
        @@ -1584,6 +1599,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)
        @@ -1956,7 +2028,7 @@ 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, ZoneMap, FTS.
        +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
                 replace : bool, default True
                     Whether to replace an existing index on this column.
                 exist_ok : bool, default False
        @@ -2009,6 +2081,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,
        @@ -2048,8 +2220,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
         
        @@ -2542,7 +2722,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.
        @@ -2554,9 +2738,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
                 ----------
        @@ -2564,6 +2752,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
                 -------
        @@ -2684,6 +2876,15 @@ 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.
        +
                 Blobs inside lists cannot be fetched by row id yet.
         
                 LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob
        @@ -2750,6 +2951,17 @@ class Table(ABC):
                 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
        @@ -2808,6 +3020,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: ...
         
        @@ -3022,6 +3253,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,
        @@ -3167,7 +3457,11 @@ class Table(ABC):
                 computed: Dict[str, str] | None = None,
                 auto_refresh_enabled: bool | None = None,
                 auto_refresh_interval_seconds: int | None = None,
        -        auto_refresh_resource_budget: Optional[Dict[str, 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,
             ):
                 """
                 Add new columns with defined values.
        @@ -3236,13 +3530,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.
        -        auto_refresh_resource_budget: dict[str, int], optional
        -            Aggregate CPU, memory, and GPU budget for automatic refreshes of a
        -            registered Function declaration. ``cpu_millis`` and
        -            ``memory_bytes`` are required; ``gpu_count`` defaults to zero.
        -            This option cannot be used with SQL-expression columns. LanceDB
        -            Enterprise only.
        -
        +        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
        @@ -3267,6 +3560,13 @@ 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(
        @@ -3277,11 +3577,13 @@ class Table(ABC):
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[Dict[str, 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,
        @@ -3289,7 +3591,14 @@ class Table(ABC):
                 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.
        @@ -3330,13 +3639,10 @@ class Table(ABC):
                     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.
        -        resource_budget: dict[str, int], optional
        -            Aggregate resources for one registered Function refresh. The
        -            ``cpu_millis`` and ``memory_bytes`` keys are required;
        -            ``gpu_count`` is optional and defaults to zero, which requests a
        -            CPU-only budget. This budget cannot be combined with the top-level
        -            ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
        -            reject it.
        +        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
        @@ -3353,11 +3659,10 @@ class Table(ABC):
                     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 without changing
        -            the deployment's CPU and memory defaults. None leaves the server's
        -            configured budget unchanged. For a complete CPU and memory budget,
        -            use ``resource_budget`` instead. 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.
        @@ -3365,6 +3670,9 @@ class Table(ABC):
                 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.
        @@ -3377,11 +3685,31 @@ class Table(ABC):
                     Deadline for Function initialization. LanceDB Enterprise only.
                 num_workers: int, optional
                     Worker count for an expression column; registered Function
        -            columns reject it and use ``resource_budget`` instead. LanceDB
        +            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
                 -------
        @@ -3399,11 +3727,13 @@ class Table(ABC):
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[Dict[str, 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,
        @@ -3411,7 +3741,14 @@ class Table(ABC):
                 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
        @@ -3451,13 +3788,10 @@ class Table(ABC):
                     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.
        -        resource_budget: dict[str, int], optional
        -            Aggregate resources for one registered Function refresh. The
        -            ``cpu_millis`` and ``memory_bytes`` keys are required;
        -            ``gpu_count`` is optional and defaults to zero, which requests a
        -            CPU-only budget. This budget cannot be combined with the top-level
        -            ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
        -            reject it.
        +        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
        @@ -3474,11 +3808,10 @@ class Table(ABC):
                     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 without changing
        -            the deployment's CPU and memory defaults. None leaves the server's
        -            configured budget unchanged. For a complete CPU and memory budget,
        -            use ``resource_budget`` instead. 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.
        @@ -3486,6 +3819,9 @@ class Table(ABC):
                 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.
        @@ -3498,11 +3834,31 @@ class Table(ABC):
                     Deadline for Function initialization. LanceDB Enterprise only.
                 num_workers: int, optional
                     Worker count for an expression column; registered Function
        -            columns reject it and use ``resource_budget`` instead. LanceDB
        +            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
                 -------
        @@ -3525,22 +3881,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
                 ----------
        @@ -3550,6 +3999,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
                 -------
        @@ -3911,7 +4368,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
        @@ -3938,6 +4398,154 @@ 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 _namespace_client_for_pickle(self) -> Optional[Any]:
        +        """Keep a table-level namespace client only when pickle can carry it."""
        +        namespace_client = self._namespace_client
        +        if namespace_client is None:
        +            return None
        +        if namespace_client is getattr(self._conn, "_namespace_client", None):
        +            # The serialized 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
        +
        +        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()}
        +
        +        # 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 {
        +            "kind": "lance",
        +            "connection_state": self._pickle_connection_state(),
        +            "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,
        +            "namespace_client": self._namespace_client_for_pickle(),
        +            "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 __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:
        @@ -3949,10 +4557,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
        @@ -4058,21 +4696,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
        @@ -4173,21 +4832,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.
        @@ -4226,6 +4900,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.
        @@ -4234,6 +4910,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.
        @@ -4282,6 +4960,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))
        @@ -4482,7 +5162,7 @@ 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, ZoneMap, FTS.
        +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
                 replace : bool, default True
                     Whether to replace an existing index on this column.
                 exist_ok : bool, default False
        @@ -4703,7 +5383,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.
         
        @@ -4712,7 +5399,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
        @@ -4723,8 +5411,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)
        @@ -5211,8 +5953,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,
        @@ -5250,6 +6000,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.
        @@ -5303,13 +6055,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
        @@ -5337,6 +6105,7 @@ class LanceTable(Table):
                         enable_v2_manifest_paths
                     ).lower()
         
        +        self._storage_options = storage_options
                 self._table = LOOP.run(
                     self._conn._conn.create_table(
                         name,
        @@ -5351,8 +6120,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:
        @@ -5456,6 +6229,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))
         
        @@ -5543,6 +6365,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,
                 *,
        @@ -5673,15 +6510,30 @@ class LanceTable(Table):
                 computed: Dict[str, str] | None = None,
                 auto_refresh_enabled: bool | None = None,
                 auto_refresh_interval_seconds: int | None = None,
        -        auto_refresh_resource_budget: Optional[Dict[str, 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:
        +        _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,
        -                auto_refresh_resource_budget=auto_refresh_resource_budget,
        +                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,
                     )
                 )
         
        @@ -5693,11 +6545,13 @@ class LanceTable(Table):
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[Dict[str, 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,
        @@ -5705,7 +6559,14 @@ class LanceTable(Table):
                 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
        @@ -5717,11 +6578,12 @@ class LanceTable(Table):
                         batch_size=batch_size,
                         max_concurrency=max_concurrency,
                         publication_interval_rows=publication_interval_rows,
        -                resource_budget=resource_budget,
        +                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,
        @@ -5729,7 +6591,15 @@ class LanceTable(Table):
                         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,
                     )
                 )
         
        @@ -5741,11 +6611,13 @@ class LanceTable(Table):
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[Dict[str, 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,
        @@ -5753,7 +6625,14 @@ class LanceTable(Table):
                 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
        @@ -5767,11 +6646,12 @@ class LanceTable(Table):
                             batch_size=batch_size,
                             max_concurrency=max_concurrency,
                             publication_interval_rows=publication_interval_rows,
        -                    resource_budget=resource_budget,
        +                    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,
        @@ -5779,7 +6659,15 @@ class LanceTable(Table):
                             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,
                         )
                     )
                 )
        @@ -5789,11 +6677,49 @@ 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(
        @@ -5854,8 +6780,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
                 --------
        @@ -6633,8 +7567,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
                 --------
        @@ -6744,6 +7686,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
        @@ -6927,6 +7872,7 @@ class AsyncTable:
                         Fm,
                         NGram,
                         ZoneMap,
        +                RTree,
                         FTS,
                     ]
                 ] = None,
        @@ -7008,13 +7954,14 @@ class AsyncTable:
                             Fm,
                             NGram,
                             ZoneMap,
        +                    RTree,
                             FTS,
                         ),
                     ):
                         raise TypeError(
                             "config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
        -                    " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, or FTS, but got "
        -                    + str(type(config))
        +                    " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, or FTS,"
        +                    " but got " + str(type(config))
                         )
                 try:
                     await self._inner.create_index(
        @@ -7054,6 +8001,7 @@ class AsyncTable:
                         Fm,
                         NGram,
                         ZoneMap,
        +                RTree,
                         FTS,
                     ]
                 ] = None,
        @@ -7127,7 +8075,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.
         
        @@ -7136,7 +8091,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
        @@ -7147,8 +8103,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)
        @@ -7704,10 +8726,18 @@ class AsyncTable:
                 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)
        +                else self.take_offsets(
        +                    query.take_offsets, preserve_order=query.preserve_order is True
        +                )
                     )
                     if query.columns is not None:
                         columns = query.columns
        @@ -7745,6 +8775,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(
        @@ -7811,11 +8843,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)
        @@ -8033,7 +9085,11 @@ class AsyncTable:
                 computed: dict[str, str] | None = None,
                 auto_refresh_enabled: bool | None = None,
                 auto_refresh_interval_seconds: int | None = None,
        -        auto_refresh_resource_budget: Optional[Dict[str, 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:
                 """
                 Add new columns with defined values.
        @@ -8100,13 +9156,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.
        -        auto_refresh_resource_budget: dict[str, int], optional
        -            Aggregate CPU, memory, and GPU budget for automatic refreshes of
        -            registered Function outputs. ``cpu_millis`` and ``memory_bytes``
        -            are required; ``gpu_count`` defaults to zero. SQL-expression
        -            columns do not use Function workers and reject this option.
        -            LanceDB Enterprise only.
        -
        +        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
        @@ -8121,6 +9176,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 (
        @@ -8134,7 +9196,11 @@ class AsyncTable:
                 options_supplied = (
                     auto_refresh_enabled is not None
                     or auto_refresh_interval_seconds is not None
        -            or auto_refresh_resource_budget 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
        @@ -8163,7 +9229,11 @@ class AsyncTable:
                         function_output_name,
                         auto_refresh_enabled,
                         auto_refresh_interval_seconds,
        -                auto_refresh_resource_budget,
        +                total_cpu_millis,
        +                total_memory_bytes,
        +                total_gpu_count,
        +                gpu_class,
        +                gpu_count,
                     )
         
                 if isinstance(transforms, pa.Field):
        @@ -8184,7 +9254,11 @@ class AsyncTable:
                         list(computed.items()),
                         auto_refresh_enabled,
                         auto_refresh_interval_seconds,
        -                auto_refresh_resource_budget,
        +                total_cpu_millis,
        +                total_memory_bytes,
        +                total_gpu_count,
        +                gpu_class,
        +                gpu_count,
                     )
                 if options_supplied:
                     raise ValueError(
        @@ -8208,11 +9282,13 @@ class AsyncTable:
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[Dict[str, 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,
        @@ -8220,7 +9296,14 @@ class AsyncTable:
                 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.
        @@ -8261,13 +9344,10 @@ class AsyncTable:
                     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.
        -        resource_budget: dict[str, int], optional
        -            Aggregate resources for one registered Function refresh. The
        -            ``cpu_millis`` and ``memory_bytes`` keys are required;
        -            ``gpu_count`` is optional and defaults to zero, which requests a
        -            CPU-only budget. This budget cannot be combined with the top-level
        -            ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
        -            reject it.
        +        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
        @@ -8284,11 +9364,10 @@ class AsyncTable:
                     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 without changing
        -            the deployment's CPU and memory defaults. None leaves the server's
        -            configured budget unchanged. For a complete CPU and memory budget,
        -            use ``resource_budget`` instead. 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.
        @@ -8296,6 +9375,9 @@ class AsyncTable:
                 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.
        @@ -8308,28 +9390,56 @@ class AsyncTable:
                     Deadline for Function initialization. LanceDB Enterprise only.
                 num_workers: int, optional
                     Worker count for an expression column; registered Function
        -            columns reject it and use ``resource_budget`` instead. LanceDB
        +            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.
                 """
        +        _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,
        -            resource_budget=resource_budget,
        +            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=None
                     if retry_policy is None
                     else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(),
        @@ -8339,7 +9449,87 @@ class AsyncTable:
                     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(
        @@ -8347,16 +9537,20 @@ class AsyncTable:
                 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
                 ----------
        @@ -8366,10 +9560,18 @@ 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.
         
        @@ -8427,9 +9629,14 @@ 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
        @@ -8465,11 +9672,13 @@ class AsyncTable:
                 batch_size: Optional[int] = None,
                 max_concurrency: Optional[int] = None,
                 publication_interval_rows: Optional[int] = None,
        -        resource_budget: Optional[Dict[str, 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,
        @@ -8477,7 +9686,14 @@ class AsyncTable:
                 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
        @@ -8517,13 +9733,10 @@ class AsyncTable:
                     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.
        -        resource_budget: dict[str, int], optional
        -            Aggregate resources for one registered Function refresh. The
        -            ``cpu_millis`` and ``memory_bytes`` keys are required;
        -            ``gpu_count`` is optional and defaults to zero, which requests a
        -            CPU-only budget. This budget cannot be combined with the top-level
        -            ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
        -            reject it.
        +        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
        @@ -8540,11 +9753,10 @@ class AsyncTable:
                     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 without changing
        -            the deployment's CPU and memory defaults. None leaves the server's
        -            configured budget unchanged. For a complete CPU and memory budget,
        -            use ``resource_budget`` instead. 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.
        @@ -8552,6 +9764,9 @@ class AsyncTable:
                 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.
        @@ -8564,11 +9779,31 @@ class AsyncTable:
                     Deadline for Function initialization. LanceDB Enterprise only.
                 num_workers: int, optional
                     Worker count for an expression column; registered Function
        -            columns reject it and use ``resource_budget`` instead. LanceDB
        +            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
                 -------
        @@ -8591,6 +9826,13 @@ 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,
        @@ -8598,11 +9840,12 @@ class AsyncTable:
                         batch_size=batch_size,
                         max_concurrency=max_concurrency,
                         publication_interval_rows=publication_interval_rows,
        -                resource_budget=resource_budget,
        +                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=None
                         if retry_policy is None
                         else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(),
        @@ -8612,7 +9855,15 @@ class AsyncTable:
                         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,
                 )
        @@ -8687,6 +9938,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
        @@ -8702,6 +9957,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
        @@ -8760,7 +10029,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.
        @@ -8772,8 +10045,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
                 ----------
        @@ -8781,6 +10058,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
                 -------
        @@ -8789,6 +10070,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
        @@ -8840,8 +10123,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(
        @@ -8867,8 +10154,13 @@ class AsyncTable:
                 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), buffer_size
        +            column,
        +            selection.row_ids,
        +            buffer_size=buffer_size,
        +            version=selection.version,
        +            snapshot_identity=selection.snapshot_identity,
                 )
                 return _wrap_blob_files(handles)
         
        @@ -8939,6 +10231,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,
                 *,
        @@ -9176,6 +10500,7 @@ class IndexStatistics:
                 "LABEL_LIST",
                 "NGRAM",
                 "ZONEMAP",
        +        "RTREE",
             ]
             distance_type: Optional[Literal["l2", "cosine", "dot"]] = None
             num_indices: Optional[int] = None
        @@ -9272,6 +10597,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.
        @@ -9302,7 +10647,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.
         
        @@ -9311,8 +10656,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))
         
        @@ -9359,6 +10705,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.
         
        @@ -9370,9 +10718,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)
         
        @@ -9424,6 +10776,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.
        @@ -9454,7 +10928,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.
         
        @@ -9463,8 +10937,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)
         
        @@ -9508,6 +10983,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.
         
        @@ -9519,12 +10996,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 f1bacb262..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"]
        @@ -1958,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",
        @@ -2216,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(
        @@ -2384,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(
        @@ -3176,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_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_db.py b/python/python/tests/test_db.py
        index 80a98bc18..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
         
        @@ -845,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
        @@ -932,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() == []
        @@ -948,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 8b06943da..2bceb750f 100644
        --- a/python/python/tests/test_e2e_remote_db.py
        +++ b/python/python/tests/test_e2e_remote_db.py
        @@ -11,11 +11,139 @@ import numpy as np
         import pyarrow as pa
         import pytest
         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"
         )
        @@ -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..6e6ab45d1 100644
        --- a/python/python/tests/test_elastic_dataloader.py
        +++ b/python/python/tests/test_elastic_dataloader.py
        @@ -32,6 +32,7 @@ Parameters used throughout:
         
         import dataclasses
         import logging
        +import multiprocessing as mp
         import threading
         from unittest.mock import patch
         
        @@ -1028,6 +1029,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 ─────────────────────────────────────────────
         
         
        diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py
        index 004aca90c..99f891ecb 100644
        --- a/python/python/tests/test_first_class_function_slice1.py
        +++ b/python/python/tests/test_first_class_function_slice1.py
        @@ -22,6 +22,7 @@ from lancedb.functions import (
             SecretReference,
         )
         from lancedb.table import AsyncTable
        +from lancedb.resources import _resource_options
         
         
         FIXTURES = (
        @@ -614,7 +615,11 @@ class _FunctionDeclarationInner:
                 output_name,
                 auto_refresh_enabled,
                 auto_refresh_interval_seconds,
        -        auto_refresh_resource_budget,
        +        total_cpu_millis,
        +        total_memory_bytes,
        +        total_gpu_count,
        +        gpu_class=None,
        +        gpu_count=None,
             ):
                 self.calls.append(
                     (
        @@ -622,7 +627,9 @@ class _FunctionDeclarationInner:
                         output_name,
                         auto_refresh_enabled,
                         auto_refresh_interval_seconds,
        -                auto_refresh_resource_budget,
        +                total_cpu_millis,
        +                total_memory_bytes,
        +                total_gpu_count,
                     )
                 )
                 return "declared"
        @@ -648,18 +655,22 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
             )
             assert result == "declared"
             assert inner.calls[-1][1] == "features"
        -    assert inner.calls[-1][2:] == (None, None, None)
        +    assert inner.calls[-1][2:] == (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, None)
        +    assert inner.calls[-1][2:] == (False, 300, 8000, None, 0)
         
         
         @pytest.mark.asyncio
        @@ -715,3 +726,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 dbc574e88..b3662e582 100644
        --- a/python/python/tests/test_first_class_function_slice2.py
        +++ b/python/python/tests/test_first_class_function_slice2.py
        @@ -833,7 +833,7 @@ def test_function_image_requires_digest_reference(image):
         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")
        +        @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g", gpu_count=2)
                 def double_on_gpu(value: int) -> int:
                     return value * 2
         
        @@ -841,6 +841,7 @@ def test_function_gpu_marker_uses_gpu_runtime():
             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
         
             @function(pip=["pyarrow"])
             def cpu_function(value: int) -> int:
        @@ -856,14 +857,29 @@ def test_function_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"):
        +    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 invalid in ["H100", "a_b", "-a10g", "a10g-", "a" * 64]:
        +    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"):
        -            function(name="invalid_gpu_class", gpu=True, gpu_class=invalid)(identity)
        -    with pytest.raises(ValueError, match="requires gpu=True"):
        -        function(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",
        @@ -895,6 +911,66 @@ class _GpuArrayFunction:
                 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"):
         
        diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py
        index 26ce5e528..1bf019fc2 100644
        --- a/python/python/tests/test_fts.py
        +++ b/python/python/tests/test_fts.py
        @@ -1655,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"
        @@ -1677,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,
        diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py
        index ae74cc8cd..8d2d282a9 100644
        --- a/python/python/tests/test_function_packaging.py
        +++ b/python/python/tests/test_function_packaging.py
        @@ -20,6 +20,7 @@ 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
        @@ -582,6 +583,48 @@ def test_array_batch_annotations_accept_explicit_schemas():
             assert identity(values).equals(values)
         
         
        +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")
        +
        +
         @pytest.mark.parametrize("class_function", [False, True])
         @pytest.mark.parametrize("postponed", [False, True])
         @pytest.mark.parametrize(
        @@ -727,7 +770,6 @@ def test_nested_class_and_closure_are_rejected_with_the_reason():
         @pytest.mark.parametrize(
             "module_name",
             [
        -        "sys",
                 "builtins",
                 "importlib",
                 "inspect",
        @@ -735,7 +777,6 @@ def test_nested_class_and_closure_are_rejected_with_the_reason():
                 "ctypes",
                 "types",
                 "ctypes.util",
        -        "importlib.metadata",
             ],
         )
         @pytest.mark.parametrize("import_style", ["import", "from", "global"])
        @@ -772,6 +813,146 @@ def test_namespace_module_errors_explain_the_rule_and_remedy(
             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"):
        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 e658d18e1..fe90732be 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,
        @@ -23,6 +25,7 @@ from lancedb.index import (
             Fm,
             NGram,
             ZoneMap,
        +    RTree,
             HnswPq,
             HnswSq,
             HnswFlat,
        @@ -89,7 +92,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()
        @@ -250,6 +253,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(" value 1
        diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py
        index b4ca746b0..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,6 +18,7 @@ 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
        @@ -26,7 +29,7 @@ from lancedb.namespace import (
             LanceNamespaceDBConnection,
             _query_to_namespace_request,
         )
        -from lancedb.query import FullTextSearchQuery, Query
        +from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query
         from lancedb.table import AsyncTable, LanceTable
         
         
        @@ -35,6 +38,37 @@ 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):
        @@ -56,6 +90,70 @@ async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
             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])
        @@ -309,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(
        @@ -1352,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:
        @@ -1414,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",
                 [
        diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py
        index 46d6493ed..1e23d6d99 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)})
        diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py
        index f49d98cb6..0a292d2d7 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(
                 [
        @@ -435,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):
        @@ -744,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):
        @@ -811,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")
        @@ -1463,18 +2000,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):
        @@ -2382,6 +2917,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)
        @@ -2486,6 +3076,86 @@ def test_take_queries(tmp_path):
             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):
        @@ -2592,6 +3262,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)
        diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py
        index 587e2d587..f8d264e31 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
        @@ -21,6 +22,7 @@ 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
        @@ -1403,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))
        @@ -1529,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":
        @@ -2204,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
        @@ -2226,13 +2354,11 @@ def test_remote_create_index_async_returns_job():
                 {"batch_size": 8},
                 {"max_concurrency": 3},
                 {"publication_interval_rows": 60},
        -        {"resource_budget": {"cpu_millis": 2000, "memory_bytes": 4 * 1024**3}},
        +        {"total_cpu_millis": 2000, "total_memory_bytes": 4 * 1024**3},
                 {
        -            "resource_budget": {
        -                "cpu_millis": 8000,
        -                "memory_bytes": 16 * 1024**3,
        -                "gpu_count": 2,
        -            }
        +            "total_cpu_millis": 8000,
        +            "total_memory_bytes": 16 * 1024**3,
        +            "total_gpu_count": 2,
                 },
                 {
                     "supervisor_resources": {
        @@ -2251,7 +2377,7 @@ def test_remote_create_index_async_returns_job():
                         "fragments_per_worker": 8,
                     },
                 },
        -        {"gpu_class": "a10g", "gpu_count": 2},
        +        {"gpu_class": "a10g", "total_gpu_count": 2},
                 {
                     "retry_policy": {"transient": True, "max_attempts": 3},
                     "error_policy": "skip",
        @@ -2265,6 +2391,7 @@ def test_remote_create_index_async_returns_job():
                     "row_timeout_seconds": 30,
                     "init_timeout_seconds": 120,
                     "num_workers": 4,
        +            "max_job_attempts": 4,
                     "max_executor_processes_per_worker": 2,
                 },
             ],
        @@ -2289,14 +2416,11 @@ 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("resource_budget") is not None:
        -                budget = refresh_kwargs["resource_budget"]
        -                expected["resource_budget"] = {
        -                    **budget,
        -                    "gpu_count": budget.get("gpu_count", 0),
        -                }
        +            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]
        @@ -2315,6 +2439,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
                         "row_timeout_seconds",
                         "init_timeout_seconds",
                         "num_workers",
        +                "max_job_attempts",
                         "max_executor_processes_per_worker",
                     ):
                         if refresh_kwargs.get(key) is not None:
        @@ -2372,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,
        @@ -2478,8 +2653,7 @@ 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"),
        @@ -2496,37 +2670,8 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle():
                 ({"max_concurrency": 2**32}, "max_concurrency"),
                 ({"num_workers": 0}, "num_workers"),
                 (
        -            {"resource_budget": {"cpu_millis": 1000}},
        -            "resource_budget.memory_bytes",
        -        ),
        -        (
        -            {
        -                "resource_budget": {
        -                    "cpu_millis": 0,
        -                    "memory_bytes": 1,
        -                }
        -            },
        -            "resource_budget.cpu_millis",
        -        ),
        -        (
        -            {
        -                "resource_budget": {
        -                    "cpu_millis": 1000,
        -                    "memory_bytes": 1,
        -                },
        -                "gpu_count": 1,
        -            },
        -            "gpu_count cannot be combined with resource_budget",
        -        ),
        -        (
        -            {
        -                "resource_budget": {
        -                    "cpu_millis": 1000,
        -                    "memory_bytes": 1,
        -                    "unknown": 1,
        -                }
        -            },
        -            "unsupported key 'unknown'",
        +            {"total_cpu_millis": 0, "total_memory_bytes": 1},
        +            "total_cpu_millis",
                 ),
                 (
                     {
        @@ -2547,17 +2692,6 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle():
                     },
                     "supervisor_resources.ephemeral_storage_bytes",
                 ),
        -        (
        -            {
        -                "supervisor_resources": {
        -                    "cpu_millis": 1,
        -                    "memory_bytes": 1,
        -                    "ephemeral_storage_bytes": 1,
        -                    "unknown": 1,
        -                }
        -            },
        -            "unsupported key 'unknown'",
        -        ),
                 (
                     {
                         "planning_workers": {
        @@ -2905,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
         
         
        @@ -3044,23 +3178,23 @@ async def test_reopened_refresh_job_wait_returns_typed_result(
             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"}
        +            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
        +            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"}
        +            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 job.result() == terminal_result
         
             assert isinstance(result, lancedb.RefreshColumnResult)
             assert result == lancedb.RefreshColumnResult.model_validate(terminal_result)
        @@ -3129,12 +3263,12 @@ async def test_reopened_unit_job_ignores_additive_result_payload(sync):
                 with mock_lancedb_connection(handler) as db:
                     job = db.open_job("index-1")
                     assert job.wait() is None
        -            assert job.result == terminal_result
        +            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
        +            assert job.result() == terminal_result
         
         
         @pytest.mark.parametrize("payload", [b"{", b"{}"])
        @@ -3272,9 +3406,9 @@ async def test_remote_job_wait_preserves_terminal_build(sync, with_terminal_serv
             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
        +    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"])
        @@ -3343,6 +3477,55 @@ 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.parametrize(
             "rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}]
         )
        @@ -3561,13 +3744,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):
        @@ -4015,6 +4201,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"
        @@ -4096,6 +4299,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",
             [
        @@ -5273,12 +5506,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()
        @@ -5792,6 +6023,9 @@ def blob_descriptor_take_table():
             )
         
         
        +_DEFAULT_DESCRIPTOR_IDENTITY = object()
        +
        +
         @contextlib.contextmanager
         def blob_remote_table(
             *,
        @@ -5807,6 +6041,7 @@ def blob_remote_table(
             search_scores=False,
             snapshot_supported=True,
             identity_header="v1:" + "a" * 64,
        +    descriptor_identity_header=_DEFAULT_DESCRIPTOR_IDENTITY,
             verify_identity=True,
         ):
             if state is None:
        @@ -5851,6 +6086,11 @@ def blob_remote_table(
                     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/":
        @@ -5859,14 +6099,26 @@ def blob_remote_table(
                     if requests is not None:
                         requests.append(("query", body))
                     columns = body.get("columns")
        -            assert columns in (
        +            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 isinstance(columns, dict):
        +            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):
        @@ -5917,11 +6169,20 @@ def blob_remote_table(
                         request.send_header("x-lancedb-version", header)
                         if snapshot_supported:
                             request.send_header("x-lancedb-query-version", header)
        -                    identity = (
        -                        identity_header(body)
        -                        if callable(identity_header)
        -                        else identity_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()
        @@ -6469,13 +6730,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():
        @@ -6628,10 +6990,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)
        @@ -6729,7 +7110,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 == {
        @@ -6743,6 +7124,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
        @@ -6754,14 +7153,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
        @@ -6770,12 +7169,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.traceback == (
        +        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) == (
        +        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")'
                 )
        @@ -6790,7 +7189,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()
        @@ -6798,27 +7203,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)
        @@ -6829,39 +7232,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)
         
        -        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",
        @@ -6869,6 +7308,13 @@ 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])
        @@ -7233,28 +7679,31 @@ async def test_remote_add_function_columns_forwards_auto_refresh_resource_budget
                     request.send_response(404)
                     request.end_headers()
         
        -    budget = {"cpu_millis": 2_000, "memory_bytes": 4 * 1024**3}
        +    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},
        -            auto_refresh_resource_budget=budget,
        +            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},
        -            auto_refresh_resource_budget=budget,
        +            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
        -        assert body["auto_refresh_resource_budget"] == {
        -            **budget,
        -            "gpu_count": 0,
        -        }
        +        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}]
         
         
        @@ -7407,10 +7856,10 @@ def _create_table_handler(request):
         
         
         @contextlib.contextmanager
        -def _mock_remote_sql_connection(flight_server):
        +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)
        @@ -7845,3 +8294,972 @@ def test_remote_fts_and_rejects_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 a479fa5d1..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)
        @@ -22,24 +24,46 @@ 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())
         
        @@ -401,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_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 4b26a9003..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()
        @@ -6011,8 +6565,8 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
                 ({"max_concurrency": 4}, "max_concurrency"),
                 ({"publication_interval_rows": 60}, "publication_interval_rows"),
                 (
        -            {"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}},
        -            "resource_budget",
        +            {"total_cpu_millis": 1000, "total_memory_bytes": 1024},
        +            "total_cpu_millis",
                 ),
                 (
                     {
        @@ -6092,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
        @@ -6310,10 +6864,8 @@ def test_auto_refresh_resource_budget_requires_a_function(tmp_path):
             with pytest.raises(ValueError, match="registered Function"):
                 table.add_columns(
                     computed={"doubled": "x * 2"},
        -            auto_refresh_resource_budget={
        -                "cpu_millis": 1_000,
        -                "memory_bytes": 1_024,
        -            },
        +            total_cpu_millis=1_000,
        +            total_memory_bytes=1_024,
                 )
             assert table.version == before
             assert table.schema.names == ["x"]
        @@ -6414,3 +6966,24 @@ def test_fts_exist_ok_matches_quoted_default_name(mem_db):
             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_torch.py b/python/python/tests/test_torch.py
        index befa3c10f..e555bf7db 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,472 @@ 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 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_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..90ad26463 100644
        --- a/python/python/tests/utils.py
        +++ b/python/python/tests/utils.py
        @@ -51,21 +51,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 +99,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 +145,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 +166,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
        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/connection.rs b/python/src/connection.rs
        index 2d65a0459..75878cf0e 100644
        --- a/python/src/connection.rs
        +++ b/python/src/connection.rs
        @@ -20,6 +20,7 @@ use arrow::{
             pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
         };
         use lancedb::{
        +    BasePath,
             connection::Connection as LanceConnection,
             connection::NamespaceClientPushdownOperation,
             database::namespace::LanceNamespaceDatabase,
        @@ -30,9 +31,9 @@ use lancedb::{
         };
         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(
        @@ -56,6 +57,139 @@ fn materialized_view_builder(
             }
         }
         
        +/// 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,
        @@ -241,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);
                     }
        @@ -311,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,
        @@ -321,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)?);
        @@ -333,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);
        @@ -359,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,
        @@ -369,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)?;
         
        @@ -382,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);
        @@ -507,7 +665,7 @@ impl Connection {
             }
         
             #[allow(clippy::too_many_arguments)]
        -    #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))]
        +    #[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,
        @@ -518,6 +676,12 @@ impl Connection {
                 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> {
        @@ -537,6 +701,22 @@ impl Connection {
                     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);
                     }
        @@ -553,7 +733,7 @@ impl Connection {
             }
         
             #[allow(clippy::too_many_arguments)]
        -    #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))]
        +    #[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,
        @@ -564,6 +744,12 @@ impl Connection {
                 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> {
        @@ -583,6 +769,22 @@ impl Connection {
                     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);
                     }
        @@ -902,6 +1104,18 @@ impl Connection {
                                 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)),
                     }
                 })
        diff --git a/python/src/index.rs b/python/src/index.rs
        index 039440211..ff75bb321 100644
        --- a/python/src/index.rs
        +++ b/python/src/index.rs
        @@ -10,7 +10,7 @@ use lancedb::index::{
             Index as LanceDbIndex,
             scalar::{
                 BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
        -        ZoneMapIndexBuilder,
        +        RTreeIndexBuilder, ZoneMapIndexBuilder,
             },
         };
         use pyo3::IntoPyObject;
        @@ -119,6 +119,16 @@ pub fn extract_index_params(source: &Option>) -> PyResult 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))
        +            }
                     "FTS" => {
                         let params = source.extract::()?;
                         let code_options = CodeAnalyzerOptions {
        @@ -293,7 +303,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, ZoneMap, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
        +                "Invalid index type '{}'.  Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
                         not_supported
                     ))),
                 }
        @@ -327,6 +337,11 @@ struct FtsParams {
             index_operators: Option,
         }
         
        +#[derive(FromPyObject)]
        +struct RTreeParams {
        +    page_size: Option,
        +}
        +
         #[derive(FromPyObject)]
         struct IvfFlatParams {
             distance_type: String,
        diff --git a/python/src/job.rs b/python/src/job.rs
        index 08f6440ab..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 {
        @@ -159,19 +220,98 @@ impl Job {
                 })
             }
         
        +    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))]
        +    #[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| {
        @@ -196,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,
         }
        @@ -232,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,
                 }
        @@ -294,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,
        @@ -356,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,
        diff --git a/python/src/lib.rs b/python/src/lib.rs
        index b0698d5e0..4680aab4c 100644
        --- a/python/src/lib.rs
        +++ b/python/src/lib.rs
        @@ -40,6 +40,7 @@ pub mod query;
         pub mod runtime;
         pub mod session;
         pub mod sql;
        +mod sync_stream;
         pub mod table;
         pub mod util;
         
        @@ -97,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::()?; @@ -113,6 +115,7 @@ 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::()?; 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 9864d7d74..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}; @@ -33,6 +34,7 @@ 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; @@ -65,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; @@ -357,6 +387,7 @@ pub struct PyQueryRequest { 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, @@ -380,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 { @@ -390,6 +422,7 @@ impl From for PyQueryRequest { 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 @@ -417,12 +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), @@ -449,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, }, } } @@ -667,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(); @@ -684,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 { @@ -751,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); } @@ -784,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 { @@ -909,6 +1007,45 @@ 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 @@ -1148,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/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 25a99e5db..c97bc6b15 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -9,7 +9,7 @@ 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, @@ -29,14 +29,14 @@ use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest}; use lancedb::connection::LanceFileVersion; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ - AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration, + AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, DeltaRef, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig, - FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform, - Ref, RefreshColumnOptions, Table as LanceDbTable, + 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::{ @@ -48,15 +48,24 @@ mod scannable; /// 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, - resource_budget: Option, + total_cpu_millis: Option, + total_memory_bytes: Option, supervisor_resources: Option, planning_workers: Option, gpu_class: Option, - gpu_count: Option, + gpu_count: Option, + total_gpu_count: Option, retry_policy: Option, error_policy: Option, max_failed_fraction: Option, @@ -103,65 +112,6 @@ fn positive_u32_integer(value: Option<&Bound<'_, PyAny>>, name: &str) -> PyResul }) } -fn resource_budget_integer( - value: &Bound<'_, PyAny>, - name: &str, - allow_zero: bool, -) -> PyResult { - if value.is_none() || value.is_instance_of::() { - return Err(PyValueError::new_err(format!( - "resource_budget.{name} must be an integer" - ))); - } - let parsed = value - .extract::() - .map_err(|_| PyValueError::new_err(format!("resource_budget.{name} must be an integer")))?; - if !allow_zero && parsed == 0 { - return Err(PyValueError::new_err(format!( - "resource_budget.{name} must be greater than zero" - ))); - } - Ok(parsed) -} - -fn parse_resource_budget( - budget: Option<&Bound<'_, PyDict>>, -) -> PyResult> { - let Some(budget) = budget else { - return Ok(None); - }; - for key in budget.keys() { - let key = key - .extract::() - .map_err(|_| PyValueError::new_err("resource_budget keys must be strings"))?; - if !matches!(key.as_str(), "cpu_millis" | "memory_bytes" | "gpu_count") { - return Err(PyValueError::new_err(format!( - "resource_budget contains unsupported key '{key}'" - ))); - } - } - let cpu_millis = budget - .get_item("cpu_millis")? - .ok_or_else(|| PyValueError::new_err("resource_budget.cpu_millis is required"))?; - let cpu_millis = resource_budget_integer(&cpu_millis, "cpu_millis", false)?; - let memory_bytes = budget - .get_item("memory_bytes")? - .ok_or_else(|| PyValueError::new_err("resource_budget.memory_bytes is required"))?; - let memory_bytes = resource_budget_integer(&memory_bytes, "memory_bytes", false)?; - let gpu_count = match budget.get_item("gpu_count")? { - None => 0, - Some(value) if value.is_none() => 0, - Some(value) => { - u32::try_from(resource_budget_integer(&value, "gpu_count", true)?).map_err(|_| { - PyValueError::new_err("resource_budget.gpu_count must be no greater than u32::MAX") - })? - } - }; - Ok(Some( - FunctionWorkerResourceBudget::new(cpu_millis, memory_bytes).with_gpu_count(gpu_count), - )) -} - 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"))); @@ -259,15 +209,24 @@ fn parse_planning_workers( 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, - resource_budget, + total_cpu_millis, + total_memory_bytes, supervisor_resources, planning_workers, gpu_class, gpu_count, + total_gpu_count, retry_policy, error_policy, max_failed_fraction, @@ -278,6 +237,17 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult PyResult PyResult 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()?; @@ -472,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)? @@ -872,6 +852,10 @@ 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, @@ -915,6 +899,10 @@ 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, @@ -968,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] @@ -988,9 +979,13 @@ 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, } } } @@ -1573,6 +1568,14 @@ impl Table { }) } + 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>, @@ -1849,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 { @@ -1981,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 { @@ -2026,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>, @@ -2154,15 +2222,29 @@ impl Table { } /// Open lazy blob handles for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids, buffer_size=None))] + #[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 @@ -2209,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>( @@ -2534,21 +2670,28 @@ impl Table { }) } - #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))] + #[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, - auto_refresh_resource_budget: Option>, + 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, - auto_refresh_resource_budget: parse_resource_budget( - auto_refresh_resource_budget.as_ref(), - )?, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, }; options.validate().infer_error()?; future_into_py(self_.py(), async move { @@ -2565,14 +2708,19 @@ impl Table { }) } - #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))] + #[pyo3(signature = (application_json, output_name, 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>, application_json: String, output_name: Option, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, - auto_refresh_resource_budget: Option>, + total_cpu_millis: Option, + total_memory_bytes: Option, + total_gpu_count: Option, + gpu_class: Option, + gpu_count: Option, ) -> PyResult> { let application = lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?; @@ -2580,9 +2728,11 @@ impl Table { let options = ComputedColumnOptions { auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), auto_refresh_interval_seconds, - auto_refresh_resource_budget: parse_resource_budget( - auto_refresh_resource_budget.as_ref(), - )?, + total_cpu_millis, + total_memory_bytes, + total_gpu_count, + gpu_class, + gpu_count, }; options.validate().infer_error()?; future_into_py(self_.py(), async move { @@ -2599,7 +2749,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, 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))] + #[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>, @@ -2608,11 +2758,13 @@ impl Table { batch_size: Option, max_concurrency: Option>, publication_interval_rows: Option, - resource_budget: Option>, + total_cpu_millis: Option, + total_memory_bytes: Option, supervisor_resources: Option>, planning_workers: Option>, gpu_class: Option, - gpu_count: Option, + gpu_count: Option, + total_gpu_count: Option, retry_policy: Option, error_policy: Option, max_failed_fraction: Option, @@ -2621,17 +2773,32 @@ impl Table { 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, - resource_budget: parse_resource_budget(resource_budget.as_ref())?, + 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, @@ -2640,6 +2807,7 @@ impl Table { 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 { @@ -2651,7 +2819,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, 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))] + #[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>, @@ -2660,11 +2828,13 @@ impl Table { batch_size: Option, max_concurrency: Option>, publication_interval_rows: Option, - resource_budget: Option>, + total_cpu_millis: Option, + total_memory_bytes: Option, supervisor_resources: Option>, planning_workers: Option>, gpu_class: Option, - gpu_count: Option, + gpu_count: Option, + total_gpu_count: Option, retry_policy: Option, error_policy: Option, max_failed_fraction: Option, @@ -2673,17 +2843,32 @@ impl Table { 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, - resource_budget: parse_resource_budget(resource_budget.as_ref())?, + 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, @@ -2692,6 +2877,7 @@ impl Table { 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 { @@ -2703,18 +2889,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()?; @@ -2722,6 +2920,53 @@ impl Table { }) } + #[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>, @@ -2767,16 +3012,17 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))] + #[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, - cpu_millis: Option, - memory_bytes: Option, - gpu_count: Option, + 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 { @@ -2784,18 +3030,21 @@ impl Table { .await .infer_error()?; let mut builder = view.refresh().full(full); - if let Some(value) = cpu_millis { - builder = builder.cpu_millis(value); + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); } - if let Some(value) = memory_bytes { - builder = builder.memory_bytes(value); + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); } - if let Some(value) = gpu_count { - builder = builder.gpu_count(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); } @@ -2804,16 +3053,17 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))] + #[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, - cpu_millis: Option, - memory_bytes: Option, - gpu_count: Option, + 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 { @@ -2821,18 +3071,21 @@ impl Table { .await .infer_error()?; let mut builder = view.refresh().full(full); - if let Some(value) = cpu_millis { - builder = builder.cpu_millis(value); + if let Some(value) = total_cpu_millis { + builder = builder.total_cpu_millis(value); } - if let Some(value) = memory_bytes { - builder = builder.memory_bytes(value); + if let Some(value) = total_memory_bytes { + builder = builder.total_memory_bytes(value); } - if let Some(value) = gpu_count { - builder = builder.gpu_count(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); } @@ -3000,6 +3253,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 { @@ -3057,9 +3407,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(()) @@ -3096,6 +3451,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> { @@ -3116,18 +3500,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/uv.lock b/python/uv.lock index 6b1a96c2e..b5c9fb616 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b25" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b26" }, { 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" }, @@ -4301,24 +4301,21 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b25" +version = "15.0.0b26" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { 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.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_2hpc2R/pylance-15.0.0b25-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:2a0bb8d6b0c55b7a821989759fc0f8f62cb4da621f89eae232cef49bb7ef341e" }, - { url = "https://pypi.fury.io/lance-format/-/ver_4LUKQ/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9b73e6e9373c4d5af3fea51e63c3e55873f470aa1a6d0412c22916f88ff5df88" }, - { url = "https://pypi.fury.io/lance-format/-/ver_11CcHk/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8090d403b2a38cd4ac8eb09de0327bc404cb3bc965d905f2b6a8479891273fae" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1S87Ih/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7f0a20e8ed41d3e49cd5e0bbba97d18ad684cf337e053641321404c9db34f1a1" }, - { url = "https://pypi.fury.io/lance-format/-/ver_13KmLJ/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:079385a6816a10d42f57bc467d9c822c7207cd31d9a6f768bbf522c0a3007229" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1bTDlQ/pylance-15.0.0b25-cp310-abi3-win_amd64.whl", hash = "sha256:d9b1d713b0d03043a3f5596e909405787f85219f54c427b14437367f0ea7acb9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_j7adN/pylance-15.0.0b25-cp310-abi3-win_arm64.whl", hash = "sha256:4a1c18176ffd6a860c6e66b0deb39fcc9ac1434dba57ee66559b7638ad4a200a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2bYWOD/pylance-15.0.0b26-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc68ef8edeb6e29f01542f0bfaa7973978f416a8eeec344427b255dd652db13a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_aF5wV/pylance-15.0.0b26-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27d4f4c18ab682052931e70c4f5d4491288c99c69f465ed806084f40b3924367" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2axp3c/pylance-15.0.0b26-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fb0b9c33f85ff9c52633488b5b696fa1a35036ae899827aceb94212a2ef746df" }, + { url = "https://pypi.fury.io/lance-format/-/ver_oCJRc/pylance-15.0.0b26-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7c5ca0afb4988206518b1cb801bb1a1a3cc09527828ae51109b2071e549a4486" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1Lg63I/pylance-15.0.0b26-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:32a986146e7b4f2e7b23974bb8718f293939f43f088e5585c38b1ae5b162d46c" }, + { url = "https://pypi.fury.io/lance-format/-/ver_FOT84/pylance-15.0.0b26-cp310-abi3-win_amd64.whl", hash = "sha256:904fd37f8212f00c1affc917b421e4ac4fc051c4c3d3c98cd7adbb33537a3ce3" }, + { url = "https://pypi.fury.io/lance-format/-/ver_A4Kru/pylance-15.0.0b26-cp310-abi3-win_arm64.whl", hash = "sha256:39dbf4b02b3bbaf916b38f1b924da2a534cdb1e32eb8e3f58fb720ef9b92331a" }, ] [[package]] diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index e868a7d35..c111fc483 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.18" +version = "0.42.0-beta.22" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true @@ -46,7 +46,7 @@ lance-io = { workspace = true } lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lindera"] } lance-table = { workspace = true } # Keep the upstream source for downstream SDKs, where workspace patches do not apply. -lance-linalg = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.26", "tag" = "v15.0.0-beta.26", "git" = "https://github.com/lance-format/lance.git" } lance-encoding = { workspace = true } lance-arrow = { workspace = true } lance-namespace = { workspace = true } diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 689200452..6dc6bea71 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.18" +version = "0.42.0-beta.22" edition = "2021" license.workspace = true repository.workspace = true diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index 82f502250..7a381b8ee 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -656,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/connection.rs b/rust/lancedb/src/connection.rs index 29f70d164..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; @@ -90,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, @@ -358,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 @@ -381,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. /// @@ -2066,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. @@ -2181,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); 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/database.rs b/rust/lancedb/src/database.rs index 8a7a941f6..b021bf0ee 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -212,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 { @@ -220,6 +222,7 @@ impl ExecuteQueryRequest { query: query.into(), default_namespace_path: vec!["public".to_string()], parameters: None, + options: Default::default(), } } } @@ -291,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 @@ -326,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, @@ -385,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) } } diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 765c8af3d..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)?; @@ -1180,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, @@ -1233,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) } @@ -1843,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")] @@ -1857,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) } diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 4e61710ff..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::{ @@ -465,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), )); } @@ -618,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/error.rs b/rust/lancedb/src/error.rs index 6aed94d71..3c8a485f9 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -344,6 +344,46 @@ fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static) 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 { @@ -351,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{}", server_build_suffix(source.as_ref())))] + #[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}" diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 4e7157c37..270761d28 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -305,6 +305,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()); /// ``` @@ -312,8 +313,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. /// @@ -365,17 +368,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)] @@ -388,6 +404,8 @@ struct PythonRuntimeV1Wire { #[derive(Deserialize)] struct PythonRuntimeV2Wire { + #[serde(default)] + gpus_per_worker: Option, python_version: String, environment: PythonEnvironmentSpec, #[serde(default)] @@ -420,6 +438,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, @@ -440,6 +463,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 }), @@ -460,6 +484,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)] @@ -479,6 +505,7 @@ impl Serialize for PythonRuntimeSpec { env, gpu: None, gpu_class: None, + gpus_per_worker: None, } .serialize(serializer), Self::PythonV2 { @@ -486,6 +513,7 @@ impl Serialize for PythonRuntimeSpec { environment, env, gpu_class, + gpus_per_worker, } => PythonRuntimeRef { kind: "python_v2", python_version, @@ -493,6 +521,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), @@ -675,6 +704,24 @@ pub struct FunctionVersion { 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, @@ -773,6 +820,21 @@ impl FunctionVersion { 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 @@ -900,6 +962,44 @@ 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> @@ -970,6 +1070,27 @@ pub struct FunctionRegistrationRequest { 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. @@ -1010,6 +1131,11 @@ 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)?; @@ -1308,6 +1434,12 @@ pub struct FunctionRefreshPlan { /// 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. @@ -1330,6 +1462,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. @@ -1337,9 +1471,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() @@ -1362,6 +1504,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 @@ -1369,6 +1518,18 @@ 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, @@ -1429,6 +1590,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. @@ -1437,6 +1604,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 { @@ -1465,6 +1709,8 @@ mod refresh_result_tests { source_version: 7, published_version: Some(8), plan, + error_groups: Vec::new(), + error_groups_truncated: false, } } @@ -1498,6 +1744,7 @@ mod refresh_result_tests { #[cfg(test)] mod conda_environment_tests { use super::{PythonEnvironmentSpec, PythonRuntimeSpec}; + use serde_json::Value; #[test] fn conda_channels_round_trip_and_pip_stays_bare() { @@ -1559,6 +1806,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}"#, diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index b1e3c1bbf..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,6 +155,9 @@ 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 { @@ -90,6 +168,26 @@ pub(crate) trait JobHandle: Send + Sync { 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") @@ -192,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. @@ -255,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()), }), } } @@ -278,6 +380,12 @@ 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 @@ -342,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( @@ -355,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 } } @@ -404,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 @@ -446,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. @@ -514,6 +710,32 @@ 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 @@ -536,6 +758,163 @@ where } } + /// 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 @@ -566,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 @@ -577,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?) } @@ -609,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. @@ -806,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!( 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 de555f709..a2f271b80 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -237,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/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 4b2a61f2c..0591be948 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -301,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 @@ -1591,6 +1596,11 @@ pub struct CreateMaterializedViewBuilder { 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 { @@ -1632,6 +1642,11 @@ impl CreateMaterializedViewBuilder { 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, } } @@ -1783,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. @@ -1799,6 +1844,11 @@ impl CreateMaterializedViewBuilder { 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; } @@ -1832,7 +1882,14 @@ impl CreateMaterializedViewBuilder { { return Ok(view); } - if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { + 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(), @@ -1961,49 +2018,53 @@ impl MaterializedView { /// 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, not a per-Function allocation. CPU or -/// memory requires all three budget fields. Embedded refreshes reject options. +/// 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 cpu_millis: Option, - pub memory_bytes: Option, - pub gpu_count: Option, + 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.cpu_millis.is_none() - && self.memory_bytes.is_none() - && self.gpu_count.is_none() + 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.cpu_millis == Some(0) || self.memory_bytes == Some(0) { + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { return Err(invalid( - "cpu_millis and memory_bytes must be positive integers", - )); - } - if (self.cpu_millis.is_some() || self.memory_bytes.is_some()) - && !(self.cpu_millis.is_some() - && self.memory_bytes.is_some() - && self.gpu_count.is_some()) - { - return Err(invalid( - "cpu_millis, memory_bytes, and gpu_count must be specified together", + "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.gpu_count == Some(0) { + 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(()) } @@ -2013,18 +2074,21 @@ impl RefreshMaterializedViewOptions { if full { values.push("full = true".to_string()); } - if let Some(cpu) = self.cpu_millis { - values.push(format!("cpu_millis = {cpu}")); + if let Some(cpu) = self.total_cpu_millis { + values.push(format!("total_cpu_millis = {cpu}")); } - if let Some(memory) = self.memory_bytes { - values.push(format!("memory_bytes = {memory}")); + if let Some(memory) = self.total_memory_bytes { + values.push(format!("total_memory_bytes = {memory}")); } - if let Some(gpu) = self.gpu_count { - values.push(format!("gpu_count = {gpu}")); + 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 { @@ -2042,25 +2106,31 @@ pub struct RefreshMaterializedViewBuilder { } impl RefreshMaterializedViewBuilder { - /// Cap total CPU capacity in millicores; requires memory and GPU budgets. - pub fn cpu_millis(mut self, cpu_millis: u64) -> Self { - self.options.cpu_millis = Some(cpu_millis); + /// 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 } - /// Cap total memory in bytes; requires CPU and GPU budgets. - pub fn memory_bytes(mut self, memory_bytes: u64) -> Self { - self.options.memory_bytes = Some(memory_bytes); + /// 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 gpu_count(mut self, gpu_count: u32) -> Self { - self.options.gpu_count = Some(gpu_count); + 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 @@ -2448,7 +2518,7 @@ mod tests { .unwrap(); assert!(matches!( - view.refresh().gpu_count(0).execute().await, + view.refresh().total_gpu_count(0).execute().await, Err(Error::NotSupported { .. }) )); assert!(matches!( diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 157440910..bc460dc35 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -742,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. @@ -867,6 +873,13 @@ pub struct QueryRequest { #[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, @@ -915,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 @@ -937,6 +955,7 @@ impl Default for QueryRequest { offset: None, take_offsets: None, take_row_ids: None, + preserve_order: false, filter: None, filter_error: None, full_text_search: None, @@ -948,6 +967,7 @@ impl Default for QueryRequest { norm: None, disable_scoring_autoprojection: false, order_by: None, + scan_in_order: None, use_rte: None, } } @@ -1036,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. @@ -2065,7 +2143,6 @@ impl ExecutionPlan for TakeRestoreExec { pub struct TakeQuery { parent: Arc, request: QueryRequest, - preserve_order: bool, } struct TakeLookup { @@ -2079,6 +2156,20 @@ struct TakeLookup { 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 { /// Create a new `TakeQuery` that will return rows at the given offsets. /// @@ -2100,7 +2191,6 @@ impl TakeQuery { take_offsets: Some(offsets), ..Default::default() }, - preserve_order: false, } } @@ -2122,16 +2212,17 @@ impl TakeQuery { take_row_ids: Some(row_ids), ..Default::default() }, - 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 { + /// 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.preserve_order = true; + self.request.preserve_order = true; self } @@ -2193,6 +2284,7 @@ impl TakeQuery { request: &QueryRequest, 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), @@ -2203,8 +2295,25 @@ impl TakeQuery { }); } }; - let preserve_order = - preserve_order || (by_row_id && request.order_by.as_ref().is_none_or(Vec::is_empty)); + // 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; @@ -2527,7 +2636,7 @@ impl ExecutableQuery for TakeQuery { self.parent.as_ref(), &self.request, options, - self.preserve_order, + self.request.preserve_order, ) .await; } @@ -2564,7 +2673,7 @@ impl ExecutableQuery for TakeQuery { self.parent.as_ref(), &self.request, verbose, - self.preserve_order, + self.request.preserve_order, ) .await; } @@ -4295,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(); @@ -4345,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(); @@ -4395,6 +4649,78 @@ mod tests { assert!(!analyzed.contains("CoalescePartitionsExec")); } + #[tokio::test] + 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])] @@ -4613,6 +4939,35 @@ mod tests { } } + #[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(); diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 125930cb7..9b26c9f3b 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -411,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, @@ -429,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)| { @@ -729,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, @@ -798,6 +823,33 @@ 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() @@ -983,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?) @@ -999,6 +1052,7 @@ impl Database for RemoteDatabase { query: format!("DESCRIBE STORAGE INTEGRATION {name}"), default_namespace_path: namespace_path.to_vec(), parameters: None, + options: Default::default(), }) .await?; integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) @@ -1021,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?; @@ -1358,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, @@ -1539,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)", @@ -2900,6 +2985,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) { @@ -4508,7 +4676,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() } @@ -4526,11 +4694,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] @@ -4943,6 +5126,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)); @@ -4981,6 +5233,12 @@ 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![], diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 7e59834d0..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()), } } @@ -109,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)] @@ -116,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, @@ -146,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 { @@ -155,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, @@ -202,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 @@ -261,6 +321,62 @@ impl JobHandle for RemoteJob { 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 @@ -298,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 } @@ -376,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; @@ -388,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}; @@ -401,6 +524,357 @@ 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)); 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/sql.rs b/rust/lancedb/src/remote/sql.rs index 9c34f8f90..b2ca5651f 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -12,7 +12,6 @@ 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, @@ -44,14 +43,18 @@ 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); @@ -68,6 +71,7 @@ pub(super) struct SubmittedQuery { pub(super) materialized_view_job_handle_supported: bool, } +#[derive(Clone)] struct SqlClientInner { database: String, database_prefix: Option, @@ -76,6 +80,8 @@ struct SqlClientInner { sql_host_override: Option, client_config: ClientConfig, client: Arc>, + deadline: Option, + cancel_on_drop: bool, } struct SqlConnection { @@ -212,11 +218,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) @@ -229,12 +286,34 @@ 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, @@ -250,24 +329,26 @@ impl SqlClient { Submission::Stream(response) => { let query = Arc::new(StreamingQuery::new( query_id, - self.inner.clone(), + 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))) } }; @@ -325,6 +406,7 @@ impl SqlClient { query: statement, default_namespace_path: namespace, parameters: None, + options: Default::default(), }) .await?, ); @@ -367,6 +449,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, @@ -511,6 +608,7 @@ impl SqlClientInner { .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 @@ -751,6 +849,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)] @@ -793,9 +895,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; @@ -832,6 +1000,7 @@ impl RemoteQuery { } *lifecycle = QueryLifecycle::Cancelled; drop(lifecycle); + self.stop_deadline(); self.mark_terminal(); self.cancelled.notify_waiters(); self.state_changed.notify_waiters(); @@ -866,13 +1035,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(()) } @@ -881,13 +1054,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()), } @@ -1164,6 +1344,9 @@ 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, self.job_id(), &state, self.lifecycle()); @@ -1330,6 +1513,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, @@ -1344,6 +1535,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 { @@ -1360,7 +1559,10 @@ impl QueryHandle for RemoteQueryHandle { } 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) @@ -1371,9 +1573,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); @@ -1383,19 +1598,17 @@ 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(); - let stream: SendableRecordBatchStream = - 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, @@ -1407,6 +1620,33 @@ 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, diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index f0ebf1894..f2a12a024 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -51,6 +51,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, definition, ) @@ -76,6 +77,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, definition, ) @@ -119,6 +121,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, |batches| { let rows = strings(&batches, "status")?; diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index c8e1aa5c3..eb29e62af 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -55,6 +55,7 @@ impl SqlClient { query: statement, default_namespace_path: namespace, parameters: None, + options: Default::default(), }, true, ) @@ -133,6 +134,7 @@ impl SqlClient { query: format!("DESCRIBE MATERIALIZED VIEW {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }) .await?; let mut reader = query.reader().await?; diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index 2ffb08936..482fa46de 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -54,6 +54,7 @@ impl SqlClient { query: statement, default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }) .await?; let reader = query.reader().await?; diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index 93c2a6c6e..14c08e94b 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -83,6 +83,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: Some(parameters), + options: Default::default(), }, |_| Ok(()), ) @@ -102,6 +103,7 @@ impl SqlClient { query: format!("DESCRIBE SECRET {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, secret_info, ) @@ -121,6 +123,7 @@ impl SqlClient { query: format!("DROP SECRET IF EXISTS {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, |_| Ok(()), ) diff --git a/rust/lancedb/src/remote/sql/stream.rs b/rust/lancedb/src/remote/sql/stream.rs index 16155bf7c..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}; @@ -56,6 +56,7 @@ pub(super) struct StreamingQuery { terminal_at: OnceLock, last_accessed: StdMutex, job_id: StdMutex>, + deadline_task: StdMutex>, } struct PreparedStream { @@ -183,11 +184,13 @@ 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"))? @@ -271,9 +274,30 @@ impl StreamingQuery { 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(); } @@ -328,11 +352,18 @@ 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 { @@ -359,6 +390,11 @@ impl StreamingQuery { } 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()), } @@ -377,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, @@ -518,7 +548,7 @@ impl QueryHandle for StreamingQueryHandle { } 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) @@ -559,12 +589,8 @@ 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(); - let stream: SendableRecordBatchStream = - 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, diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index b058269a0..ca09c4b5d 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -111,6 +111,7 @@ impl SqlClient { ), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, move |batches| view_description(batches, namespace_path), ) @@ -132,6 +133,7 @@ impl SqlClient { query: format!("DESCRIBE VIEW {}", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, + options: Default::default(), }, move |batches| view_description(batches, namespace_path), ) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d7249da9b..7d7ac2d4a 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -116,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. @@ -138,11 +139,14 @@ 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, @@ -170,6 +174,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"), @@ -313,11 +320,14 @@ 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, large_result, @@ -352,9 +362,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( @@ -493,6 +524,12 @@ impl FlightService for TestSqlService { { 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")); } @@ -502,6 +539,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()) @@ -1208,17 +1253,38 @@ 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()], @@ -1247,7 +1313,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() @@ -1302,6 +1368,12 @@ 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()], @@ -1365,6 +1437,12 @@ async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry .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()], @@ -1452,6 +1530,12 @@ 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()], @@ -1553,6 +1637,7 @@ async fn fast_durable_job_failure_exposes_the_same_job_id_on_the_query_handle() query: "SELECT durable job failure".into(), default_namespace_path: vec![], parameters: None, + options: Default::default(), }) .await .unwrap(); @@ -1685,10 +1770,11 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { let third = view .refresh() .full(true) - .cpu_millis(8000) - .memory_bytes(16 << 30) - .gpu_count(2) + .total_cpu_millis(8000) + .total_memory_bytes(16 << 30) + .total_gpu_count(2) .gpu_class("h100") + .gpu_count(2) .execute_async() .await .unwrap() @@ -1696,9 +1782,8 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { .await .unwrap(); for invalid in [ - view.refresh().cpu_millis(1), view.refresh().gpu_class("H200:8"), - view.refresh().gpu_count(0).gpu_class("h100"), + view.refresh().total_gpu_count(0).gpu_class("h100"), ] { assert!(matches!( invalid.execute_async().await, @@ -1726,7 +1811,7 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { "DESCRIBE MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true)", - "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true, cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2, gpu_class = 'h100')", + "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!( @@ -1906,10 +1991,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 @@ -2315,7 +2402,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"] { @@ -2380,7 +2474,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()); @@ -3181,6 +3275,9 @@ async fn function_creation_and_description_use_sql_query_handles() { 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", @@ -3189,6 +3286,9 @@ async fn function_creation_and_description_use_sql_query_handles() { }]); 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"); @@ -3267,6 +3367,9 @@ async fn function_creation_and_description_use_sql_query_handles() { 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")); @@ -4445,3 +4548,849 @@ async fn remote_optimize_branch_options_are_not_dropped() { ); 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() +} + +#[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/table.rs b/rust/lancedb/src/remote/table.rs index 1394f1ab0..3642fb950 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2,9 +2,13 @@ // 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; #[cfg(test)] mod write_tests; @@ -22,7 +26,7 @@ use crate::index::Index; use crate::index::IndexStatistics; 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}; @@ -78,7 +82,7 @@ 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}; @@ -324,6 +328,26 @@ impl crate::job::JobHandle for FreshnessJob { 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, @@ -331,6 +355,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 } @@ -373,6 +401,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 @@ -409,6 +447,26 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { 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, @@ -416,6 +474,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 } @@ -858,6 +920,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), @@ -961,6 +1062,33 @@ impl RemoteTable { } } + 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 @@ -1282,6 +1410,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. @@ -2603,6 +2738,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 { @@ -3257,6 +3430,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 { @@ -3337,7 +3511,8 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - return crate::query::create_take_plan(self, request, options, false).await; + return crate::query::create_take_plan(self, request, options, request.preserve_order) + .await; } let streams = self.execute_query(query, &options).await?; @@ -3361,8 +3536,13 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - let plan = - crate::query::create_take_plan(self, request, options.clone(), false).await?; + let plan = crate::query::create_take_plan( + self, + request, + options.clone(), + request.preserve_order, + ) + .await?; let inner = execute_plan(plan, Default::default())?; let inner = MaxBatchLengthStream::new_boxed(inner, options.max_batch_length as usize); let inner = if let Some(timeout) = options.timeout { @@ -3425,7 +3605,8 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - return crate::query::explain_take_plan(self, request, verbose, false).await; + return crate::query::explain_take_plan(self, request, verbose, request.preserve_order) + .await; } let base_request = self @@ -3940,6 +4121,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); @@ -4055,19 +4239,10 @@ impl BaseTable for RemoteTable { options: crate::table::optimize::CompactionOverrides, ) -> Result { self.check_mutable().await?; - let compaction_options = optimize::compaction_sql_options(&options)?; + 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 {} REWRITE DATA", quote_sql_identifier(&self.name)); - let mut sql_options = Vec::new(); - if let Some(branch) = &self.branch { - sql_options.push(format!("branch = {}", quote_sql_string(branch))); - } - sql_options.extend(compaction_options); - if !sql_options.is_empty() { - statement.push_str(&format!(" WITH ({})", sql_options.join(", "))); - } // `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) @@ -4084,6 +4259,106 @@ impl BaseTable for RemoteTable { 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 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); + } + let job_id = cleanup::receipt(&batches)?; + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + + 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 query = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + options: Default::default(), + }) + .await + .map_err(optimize::map_optimize_error)?; + let mut reader = query.reader().await.map_err(optimize::map_optimize_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader + .try_next() + .await + .map_err(optimize::map_optimize_error)? + { + batches.push(batch); + } + let job_id = optimize::receipt(&batches)?; + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + async fn add_columns( &self, transforms: NewColumnTransform, @@ -4254,8 +4529,20 @@ impl BaseTable for RemoteTable { if let Some(interval) = options.auto_refresh_interval_seconds { body["auto_refresh_interval_seconds"] = serde_json::json!(interval); } - if let Some(budget) = options.auto_refresh_resource_budget { - body["auto_refresh_resource_budget"] = serde_json::json!(budget); + 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 @@ -4314,48 +4601,37 @@ impl BaseTable for RemoteTable { ) -> Result> { options.validate()?; self.check_mutable().await?; + if options.retry_errors == Some(true) || options.function_version.is_some() { + self.require_function_failure_workflow().await?; + } 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.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) + self.submit_refresh("backfill_column", body).await + } + + 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 - .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, - })?; - - 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 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); } @@ -4365,6 +4641,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 @@ -4373,8 +4652,77 @@ 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, }) @@ -4612,20 +4960,93 @@ 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 mut body = serde_json::json!({ - "columns": columns.unwrap_or_default(), - }); - self.apply_branch_body(&mut body); - 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 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_error)?; + let mut reader = query.reader().await.map_err(prewarm::map_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader.try_next().await.map_err(prewarm::map_error)? { + batches.push(batch); + } + let (job_id, _table_version) = prewarm::receipt(&batches)?; + // Construct lazily: submission must not require an HTTP status round trip. + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + + 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) @@ -4918,6 +5339,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| { @@ -5242,6 +5676,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![ @@ -6364,6 +6888,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( @@ -8254,8 +8799,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(); @@ -8267,7 +8812,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 @@ -8279,12 +8825,24 @@ 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] @@ -10782,9 +11340,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, - auto_refresh_resource_budget: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, }) .execute() .await @@ -11371,11 +11933,11 @@ mod tests { )) .unwrap(); expected["auto_refresh_enabled"] = serde_json::json!(true); - expected["auto_refresh_resource_budget"] = serde_json::json!({ - "cpu_millis": 8_000, - "memory_bytes": 17_179_869_184_u64, - "gpu_count": 2, - }); + 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) @@ -11404,12 +11966,13 @@ mod tests { .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, - auto_refresh_resource_budget: Some( - crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) - .with_gpu_count(2), - ), + total_cpu_millis: Some(8000), + total_memory_bytes: Some(17179869184), + total_gpu_count: Some(2), }) .execute() .await @@ -11493,6 +12056,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()) @@ -11515,6 +12091,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 { @@ -11597,7 +12177,7 @@ mod tests { serde_json::json!({ "column": "quality", "gpu_class": "a10g", - "gpu_count": 2, + "total_gpu_count": 2, }) ); http::Response::builder() @@ -11607,7 +12187,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 @@ -11620,7 +12200,7 @@ mod tests { #[case(Some(2), 2)] #[tokio::test] async fn test_refresh_column_async_resource_budget( - #[case] gpu_count: Option, + #[case] total_gpu_count: Option, #[case] expected_gpu_count: u32, ) { use crate::table::{FunctionWorkerResourceBudget, RefreshColumnOptions}; @@ -11631,11 +12211,9 @@ mod tests { request_body_json(&request), serde_json::json!({ "column": "quality", - "resource_budget": { - "cpu_millis": 8_000, - "memory_bytes": 17_179_869_184_u64, - "gpu_count": expected_gpu_count, - }, + "total_cpu_millis": 8_000, + "total_memory_bytes": 17_179_869_184_u64, + "total_gpu_count": expected_gpu_count, }) ); http::Response::builder() @@ -11644,13 +12222,16 @@ mod tests { .unwrap() }); let mut budget = FunctionWorkerResourceBudget::new(8_000, 17_179_869_184); - if let Some(gpu_count) = gpu_count { - budget = budget.with_gpu_count(gpu_count); + 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().resource_budget(budget), + 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(); @@ -11823,6 +12404,10 @@ mod tests { 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", @@ -11908,22 +12493,23 @@ mod tests { RefreshColumnOptions::default().gpu_class("-a10g"), "gpu_class", ), - (RefreshColumnOptions::default().gpu_count(0), "gpu_count"), ( RefreshColumnOptions::default() - .resource_budget(FunctionWorkerResourceBudget::new(0, 1)), - "resource_budget.cpu_millis", + .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() - .resource_budget(FunctionWorkerResourceBudget::new(1, 0)), - "resource_budget.memory_bytes", - ), - ( - RefreshColumnOptions::default() - .resource_budget(FunctionWorkerResourceBudget::new(1, 1)) - .gpu_count(1), - "gpu_count cannot be combined with resource_budget", + .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 @@ -12917,6 +13503,10 @@ 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, @@ -13030,6 +13620,20 @@ 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}"), @@ -13037,6 +13641,10 @@ mod tests { }); 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")); @@ -13130,6 +13738,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] @@ -13563,67 +14249,16 @@ 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(); - } - - #[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()])) - .await - .unwrap(); - } - - #[tokio::test] - async fn test_prewarm_data_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/page_cache/prewarm/" => { - let body = request_body_json(&request); - assert_eq!(body["branch"], "dev"); - assert_eq!(body["columns"], json!(["payload"])); - http::Response::builder() - .status(202) - .body(r#"{"job_id":"prewarm-job"}"#) - .unwrap() - } - path => panic!("unexpected request path: {path}"), - } - }); - let branch = table - .create_branch("dev", Ref::Version(None, None)) - .await - .unwrap(); - branch - .prewarm_data(Some(vec!["payload".into()])) - .await - .unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("SQL")); } #[tokio::test] @@ -13993,6 +14628,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| { @@ -18164,6 +18824,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", |_| { diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 3367d2218..34c6743b1 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -1156,7 +1156,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() ), }); @@ -1190,9 +1192,20 @@ 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) @@ -2046,6 +2059,80 @@ mod tests { 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); + } + } + #[tokio::test] async fn remote_blob_ranges_accept_empty_requests_without_http() { let (table, requests) = mock_take_blob_table(vec![], Some("7")); diff --git a/rust/lancedb/src/remote/table/cleanup.rs b/rust/lancedb/src/remote/table/cleanup.rs new file mode 100644 index 000000000..c20417742 --- /dev/null +++ b/rust/lancedb/src/remote/table/cleanup.rs @@ -0,0 +1,234 @@ +// 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 receipt(batches: &[RecordBatch]) -> Result { + let invalid = || { + Error::Runtime { message: "VACUUM did not return a single nonempty job_id receipt; inspect jobs before retrying because cleanup may already have been submitted".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 ids = batch + .column_by_name("job_id") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if ids.is_null(0) || ids.value(0).trim().is_empty() { + return Err(invalid()); + } + Ok(ids.value(0).to_string()) +} + +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 ambiguous_cleanup_receipts_never_become_query_handles() { + let batch = |values: Vec>| { + RecordBatch::try_from_iter([( + "job_id", + Arc::new(StringArray::from(values)) as arrow_array::ArrayRef, + )]) + .unwrap() + }; + for batches in [ + vec![], + vec![batch(vec![])], + vec![batch(vec![None])], + vec![batch(vec![Some("")])], + vec![batch(vec![Some("one"), Some("two")])], + ] { + assert!( + receipt(&batches) + .unwrap_err() + .to_string() + .contains("inspect jobs before retrying") + ); + } + assert_eq!( + receipt(&[batch(vec![]), batch(vec![Some("durable-job")])]).unwrap(), + "durable-job" + ); + } + + #[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/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 6f4b7f7e8..80d4d9639 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -4,6 +4,49 @@ //! 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) +} + +/// Submission can already have created work: reject ambiguous receipts without +/// retrying or confusing the SQL query's identity with the compaction job. +pub(super) fn receipt(batches: &[arrow_array::RecordBatch]) -> Result { + use arrow_array::{Array, StringArray}; + let invalid = || { + Error::Runtime { message: "OPTIMIZE did not return a single nonempty job_id receipt; inspect jobs before retrying because compaction may already have been submitted".into() } + }; + if batches.iter().map(|batch| batch.num_rows()).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let ids = batch + .column_by_name("job_id") + .and_then(|a| a.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if ids.is_null(0) || ids.value(0).is_empty() { + return Err(invalid()); + } + Ok(ids.value(0).into()) +} + pub(super) fn compaction_sql_options( options: &crate::table::optimize::CompactionOverrides, ) -> Result> { @@ -258,3 +301,37 @@ mod tests { } } } + +#[cfg(test)] +mod receipt_tests { + use super::*; + use arrow_array::{ArrayRef, RecordBatch, StringArray}; + use std::sync::Arc; + + #[test] + fn compaction_receipt_requires_one_unambiguous_registry_id() { + let batch = |ids: Vec>| { + RecordBatch::try_from_iter([("job_id", Arc::new(StringArray::from(ids)) as ArrayRef)]) + .unwrap() + }; + assert_eq!( + receipt(&[batch(vec![Some("compacting-job")])]).unwrap(), + "compacting-job" + ); + for batches in [ + vec![], + vec![batch(vec![])], + vec![batch(vec![None])], + vec![batch(vec![Some("")])], + vec![batch(vec![Some("a"), Some("b")])], + vec![batch(vec![Some("a")]), batch(vec![Some("b")])], + ] { + assert!( + receipt(&batches) + .unwrap_err() + .to_string() + .contains("inspect jobs before retrying") + ); + } + } +} diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs new file mode 100644 index 000000000..4b6b2236f --- /dev/null +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -0,0 +1,431 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! SQL submission and receipt validation for data-cache prewarm jobs. + +use arrow_array::{Array, RecordBatch, StringArray, UInt64Array}; +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) +} + +pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> { + let invalid = || { + Error::Runtime { + message: "PREWARM did not return a single (job_id, table_version) receipt; inspect jobs before retrying because work may already have been submitted".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 id = batch + .column_by_name("job_id") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + let version = batch + .column_by_name("table_version") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if id.is_null(0) || id.value(0).is_empty() || version.is_null(0) { + return Err(invalid()); + } + Ok((id.value(0).into(), version.value(0))) +} + +/// 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 arrow_schema::{DataType, Field, Schema}; + 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:?}"); + } + } + + fn batch(ids: Vec>, versions: Vec>) -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "job_id", + Arc::new(StringArray::from(ids)) as arrow_array::ArrayRef, + ), + ( + "table_version", + Arc::new(UInt64Array::from(versions)) as arrow_array::ArrayRef, + ), + ]) + .unwrap() + } + + #[test] + fn receipt_requires_one_non_null_job_and_version() { + assert_eq!( + receipt(&[batch(vec![Some("job-1")], vec![Some(42)])]).unwrap(), + ("job-1".into(), 42) + ); + for batches in [ + vec![], + vec![batch(vec![], vec![])], + vec![batch(vec![None], vec![Some(42)])], + vec![batch(vec![Some("")], vec![Some(42)])], + vec![batch(vec![Some("job")], vec![None])], + vec![batch(vec![Some("a"), Some("b")], vec![Some(1), Some(2)])], + vec![ + batch(vec![Some("a")], vec![Some(1)]), + batch(vec![Some("b")], vec![Some(2)]), + ], + vec![RecordBatch::new_empty(Arc::new(Schema::new(vec![ + Field::new("wrong", DataType::Utf8, false), + ])))], + ] { + let error = receipt(&batches).unwrap_err().to_string(); + assert!(error.contains("inspect jobs before retrying"), "{error}"); + } + } + + #[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/sql.rs b/rust/lancedb/src/sql.rs index bda5df085..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 { @@ -73,8 +90,9 @@ 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. +/// 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`. diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 00505220b..0728484da 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,10 +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; @@ -107,6 +115,7 @@ 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, @@ -278,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, } @@ -688,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. @@ -881,6 +911,28 @@ 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 { @@ -969,6 +1021,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { } 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( @@ -980,6 +1041,28 @@ 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 @@ -999,6 +1082,20 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { 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 { @@ -1840,10 +1937,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. @@ -1910,8 +2014,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; @@ -2043,6 +2149,66 @@ impl Table { 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( @@ -2207,10 +2373,10 @@ impl Table { /// [`RefreshColumnOptions::publication_interval_rows()`] sets an opt-in /// row-count publication threshold for completed Function outputs; unset /// keeps whole-fragment publication. - /// [`RefreshColumnOptions::resource_budget()`] sets the aggregate CPU, + /// [`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 + /// [`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 @@ -2267,6 +2433,25 @@ 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 @@ -2275,9 +2460,9 @@ impl Table { /// [`RefreshColumnOptions::publication_interval_rows()`] to publish /// completed Function outputs at a row-count threshold; unset keeps /// whole-fragment publication. Set - /// [`RefreshColumnOptions::resource_budget()`] to pass a complete aggregate + /// [`RefreshColumnOptions::total_memory_bytes()`] to pass a complete aggregate /// CPU, memory, and GPU budget for a Function refresh. The standalone - /// [`RefreshColumnOptions::gpu_count()`] shorthand and + /// [`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 @@ -2285,6 +2470,30 @@ impl Table { /// 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}; /// # async fn refresh(table: &Table) -> Result<(), Box> { @@ -2293,7 +2502,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(()) @@ -2388,6 +2597,9 @@ impl Table { /// 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. @@ -2413,6 +2625,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 @@ -2578,9 +2846,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, @@ -2692,6 +2967,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 @@ -2985,8 +3302,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 @@ -2998,6 +3316,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( @@ -3448,7 +3824,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, }; @@ -3459,9 +3835,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) @@ -3670,10 +4086,9 @@ impl NativeTable { 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(); @@ -3683,17 +4098,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() { @@ -3877,10 +4315,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 { @@ -3910,6 +4356,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( @@ -3922,6 +4377,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 } @@ -5498,6 +5961,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(); diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index a76c0d043..1e859ea90 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -180,9 +180,13 @@ impl AddColumnsBuilder { /// # 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), - /// auto_refresh_resource_budget: None, + /// total_cpu_millis: None, + /// total_memory_bytes: None, + /// total_gpu_count: None, /// }).execute().await?; /// # Ok(()) /// # } @@ -202,7 +206,7 @@ impl AddColumnsBuilder { read_columns, options, } = self; - if let Some(options) = options { + if let Some(options) = &options { options.validate()?; if computed.is_empty() && function.is_none() { return Err(Error::InvalidInput { @@ -210,11 +214,9 @@ impl AddColumnsBuilder { .into(), }); } - if options.auto_refresh_resource_budget.is_some() && function.is_none() { + if options.has_resource_defaults() && function.is_none() { return Err(Error::InvalidInput { - message: - "auto_refresh_resource_budget requires a registered Function declaration" - .into(), + message: "total_* resources require a registered Function declaration".into(), }); } } @@ -297,14 +299,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), - auto_refresh_resource_budget: None, + 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(); @@ -320,7 +326,7 @@ mod tests { for interval in [0, u64::MAX] { let invalid = ComputedColumnOptions { auto_refresh_interval_seconds: Some(interval), - ..options + ..options.clone() }; assert!( table @@ -339,7 +345,7 @@ mod tests { "once".into(), "x".into() )])) - .computed_options(options) + .computed_options(options.clone()) .execute() .await .is_err() @@ -391,11 +397,13 @@ mod tests { .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, - auto_refresh_resource_budget: Some( - crate::table::FunctionWorkerResourceBudget::new(1_000, 1_024), - ), + total_cpu_millis: Some(1000), + total_memory_bytes: Some(1024), + total_gpu_count: Some(0), }) .execute() .await 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 a87c38f3c..d1ec7d237 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -42,7 +42,6 @@ use serde_json::Value; use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding, OutputMapping}; use crate::materialized_view::without_declarations; -use crate::table::FunctionWorkerResourceBudget; use crate::utils::resolve_arrow_field_path; use crate::{Error, Result}; @@ -62,13 +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"; -/// Aggregate worker-resource budget for automatic Function refreshes. -pub const AUTO_REFRESH_RESOURCE_BUDGET_META_KEY: &str = - "computed_column.auto_refresh_resource_budget"; - /// 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. @@ -77,10 +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, - /// Aggregate worker-resource budget for automatic Function refreshes. - /// This option requires a registered Function output. + /// Default total CPU budget in millicores for manual and automatic refreshes. + /// Requires a registered Function output. #[serde(skip_serializing_if = "Option::is_none")] - pub auto_refresh_resource_budget: Option, + 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 { @@ -88,12 +95,24 @@ impl Default for ComputedColumnOptions { Self { auto_refresh_enabled: true, auto_refresh_interval_seconds: None, - auto_refresh_resource_budget: 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 @@ -104,8 +123,28 @@ impl ComputedColumnOptions { message: "auto_refresh_interval_seconds must be a positive integer no greater than u64::MAX / 1000".into(), }); } - if let Some(budget) = &self.auto_refresh_resource_budget { - budget.validate()?; + 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(()) } @@ -124,15 +163,29 @@ impl ComputedColumnOptions { message: "auto_refresh_interval_seconds must be a positive integer".into(), })?); } - if let Some(value) = metadata.get(AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) { - options.auto_refresh_resource_budget = Some(serde_json::from_str(value).map_err( - |error| Error::InvalidInput { - message: format!( - "auto_refresh_resource_budget must be a valid resource budget: {error}" - ), - }, - )?); + 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) } @@ -175,13 +228,20 @@ impl ComputedColumnOptions { if let Some(interval) = self.auto_refresh_interval_seconds { metadata.insert(AUTO_REFRESH_INTERVAL_META_KEY.into(), interval.to_string()); } - if let Some(budget) = &self.auto_refresh_resource_budget { - metadata.insert( - AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), - serde_json::to_string(budget).map_err(|error| Error::InvalidInput { - message: format!("failed to encode auto_refresh_resource_budget: {error}"), - })?, - ); + 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) } @@ -2702,68 +2762,70 @@ 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 computed_auto_refresh_resource_budget_metadata_round_trips() { - let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) - .with_gpu_count(2); + fn gpu_worker_defaults_round_trip_independently_of_totals() { let options = super::ComputedColumnOptions { - auto_refresh_enabled: true, - auto_refresh_interval_seconds: Some(300), - auto_refresh_resource_budget: Some(budget), + gpu_class: Some("any".into()), + gpu_count: Some(2), + total_gpu_count: Some(8), + ..Default::default() }; - assert_eq!( - super::ComputedColumnOptions::from_metadata(&HashMap::new()).unwrap(), - super::ComputedColumnOptions::default() - ); let metadata = options.metadata().unwrap(); - assert_eq!( - metadata - .get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) - .map(String::as_str), - Some(r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":2}"#) - ); + 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 ); - - let mut omitted_gpu = metadata.clone(); - omitted_gpu.insert( - super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), - r#"{"cpu_millis":8000,"memory_bytes":17179869184}"#.into(), + assert!( + super::ComputedColumnOptions { + gpu_count: Some(0), + ..Default::default() + } + .validate() + .is_err() ); - let decoded = super::ComputedColumnOptions::from_metadata(&omitted_gpu).unwrap(); - assert_eq!(decoded.auto_refresh_resource_budget.unwrap().gpu_count, 0); + 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!( - decoded - .metadata() - .unwrap() - .get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) - .map(String::as_str), - Some(r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":0}"#) + super::ComputedColumnOptions::from_metadata(&metadata).unwrap(), + options ); - - for invalid in [ - r#"{"memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":8000,"gpu_count":2}"#, - r#"{"cpu_millis":"8000","memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":-1,"memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":18446744073709551616,"memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":-1}"#, - r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":4294967296}"#, - r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":2,"unknown":1}"#, - r#"{"cpu_millis":0,"memory_bytes":17179869184,"gpu_count":2}"#, - r#"{"cpu_millis":8000,"memory_bytes":0,"gpu_count":2}"#, - ] { - let mut malformed = metadata.clone(); - malformed.insert( - super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), - invalid.into(), - ); - assert!( - super::ComputedColumnOptions::from_metadata(&malformed).is_err(), - "accepted invalid budget: {invalid}" - ); + 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()); } } @@ -2797,9 +2859,11 @@ mod tests { function_field("assignment", super::FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL), ]); let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) - .with_gpu_count(2); + .with_total_gpu_count(2); let updated = super::ComputedColumnOptions { - auto_refresh_resource_budget: Some(budget), + 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) @@ -2808,8 +2872,8 @@ mod tests { for name in ["first", "second"] { let metadata = updated.field_with_name(name).unwrap().metadata(); assert_eq!( - metadata.get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY), - Some(&serde_json::to_string(&budget).unwrap()) + metadata.get("computed_column.total_cpu_millis"), + Some(&"8000".to_string()) ); assert_eq!( metadata.get("custom").map(String::as_str), @@ -2821,7 +2885,7 @@ mod tests { .field_with_name("assignment") .unwrap() .metadata() - .contains_key(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) + .contains_key("computed_column.total_cpu_millis") ); } @@ -2928,16 +2992,6 @@ 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}; - 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(); 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/optimize.rs b/rust/lancedb/src/table/optimize.rs index ab34e05c6..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>, } @@ -261,8 +290,11 @@ pub enum OptimizeAction { /// 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 and may perform no work when - /// the first task exceeds it. Zero I/O buffer size disables byte-based I/O + /// 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. @@ -298,10 +330,11 @@ pub enum OptimizeAction { /// # } /// ``` /// - /// 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. + /// 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>, 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 7d98dc001..4dd8df294 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -120,10 +120,20 @@ 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().has_take() { + // 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()) @@ -146,6 +156,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, @@ -169,10 +220,12 @@ pub async fn create_plan( options: QueryExecutionOptions, ) -> Result> { let query = query.canonicalized()?; + validate_scan_in_order(&query)?; if let AnyQuery::Query(request) = &query && request.has_take() { - return crate::query::create_take_plan(table, request, options, false).await; + return crate::query::create_take_plan(table, request, options, request.preserve_order) + .await; } let query = match query { @@ -426,6 +479,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 @@ -1182,6 +1246,21 @@ mod tests { FixedSizeListArray::try_new_from_values(Float32Array::from(values), dimension).unwrap() } + fn collect_i32(batches: &[RecordBatch]) -> 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}; @@ -1858,6 +1937,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; @@ -2399,4 +2532,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 400df6c82..eddb4d0c0 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -183,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 diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index f6bab98f5..bf0c84e8f 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -65,39 +65,39 @@ use crate::{Error, Result}; #[serde(deny_unknown_fields)] #[non_exhaustive] pub struct FunctionWorkerResourceBudget { - pub cpu_millis: u64, - pub memory_bytes: u64, + pub total_cpu_millis: u64, + pub total_memory_bytes: u64, /// Aggregate GPU budget across the refresh. Zero is CPU-only. #[serde(default)] - pub gpu_count: u32, + pub total_gpu_count: u32, } impl FunctionWorkerResourceBudget { /// Create a CPU-only aggregate budget. - pub fn new(cpu_millis: u64, memory_bytes: u64) -> Self { + pub fn new(total_cpu_millis: u64, total_memory_bytes: u64) -> Self { Self { - cpu_millis, - memory_bytes, - gpu_count: 0, + total_cpu_millis, + total_memory_bytes, + total_gpu_count: 0, } } /// Set the aggregate GPU budget. - pub fn with_gpu_count(mut self, gpu_count: u32) -> Self { - self.gpu_count = gpu_count; + 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.cpu_millis == 0 { + if self.total_cpu_millis == 0 { return Err(Error::InvalidInput { - message: "resource_budget.cpu_millis must be greater than zero".into(), + message: "total_cpu_millis must be greater than zero".into(), }); } - if self.memory_bytes == 0 { + if self.total_memory_bytes == 0 { return Err(Error::InvalidInput { - message: "resource_budget.memory_bytes must be greater than zero".into(), + message: "total_memory_bytes must be greater than zero".into(), }); } Ok(()) @@ -212,9 +212,30 @@ impl FunctionRefreshPlanningConfig { #[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, @@ -252,7 +273,7 @@ pub struct RefreshColumnOptions { /// 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 `resource_budget`. + /// 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. @@ -263,10 +284,12 @@ pub struct RefreshColumnOptions { /// rejects this option. #[serde(skip_serializing_if = "Option::is_none")] pub publication_interval_rows: Option, - /// Complete aggregate CPU, memory, and GPU budget for a registered - /// Function refresh. Cannot be combined with `gpu_count`. + /// Total CPU budget for this execution, in millicores. #[serde(skip_serializing_if = "Option::is_none")] - pub resource_budget: Option, + 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")] @@ -281,15 +304,51 @@ pub struct RefreshColumnOptions { /// 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()); @@ -326,6 +385,12 @@ impl RefreshColumnOptions { 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); @@ -363,12 +428,15 @@ impl RefreshColumnOptions { self } - /// Set the aggregate worker resource budget for a Function refresh. - /// - /// Use [`FunctionWorkerResourceBudget::new`] for a CPU-only budget, or - /// [`FunctionWorkerResourceBudget::with_gpu_count`] to include GPUs. - pub fn resource_budget(mut self, budget: FunctionWorkerResourceBudget) -> Self { - self.resource_budget = Some(budget); + /// 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 } @@ -390,15 +458,27 @@ impl RefreshColumnOptions { 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()), @@ -407,6 +487,7 @@ impl RefreshColumnOptions { ("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(), @@ -416,7 +497,9 @@ impl RefreshColumnOptions { "publication_interval_rows", self.publication_interval_rows.is_some(), ), - ("resource_budget", self.resource_budget.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()), ] @@ -426,6 +509,31 @@ impl RefreshColumnOptions { /// 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() @@ -461,6 +569,11 @@ impl RefreshColumnOptions { 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(), @@ -481,14 +594,12 @@ impl RefreshColumnOptions { message: "publication_interval_rows must be greater than zero".into(), }); } - if self.resource_budget.is_some() && self.gpu_count.is_some() { + if self.total_cpu_millis == Some(0) || self.total_memory_bytes == Some(0) { return Err(Error::InvalidInput { - message: "gpu_count cannot be combined with resource_budget".into(), + message: "total_cpu_millis and total_memory_bytes must be positive integers".into(), }); } - if let Some(budget) = &self.resource_budget { - budget.validate()?; - } + if let Some(resources) = &self.supervisor_resources { resources.validate("supervisor_resources")?; } @@ -500,9 +611,19 @@ impl RefreshColumnOptions { } 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(()) } } @@ -780,6 +901,8 @@ 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, @@ -2718,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/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/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index 829486015..10114cbad 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -85,6 +85,9 @@ fn execution_controls_require_their_positive_ranges() { ("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)), ] { 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/rust/lancedb/vendor/lance-linalg/Cargo.toml b/rust/lancedb/vendor/lance-linalg/Cargo.toml index 867cd9561..e9b2f2d9a 100644 --- a/rust/lancedb/vendor/lance-linalg/Cargo.toml +++ b/rust/lancedb/vendor/lance-linalg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lance-linalg" -version = "15.0.0-beta.25" +version = "15.0.0-beta.26" publish = false edition = { workspace = true } license = { workspace = true } diff --git a/rust/lancedb/vendor/lance-linalg/README.lancedb.md b/rust/lancedb/vendor/lance-linalg/README.lancedb.md index ca1818740..96e9052a8 100644 --- a/rust/lancedb/vendor/lance-linalg/README.lancedb.md +++ b/rust/lancedb/vendor/lance-linalg/README.lancedb.md @@ -1,5 +1,5 @@ -This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.25` -(commit `f5dbd55dd79f1f0412f897ed1917128300fb8c1a`), licensed under Apache-2.0. +This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.26` +(commit `f9fd19edfb14e43d3981b20dfaf183672751414b`), licensed under Apache-2.0. LanceDB patches `src/distance/cosine.rs` to recompute FLOAT32 cosine distances in FLOAT64 when squared norms or dot products overflow or underflow. Ordinary 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 "$@"